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.h"
18
19 #include <iomanip>
20 #include <stdint.h>
21
22 #include "art_method.h"
23 #include "base/indenter.h"
24 #include "base/stats-inl.h"
25 #include "oat_quick_method_header.h"
26 #include "scoped_thread_state_change-inl.h"
27
28 namespace art {
29
30 // The callback is used to inform the caller about memory bounds of the bit-tables.
31 template<typename DecodeCallback>
CodeInfo(const uint8_t * data,size_t * num_read_bits,DecodeCallback callback)32 CodeInfo::CodeInfo(const uint8_t* data, size_t* num_read_bits, DecodeCallback callback) {
33 BitMemoryReader reader(data);
34 std::array<uint32_t, kNumHeaders> header = reader.ReadInterleavedVarints<kNumHeaders>();
35 ForEachHeaderField([this, &header](size_t i, auto member_pointer) ALWAYS_INLINE {
36 this->*member_pointer = header[i];
37 });
38 ForEachBitTableField([this, &reader, &callback](size_t i, auto member_pointer) ALWAYS_INLINE {
39 auto& table = this->*member_pointer;
40 if (LIKELY(HasBitTable(i))) {
41 if (UNLIKELY(IsBitTableDeduped(i))) {
42 ssize_t bit_offset = reader.NumberOfReadBits() - reader.ReadVarint();
43 BitMemoryReader reader2(reader.data(), bit_offset); // The offset is negative.
44 table.Decode(reader2);
45 callback(i, &table, reader2.GetReadRegion());
46 } else {
47 ssize_t bit_offset = reader.NumberOfReadBits();
48 table.Decode(reader);
49 callback(i, &table, reader.GetReadRegion().Subregion(bit_offset));
50 }
51 }
52 });
53 if (num_read_bits != nullptr) {
54 *num_read_bits = reader.NumberOfReadBits();
55 }
56 }
57
CodeInfo(const uint8_t * data,size_t * num_read_bits)58 CodeInfo::CodeInfo(const uint8_t* data, size_t* num_read_bits)
59 : CodeInfo(data, num_read_bits, [](size_t, auto*, BitMemoryRegion) ALWAYS_INLINE {}) {}
60
CodeInfo(const OatQuickMethodHeader * header)61 CodeInfo::CodeInfo(const OatQuickMethodHeader* header)
62 : CodeInfo(header->GetOptimizedCodeInfoPtr()) {}
63
DecodeGcMasksOnly(const OatQuickMethodHeader * header)64 CodeInfo CodeInfo::DecodeGcMasksOnly(const OatQuickMethodHeader* header) {
65 CodeInfo code_info(header->GetOptimizedCodeInfoPtr());
66 CodeInfo copy; // Copy to dead-code-eliminate all fields that we do not need.
67 copy.stack_maps_ = code_info.stack_maps_;
68 copy.register_masks_ = code_info.register_masks_;
69 copy.stack_masks_ = code_info.stack_masks_;
70 return copy;
71 }
72
DecodeInlineInfoOnly(const OatQuickMethodHeader * header)73 CodeInfo CodeInfo::DecodeInlineInfoOnly(const OatQuickMethodHeader* header) {
74 CodeInfo code_info(header->GetOptimizedCodeInfoPtr());
75 CodeInfo copy; // Copy to dead-code-eliminate all fields that we do not need.
76 copy.number_of_dex_registers_ = code_info.number_of_dex_registers_;
77 copy.stack_maps_ = code_info.stack_maps_;
78 copy.inline_infos_ = code_info.inline_infos_;
79 copy.method_infos_ = code_info.method_infos_;
80 return copy;
81 }
82
GetStackMapForNativePcOffset(uintptr_t pc,InstructionSet isa) const83 StackMap CodeInfo::GetStackMapForNativePcOffset(uintptr_t pc, InstructionSet isa) const {
84 uint32_t packed_pc = StackMap::PackNativePc(pc, isa);
85 // Binary search. All catch stack maps are stored separately at the end.
86 auto it = std::partition_point(
87 stack_maps_.begin(),
88 stack_maps_.end(),
89 [packed_pc](const StackMap& sm) {
90 return sm.GetPackedNativePc() < packed_pc && sm.GetKind() != StackMap::Kind::Catch;
91 });
92 // Start at the lower bound and iterate over all stack maps with the given native pc.
93 for (; it != stack_maps_.end() && (*it).GetNativePcOffset(isa) == pc; ++it) {
94 StackMap::Kind kind = static_cast<StackMap::Kind>((*it).GetKind());
95 if (kind == StackMap::Kind::Default || kind == StackMap::Kind::OSR) {
96 return *it;
97 }
98 }
99 return stack_maps_.GetInvalidRow();
100 }
101
102 // Scan backward to determine dex register locations at given stack map.
103 // All registers for a stack map are combined - inlined registers are just appended,
104 // therefore 'first_dex_register' allows us to select a sub-range to decode.
DecodeDexRegisterMap(uint32_t stack_map_index,uint32_t first_dex_register,DexRegisterMap * map) const105 void CodeInfo::DecodeDexRegisterMap(uint32_t stack_map_index,
106 uint32_t first_dex_register,
107 /*out*/ DexRegisterMap* map) const {
108 // Count remaining work so we know when we have finished.
109 uint32_t remaining_registers = map->size();
110
111 // Keep scanning backwards and collect the most recent location of each register.
112 for (int32_t s = stack_map_index; s >= 0 && remaining_registers != 0; s--) {
113 StackMap stack_map = GetStackMapAt(s);
114 DCHECK_LE(stack_map_index - s, kMaxDexRegisterMapSearchDistance) << "Unbounded search";
115
116 // The mask specifies which registers where modified in this stack map.
117 // NB: the mask can be shorter than expected if trailing zero bits were removed.
118 uint32_t mask_index = stack_map.GetDexRegisterMaskIndex();
119 if (mask_index == StackMap::kNoValue) {
120 continue; // Nothing changed at this stack map.
121 }
122 BitMemoryRegion mask = dex_register_masks_.GetBitMemoryRegion(mask_index);
123 if (mask.size_in_bits() <= first_dex_register) {
124 continue; // Nothing changed after the first register we are interested in.
125 }
126
127 // The map stores one catalogue index per each modified register location.
128 uint32_t map_index = stack_map.GetDexRegisterMapIndex();
129 DCHECK_NE(map_index, StackMap::kNoValue);
130
131 // Skip initial registers which we are not interested in (to get to inlined registers).
132 map_index += mask.PopCount(0, first_dex_register);
133 mask = mask.Subregion(first_dex_register, mask.size_in_bits() - first_dex_register);
134
135 // Update registers that we see for first time (i.e. most recent value).
136 DexRegisterLocation* regs = map->data();
137 const uint32_t end = std::min<uint32_t>(map->size(), mask.size_in_bits());
138 const size_t kNumBits = BitSizeOf<uint32_t>();
139 for (uint32_t reg = 0; reg < end; reg += kNumBits) {
140 // Process the mask in chunks of kNumBits for performance.
141 uint32_t bits = mask.LoadBits(reg, std::min<uint32_t>(end - reg, kNumBits));
142 while (bits != 0) {
143 uint32_t bit = CTZ(bits);
144 if (regs[reg + bit].GetKind() == DexRegisterLocation::Kind::kInvalid) {
145 regs[reg + bit] = GetDexRegisterCatalogEntry(dex_register_maps_.Get(map_index));
146 remaining_registers--;
147 }
148 map_index++;
149 bits ^= 1u << bit; // Clear the bit.
150 }
151 }
152 }
153
154 // Set any remaining registers to None (which is the default state at first stack map).
155 if (remaining_registers != 0) {
156 DexRegisterLocation* regs = map->data();
157 for (uint32_t r = 0; r < map->size(); r++) {
158 if (regs[r].GetKind() == DexRegisterLocation::Kind::kInvalid) {
159 regs[r] = DexRegisterLocation::None();
160 }
161 }
162 }
163 }
164
165 // Decode the CodeInfo while collecting size statistics.
CollectSizeStats(const uint8_t * code_info_data,Stats & stats)166 void CodeInfo::CollectSizeStats(const uint8_t* code_info_data, /*out*/ Stats& stats) {
167 BitMemoryReader reader(code_info_data);
168 reader.ReadInterleavedVarints<kNumHeaders>();
169 stats["Header"].AddBits(reader.NumberOfReadBits());
170 size_t num_bits;
171 CodeInfo code_info(code_info_data, &num_bits, [&](size_t i, auto* table, BitMemoryRegion region) {
172 if (!code_info.IsBitTableDeduped(i)) {
173 Stats& table_stats = stats[table->GetName()];
174 table_stats.AddBits(region.size_in_bits());
175 table_stats["Header"].AddBits(region.size_in_bits() - table->DataBitSize());
176 const char* const* column_names = table->GetColumnNames();
177 for (size_t c = 0; c < table->NumColumns(); c++) {
178 if (table->NumColumnBits(c) > 0) {
179 Stats& column_stats = table_stats[column_names[c]];
180 column_stats.AddBits(table->NumRows() * table->NumColumnBits(c), table->NumRows());
181 }
182 }
183 }
184 });
185 stats.AddBytes(BitsToBytesRoundUp(num_bits));
186 }
187
Dump(VariableIndentationOutputStream * vios) const188 void DexRegisterMap::Dump(VariableIndentationOutputStream* vios) const {
189 if (HasAnyLiveDexRegisters()) {
190 ScopedIndentation indent1(vios);
191 for (size_t i = 0; i < size(); ++i) {
192 DexRegisterLocation reg = (*this)[i];
193 if (reg.IsLive()) {
194 vios->Stream() << "v" << i << ":" << reg << " ";
195 }
196 }
197 vios->Stream() << "\n";
198 }
199 }
200
Dump(VariableIndentationOutputStream * vios,uint32_t code_offset,bool verbose,InstructionSet instruction_set) const201 void CodeInfo::Dump(VariableIndentationOutputStream* vios,
202 uint32_t code_offset,
203 bool verbose,
204 InstructionSet instruction_set) const {
205 vios->Stream() << "CodeInfo"
206 << " CodeSize:" << code_size_
207 << " FrameSize:" << packed_frame_size_ * kStackAlignment
208 << " CoreSpillMask:" << std::hex << core_spill_mask_
209 << " FpSpillMask:" << std::hex << fp_spill_mask_
210 << " NumberOfDexRegisters:" << std::dec << number_of_dex_registers_
211 << "\n";
212 ScopedIndentation indent1(vios);
213 ForEachBitTableField([this, &vios, verbose](size_t, auto member_pointer) {
214 const auto& table = this->*member_pointer;
215 if (table.NumRows() != 0) {
216 vios->Stream() << table.GetName() << " BitSize=" << table.DataBitSize();
217 vios->Stream() << " Rows=" << table.NumRows() << " Bits={";
218 const char* const* column_names = table.GetColumnNames();
219 for (size_t c = 0; c < table.NumColumns(); c++) {
220 vios->Stream() << (c != 0 ? " " : "");
221 vios->Stream() << column_names[c] << "=" << table.NumColumnBits(c);
222 }
223 vios->Stream() << "}\n";
224 if (verbose) {
225 ScopedIndentation indent1(vios);
226 for (size_t r = 0; r < table.NumRows(); r++) {
227 vios->Stream() << "[" << std::right << std::setw(3) << r << "]={";
228 for (size_t c = 0; c < table.NumColumns(); c++) {
229 vios->Stream() << (c != 0 ? " " : "");
230 if (&table == static_cast<const void*>(&stack_masks_) ||
231 &table == static_cast<const void*>(&dex_register_masks_)) {
232 BitMemoryRegion bits = table.GetBitMemoryRegion(r, c);
233 for (size_t b = 0, e = bits.size_in_bits(); b < e; b++) {
234 vios->Stream() << bits.LoadBit(e - b - 1);
235 }
236 } else {
237 vios->Stream() << std::right << std::setw(8) << static_cast<int32_t>(table.Get(r, c));
238 }
239 }
240 vios->Stream() << "}\n";
241 }
242 }
243 }
244 });
245
246 // Display stack maps along with (live) Dex register maps.
247 if (verbose) {
248 for (StackMap stack_map : stack_maps_) {
249 stack_map.Dump(vios, *this, code_offset, instruction_set);
250 }
251 }
252 }
253
Dump(VariableIndentationOutputStream * vios,const CodeInfo & code_info,uint32_t code_offset,InstructionSet instruction_set) const254 void StackMap::Dump(VariableIndentationOutputStream* vios,
255 const CodeInfo& code_info,
256 uint32_t code_offset,
257 InstructionSet instruction_set) const {
258 const uint32_t pc_offset = GetNativePcOffset(instruction_set);
259 vios->Stream()
260 << "StackMap[" << Row() << "]"
261 << std::hex
262 << " (native_pc=0x" << code_offset + pc_offset
263 << ", dex_pc=0x" << GetDexPc()
264 << ", register_mask=0x" << code_info.GetRegisterMaskOf(*this)
265 << std::dec
266 << ", stack_mask=0b";
267 BitMemoryRegion stack_mask = code_info.GetStackMaskOf(*this);
268 for (size_t i = 0, e = stack_mask.size_in_bits(); i < e; ++i) {
269 vios->Stream() << stack_mask.LoadBit(e - i - 1);
270 }
271 switch (static_cast<Kind>(GetKind())) {
272 case Kind::Default: break;
273 case Kind::Catch: vios->Stream() << ", Catch"; break;
274 case Kind::OSR: vios->Stream() << ", OSR"; break;
275 case Kind::Debug: vios->Stream() << ", Debug"; break;
276 }
277 vios->Stream() << ")\n";
278 code_info.GetDexRegisterMapOf(*this).Dump(vios);
279 for (InlineInfo inline_info : code_info.GetInlineInfosOf(*this)) {
280 inline_info.Dump(vios, code_info, *this);
281 }
282 }
283
Dump(VariableIndentationOutputStream * vios,const CodeInfo & code_info,const StackMap & stack_map) const284 void InlineInfo::Dump(VariableIndentationOutputStream* vios,
285 const CodeInfo& code_info,
286 const StackMap& stack_map) const {
287 uint32_t depth = Row() - stack_map.GetInlineInfoIndex();
288 vios->Stream()
289 << "InlineInfo[" << Row() << "]"
290 << " (depth=" << depth
291 << std::hex
292 << ", dex_pc=0x" << GetDexPc();
293 if (EncodesArtMethod()) {
294 ScopedObjectAccess soa(Thread::Current());
295 vios->Stream() << ", method=" << GetArtMethod()->PrettyMethod();
296 } else {
297 MethodInfo method_info = code_info.GetMethodInfoOf(*this);
298 vios->Stream() << std::dec << ", method_index=" << method_info.GetMethodIndex();
299 if (method_info.HasDexFileIndex()) {
300 vios->Stream() << ", is_in_bootclasspath=" << std::boolalpha
301 << (method_info.GetDexFileIndexKind() == MethodInfo::kKindBCP)
302 << std::noboolalpha << ", dex_file_index=" << std::dec
303 << method_info.GetDexFileIndex();
304 }
305 }
306 vios->Stream() << ")\n";
307 code_info.GetInlineDexRegisterMapOf(stack_map, *this).Dump(vios);
308 }
309
310 } // namespace art
311