• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "stack_map_stream.h"
18 
19 #include <memory>
20 #include <vector>
21 
22 #include "art_method-inl.h"
23 #include "base/stl_util.h"
24 #include "class_linker.h"
25 #include "dex/dex_file.h"
26 #include "dex/dex_file_types.h"
27 #include "driver/compiler_options.h"
28 #include "optimizing/code_generator.h"
29 #include "optimizing/nodes.h"
30 #include "optimizing/optimizing_compiler.h"
31 #include "runtime.h"
32 #include "scoped_thread_state_change-inl.h"
33 #include "stack_map.h"
34 
35 namespace art {
36 
37 constexpr static bool kVerifyStackMaps = kIsDebugBuild;
38 
GetStackMapNativePcOffset(size_t i)39 uint32_t StackMapStream::GetStackMapNativePcOffset(size_t i) {
40   return StackMap::UnpackNativePc(stack_maps_[i][StackMap::kPackedNativePc], instruction_set_);
41 }
42 
SetStackMapNativePcOffset(size_t i,uint32_t native_pc_offset)43 void StackMapStream::SetStackMapNativePcOffset(size_t i, uint32_t native_pc_offset) {
44   stack_maps_[i][StackMap::kPackedNativePc] =
45       StackMap::PackNativePc(native_pc_offset, instruction_set_);
46 }
47 
BeginMethod(size_t frame_size_in_bytes,size_t core_spill_mask,size_t fp_spill_mask,uint32_t num_dex_registers,bool baseline)48 void StackMapStream::BeginMethod(size_t frame_size_in_bytes,
49                                  size_t core_spill_mask,
50                                  size_t fp_spill_mask,
51                                  uint32_t num_dex_registers,
52                                  bool baseline) {
53   DCHECK(!in_method_) << "Mismatched Begin/End calls";
54   in_method_ = true;
55   DCHECK_EQ(packed_frame_size_, 0u) << "BeginMethod was already called";
56 
57   DCHECK_ALIGNED(frame_size_in_bytes, kStackAlignment);
58   packed_frame_size_ = frame_size_in_bytes / kStackAlignment;
59   core_spill_mask_ = core_spill_mask;
60   fp_spill_mask_ = fp_spill_mask;
61   num_dex_registers_ = num_dex_registers;
62   baseline_ = baseline;
63 
64   if (kVerifyStackMaps) {
65     dchecks_.emplace_back([=](const CodeInfo& code_info) {
66       DCHECK_EQ(code_info.packed_frame_size_, frame_size_in_bytes / kStackAlignment);
67       DCHECK_EQ(code_info.core_spill_mask_, core_spill_mask);
68       DCHECK_EQ(code_info.fp_spill_mask_, fp_spill_mask);
69       DCHECK_EQ(code_info.number_of_dex_registers_, num_dex_registers);
70     });
71   }
72 }
73 
EndMethod(size_t code_size)74 void StackMapStream::EndMethod(size_t code_size) {
75   DCHECK(in_method_) << "Mismatched Begin/End calls";
76   in_method_ = false;
77   code_size_ = code_size;
78 
79   // Read the stack masks now. The compiler might have updated them.
80   for (size_t i = 0; i < lazy_stack_masks_.size(); i++) {
81     BitVector* stack_mask = lazy_stack_masks_[i];
82     if (stack_mask != nullptr && stack_mask->GetNumberOfBits() != 0) {
83       stack_maps_[i][StackMap::kStackMaskIndex] =
84           stack_masks_.Dedup(stack_mask->GetRawStorage(), stack_mask->GetNumberOfBits());
85     }
86   }
87 
88   if (kIsDebugBuild) {
89     uint32_t packed_code_size = StackMap::PackNativePc(code_size, instruction_set_);
90     for (size_t i = 0; i < stack_maps_.size(); i++) {
91       DCHECK_LE(stack_maps_[i][StackMap::kPackedNativePc], packed_code_size);
92     }
93   }
94 
95   if (kVerifyStackMaps) {
96     dchecks_.emplace_back([=](const CodeInfo& code_info) {
97         CHECK_EQ(code_info.code_size_, code_size);
98     });
99   }
100 }
101 
BeginStackMapEntry(uint32_t dex_pc,uint32_t native_pc_offset,uint32_t register_mask,BitVector * stack_mask,StackMap::Kind kind,bool needs_vreg_info)102 void StackMapStream::BeginStackMapEntry(uint32_t dex_pc,
103                                         uint32_t native_pc_offset,
104                                         uint32_t register_mask,
105                                         BitVector* stack_mask,
106                                         StackMap::Kind kind,
107                                         bool needs_vreg_info) {
108   DCHECK(in_method_) << "Call BeginMethod first";
109   DCHECK(!in_stack_map_) << "Mismatched Begin/End calls";
110   in_stack_map_ = true;
111 
112   current_stack_map_ = BitTableBuilder<StackMap>::Entry();
113   current_stack_map_[StackMap::kKind] = static_cast<uint32_t>(kind);
114   current_stack_map_[StackMap::kPackedNativePc] =
115       StackMap::PackNativePc(native_pc_offset, instruction_set_);
116   current_stack_map_[StackMap::kDexPc] = dex_pc;
117   if (stack_maps_.size() > 0) {
118     // Check that non-catch stack maps are sorted by pc.
119     // Catch stack maps are at the end and may be unordered.
120     if (stack_maps_.back()[StackMap::kKind] == StackMap::Kind::Catch) {
121       DCHECK(current_stack_map_[StackMap::kKind] == StackMap::Kind::Catch);
122     } else if (current_stack_map_[StackMap::kKind] != StackMap::Kind::Catch) {
123       DCHECK_LE(stack_maps_.back()[StackMap::kPackedNativePc],
124                 current_stack_map_[StackMap::kPackedNativePc]);
125     }
126   }
127   if (register_mask != 0) {
128     uint32_t shift = LeastSignificantBit(register_mask);
129     BitTableBuilder<RegisterMask>::Entry entry;
130     entry[RegisterMask::kValue] = register_mask >> shift;
131     entry[RegisterMask::kShift] = shift;
132     current_stack_map_[StackMap::kRegisterMaskIndex] = register_masks_.Dedup(&entry);
133   }
134   // The compiler assumes the bit vector will be read during PrepareForFillIn(),
135   // and it might modify the data before that. Therefore, just store the pointer.
136   // See ClearSpillSlotsFromLoopPhisInStackMap in code_generator.h.
137   lazy_stack_masks_.push_back(stack_mask);
138   current_inline_infos_.clear();
139   current_dex_registers_.clear();
140   expected_num_dex_registers_ = needs_vreg_info  ? num_dex_registers_ : 0u;
141 
142   if (kVerifyStackMaps) {
143     size_t stack_map_index = stack_maps_.size();
144     // Create lambda method, which will be executed at the very end to verify data.
145     // Parameters and local variables will be captured(stored) by the lambda "[=]".
146     dchecks_.emplace_back([=](const CodeInfo& code_info) {
147       if (kind == StackMap::Kind::Default || kind == StackMap::Kind::OSR) {
148         StackMap stack_map = code_info.GetStackMapForNativePcOffset(native_pc_offset,
149                                                                     instruction_set_);
150         CHECK_EQ(stack_map.Row(), stack_map_index);
151       } else if (kind == StackMap::Kind::Catch) {
152         StackMap stack_map = code_info.GetCatchStackMapForDexPc(dex_pc);
153         CHECK_EQ(stack_map.Row(), stack_map_index);
154       }
155       StackMap stack_map = code_info.GetStackMapAt(stack_map_index);
156       CHECK_EQ(stack_map.GetNativePcOffset(instruction_set_), native_pc_offset);
157       CHECK_EQ(stack_map.GetKind(), static_cast<uint32_t>(kind));
158       CHECK_EQ(stack_map.GetDexPc(), dex_pc);
159       CHECK_EQ(code_info.GetRegisterMaskOf(stack_map), register_mask);
160       BitMemoryRegion seen_stack_mask = code_info.GetStackMaskOf(stack_map);
161       CHECK_GE(seen_stack_mask.size_in_bits(), stack_mask ? stack_mask->GetNumberOfBits() : 0);
162       for (size_t b = 0; b < seen_stack_mask.size_in_bits(); b++) {
163         CHECK_EQ(seen_stack_mask.LoadBit(b), stack_mask != nullptr && stack_mask->IsBitSet(b));
164       }
165     });
166   }
167 }
168 
EndStackMapEntry()169 void StackMapStream::EndStackMapEntry() {
170   DCHECK(in_stack_map_) << "Mismatched Begin/End calls";
171   in_stack_map_ = false;
172 
173   // Generate index into the InlineInfo table.
174   size_t inlining_depth = current_inline_infos_.size();
175   if (!current_inline_infos_.empty()) {
176     current_inline_infos_.back()[InlineInfo::kIsLast] = InlineInfo::kLast;
177     current_stack_map_[StackMap::kInlineInfoIndex] =
178         inline_infos_.Dedup(current_inline_infos_.data(), current_inline_infos_.size());
179   }
180 
181   // Generate delta-compressed dex register map.
182   size_t num_dex_registers = current_dex_registers_.size();
183   if (!current_dex_registers_.empty()) {
184     DCHECK_EQ(expected_num_dex_registers_, current_dex_registers_.size());
185     CreateDexRegisterMap();
186   }
187 
188   stack_maps_.Add(current_stack_map_);
189 
190   if (kVerifyStackMaps) {
191     size_t stack_map_index = stack_maps_.size() - 1;
192     dchecks_.emplace_back([=](const CodeInfo& code_info) {
193       StackMap stack_map = code_info.GetStackMapAt(stack_map_index);
194       CHECK_EQ(stack_map.HasDexRegisterMap(), (num_dex_registers != 0));
195       CHECK_EQ(stack_map.HasInlineInfo(), (inlining_depth != 0));
196       CHECK_EQ(code_info.GetInlineInfosOf(stack_map).size(), inlining_depth);
197     });
198   }
199 }
200 
BeginInlineInfoEntry(ArtMethod * method,uint32_t dex_pc,uint32_t num_dex_registers,const DexFile * outer_dex_file,const CodeGenerator * codegen)201 void StackMapStream::BeginInlineInfoEntry(ArtMethod* method,
202                                           uint32_t dex_pc,
203                                           uint32_t num_dex_registers,
204                                           const DexFile* outer_dex_file,
205                                           const CodeGenerator* codegen) {
206   DCHECK(in_stack_map_) << "Call BeginStackMapEntry first";
207   DCHECK(!in_inline_info_) << "Mismatched Begin/End calls";
208   in_inline_info_ = true;
209   DCHECK_EQ(expected_num_dex_registers_, current_dex_registers_.size());
210 
211   expected_num_dex_registers_ += num_dex_registers;
212 
213   BitTableBuilder<InlineInfo>::Entry entry;
214   entry[InlineInfo::kIsLast] = InlineInfo::kMore;
215   entry[InlineInfo::kDexPc] = dex_pc;
216   entry[InlineInfo::kNumberOfDexRegisters] = static_cast<uint32_t>(expected_num_dex_registers_);
217   if (EncodeArtMethodInInlineInfo(method)) {
218     entry[InlineInfo::kArtMethodHi] = High32Bits(reinterpret_cast<uintptr_t>(method));
219     entry[InlineInfo::kArtMethodLo] = Low32Bits(reinterpret_cast<uintptr_t>(method));
220   } else {
221     uint32_t is_in_bootclasspath = MethodInfo::kKindNonBCP;
222     uint32_t dexfile_index = MethodInfo::kSameDexFile;
223     if (dex_pc != static_cast<uint32_t>(-1)) {
224       ScopedObjectAccess soa(Thread::Current());
225       const DexFile* dex_file = method->GetDexFile();
226       if (!IsSameDexFile(*outer_dex_file, *dex_file)) {
227         if (method->GetDeclaringClass()->IsBootStrapClassLoaded()) {
228           ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
229           const std::vector<const DexFile*>& boot_class_path = class_linker->GetBootClassPath();
230           auto it = std::find_if(
231               boot_class_path.begin(), boot_class_path.end(), [dex_file](const DexFile* df) {
232                 return IsSameDexFile(*df, *dex_file);
233               });
234           is_in_bootclasspath = MethodInfo::kKindBCP;
235           dexfile_index = std::distance(boot_class_path.begin(), it);
236         } else {
237           const std::vector<const DexFile*>& dex_files =
238               codegen->GetCompilerOptions().GetDexFilesForOatFile();
239           auto it = std::find_if(dex_files.begin(), dex_files.end(), [dex_file](const DexFile* df) {
240             return IsSameDexFile(*df, *dex_file);
241           });
242           // No need to set is_in_bootclasspath since the default value works.
243           dexfile_index = std::distance(dex_files.begin(), it);
244         }
245       }
246     }
247     uint32_t dex_method_index = method->GetDexMethodIndex();
248     entry[InlineInfo::kMethodInfoIndex] =
249         method_infos_.Dedup({dex_method_index, is_in_bootclasspath, dexfile_index});
250   }
251   current_inline_infos_.push_back(entry);
252 
253   if (kVerifyStackMaps) {
254     size_t stack_map_index = stack_maps_.size();
255     size_t depth = current_inline_infos_.size() - 1;
256     dchecks_.emplace_back([=](const CodeInfo& code_info) {
257       StackMap stack_map = code_info.GetStackMapAt(stack_map_index);
258       InlineInfo inline_info = code_info.GetInlineInfosOf(stack_map)[depth];
259       CHECK_EQ(inline_info.GetDexPc(), dex_pc);
260       bool encode_art_method = EncodeArtMethodInInlineInfo(method);
261       CHECK_EQ(inline_info.EncodesArtMethod(), encode_art_method);
262       if (encode_art_method) {
263         CHECK_EQ(inline_info.GetArtMethod(), method);
264       } else {
265         MethodInfo method_info = code_info.GetMethodInfoOf(inline_info);
266         CHECK_EQ(method_info.GetMethodIndex(), method->GetDexMethodIndex());
267         CHECK(method_info.GetDexFileIndexKind() == MethodInfo::kKindNonBCP ||
268               method_info.GetDexFileIndexKind() == MethodInfo::kKindBCP);
269         ScopedObjectAccess soa(Thread::Current());
270         if (inline_info.GetDexPc() != static_cast<uint32_t>(-1) &&
271             !IsSameDexFile(*outer_dex_file, *method->GetDexFile())) {
272           if (method->GetDeclaringClass()->IsBootStrapClassLoaded()) {
273             CHECK_EQ(method_info.GetDexFileIndexKind(), MethodInfo::kKindBCP);
274             ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
275             const std::vector<const DexFile*>& boot_class_path = class_linker->GetBootClassPath();
276             DCHECK_LT(method_info.GetDexFileIndex(), boot_class_path.size());
277             CHECK(IsSameDexFile(*boot_class_path[method_info.GetDexFileIndex()],
278                                 *method->GetDexFile()));
279           } else {
280             CHECK_EQ(method_info.GetDexFileIndexKind(), MethodInfo::kKindNonBCP);
281             const std::vector<const DexFile*>& dex_files =
282                 codegen->GetCompilerOptions().GetDexFilesForOatFile();
283             DCHECK_LT(method_info.GetDexFileIndex(), dex_files.size());
284             CHECK(IsSameDexFile(*dex_files[method_info.GetDexFileIndex()], *method->GetDexFile()));
285           }
286         }
287       }
288     });
289   }
290 }
291 
EndInlineInfoEntry()292 void StackMapStream::EndInlineInfoEntry() {
293   DCHECK(in_inline_info_) << "Mismatched Begin/End calls";
294   in_inline_info_ = false;
295   DCHECK_EQ(expected_num_dex_registers_, current_dex_registers_.size());
296 }
297 
298 // Create delta-compressed dex register map based on the current list of DexRegisterLocations.
299 // All dex registers for a stack map are concatenated - inlined registers are just appended.
CreateDexRegisterMap()300 void StackMapStream::CreateDexRegisterMap() {
301   // These are fields rather than local variables so that we can reuse the reserved memory.
302   temp_dex_register_mask_.ClearAllBits();
303   temp_dex_register_map_.clear();
304 
305   // Ensure that the arrays that hold previous state are big enough to be safely indexed below.
306   if (previous_dex_registers_.size() < current_dex_registers_.size()) {
307     previous_dex_registers_.resize(current_dex_registers_.size(), DexRegisterLocation::None());
308     dex_register_timestamp_.resize(current_dex_registers_.size(), 0u);
309   }
310 
311   // Set bit in the mask for each register that has been changed since the previous stack map.
312   // Modified registers are stored in the catalogue and the catalogue index added to the list.
313   for (size_t i = 0; i < current_dex_registers_.size(); i++) {
314     DexRegisterLocation reg = current_dex_registers_[i];
315     // Distance is difference between this index and the index of last modification.
316     uint32_t distance = stack_maps_.size() - dex_register_timestamp_[i];
317     if (previous_dex_registers_[i] != reg || distance > kMaxDexRegisterMapSearchDistance) {
318       BitTableBuilder<DexRegisterInfo>::Entry entry;
319       entry[DexRegisterInfo::kKind] = static_cast<uint32_t>(reg.GetKind());
320       entry[DexRegisterInfo::kPackedValue] =
321           DexRegisterInfo::PackValue(reg.GetKind(), reg.GetValue());
322       uint32_t index = reg.IsLive() ? dex_register_catalog_.Dedup(&entry) : kNoValue;
323       temp_dex_register_mask_.SetBit(i);
324       temp_dex_register_map_.push_back({index});
325       previous_dex_registers_[i] = reg;
326       dex_register_timestamp_[i] = stack_maps_.size();
327     }
328   }
329 
330   // Set the mask and map for the current StackMap (which includes inlined registers).
331   if (temp_dex_register_mask_.GetNumberOfBits() != 0) {
332     current_stack_map_[StackMap::kDexRegisterMaskIndex] =
333         dex_register_masks_.Dedup(temp_dex_register_mask_.GetRawStorage(),
334                                   temp_dex_register_mask_.GetNumberOfBits());
335   }
336   if (!current_dex_registers_.empty()) {
337     current_stack_map_[StackMap::kDexRegisterMapIndex] =
338         dex_register_maps_.Dedup(temp_dex_register_map_.data(),
339                                  temp_dex_register_map_.size());
340   }
341 
342   if (kVerifyStackMaps) {
343     size_t stack_map_index = stack_maps_.size();
344     // We need to make copy of the current registers for later (when the check is run).
345     auto expected_dex_registers = std::make_shared<dchecked_vector<DexRegisterLocation>>(
346         current_dex_registers_.begin(), current_dex_registers_.end());
347     dchecks_.emplace_back([=](const CodeInfo& code_info) {
348       StackMap stack_map = code_info.GetStackMapAt(stack_map_index);
349       uint32_t expected_reg = 0;
350       for (DexRegisterLocation reg : code_info.GetDexRegisterMapOf(stack_map)) {
351         CHECK_EQ((*expected_dex_registers)[expected_reg++], reg);
352       }
353       for (InlineInfo inline_info : code_info.GetInlineInfosOf(stack_map)) {
354         DexRegisterMap map = code_info.GetInlineDexRegisterMapOf(stack_map, inline_info);
355         for (DexRegisterLocation reg : map) {
356           CHECK_EQ((*expected_dex_registers)[expected_reg++], reg);
357         }
358       }
359       CHECK_EQ(expected_reg, expected_dex_registers->size());
360     });
361   }
362 }
363 
Encode()364 ScopedArenaVector<uint8_t> StackMapStream::Encode() {
365   DCHECK(in_stack_map_ == false) << "Mismatched Begin/End calls";
366   DCHECK(in_inline_info_ == false) << "Mismatched Begin/End calls";
367 
368   uint32_t flags = (inline_infos_.size() > 0) ? CodeInfo::kHasInlineInfo : 0;
369   flags |= baseline_ ? CodeInfo::kIsBaseline : 0;
370   DCHECK_LE(flags, kVarintMax);  // Ensure flags can be read directly as byte.
371   uint32_t bit_table_flags = 0;
372   ForEachBitTable([&bit_table_flags](size_t i, auto bit_table) {
373     if (bit_table->size() != 0) {  // Record which bit-tables are stored.
374       bit_table_flags |= 1 << i;
375     }
376   });
377 
378   ScopedArenaVector<uint8_t> buffer(allocator_->Adapter(kArenaAllocStackMapStream));
379   BitMemoryWriter<ScopedArenaVector<uint8_t>> out(&buffer);
380   out.WriteInterleavedVarints(std::array<uint32_t, CodeInfo::kNumHeaders>{
381     flags,
382     code_size_,
383     packed_frame_size_,
384     core_spill_mask_,
385     fp_spill_mask_,
386     num_dex_registers_,
387     bit_table_flags,
388   });
389   ForEachBitTable([&out](size_t, auto bit_table) {
390     if (bit_table->size() != 0) {  // Skip empty bit-tables.
391       bit_table->Encode(out);
392     }
393   });
394 
395   // Verify that we can load the CodeInfo and check some essentials.
396   size_t number_of_read_bits;
397   CodeInfo code_info(buffer.data(), &number_of_read_bits);
398   CHECK_EQ(number_of_read_bits, out.NumberOfWrittenBits());
399   CHECK_EQ(code_info.GetNumberOfStackMaps(), stack_maps_.size());
400   CHECK_EQ(CodeInfo::HasInlineInfo(buffer.data()), inline_infos_.size() > 0);
401   CHECK_EQ(CodeInfo::IsBaseline(buffer.data()), baseline_);
402 
403   // Verify all written data (usually only in debug builds).
404   if (kVerifyStackMaps) {
405     for (const auto& dcheck : dchecks_) {
406       dcheck(code_info);
407     }
408   }
409 
410   return buffer;
411 }
412 
413 }  // namespace art
414