1 /*
2 * Copyright (C) 2014 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 "graph_visualizer.h"
18
19 #include <dlfcn.h>
20
21 #include <cctype>
22 #include <ios>
23 #include <sstream>
24
25 #include "android-base/stringprintf.h"
26 #include "art_method.h"
27 #include "art_method-inl.h"
28 #include "base/intrusive_forward_list.h"
29 #include "bounds_check_elimination.h"
30 #include "builder.h"
31 #include "code_generator.h"
32 #include "data_type-inl.h"
33 #include "dead_code_elimination.h"
34 #include "dex/descriptors_names.h"
35 #include "disassembler.h"
36 #include "inliner.h"
37 #include "licm.h"
38 #include "nodes.h"
39 #include "optimization.h"
40 #include "reference_type_propagation.h"
41 #include "register_allocator_linear_scan.h"
42 #include "scoped_thread_state_change-inl.h"
43 #include "ssa_liveness_analysis.h"
44 #include "utils/assembler.h"
45
46 namespace art {
47
48 // Unique pass-name to identify that the dump is for printing to log.
49 constexpr const char* kDebugDumpName = "debug";
50 constexpr const char* kDebugDumpGraphName = "debug_graph";
51
52 using android::base::StringPrintf;
53
HasWhitespace(const char * str)54 static bool HasWhitespace(const char* str) {
55 DCHECK(str != nullptr);
56 while (str[0] != 0) {
57 if (isspace(str[0])) {
58 return true;
59 }
60 str++;
61 }
62 return false;
63 }
64
65 class StringList {
66 public:
67 enum Format {
68 kArrayBrackets,
69 kSetBrackets,
70 };
71
72 // Create an empty list
StringList(Format format=kArrayBrackets)73 explicit StringList(Format format = kArrayBrackets) : format_(format), is_empty_(true) {}
74
75 // Construct StringList from a linked list. List element class T
76 // must provide methods `GetNext` and `Dump`.
77 template<class T>
StringList(T * first_entry,Format format=kArrayBrackets)78 explicit StringList(T* first_entry, Format format = kArrayBrackets) : StringList(format) {
79 for (T* current = first_entry; current != nullptr; current = current->GetNext()) {
80 current->Dump(NewEntryStream());
81 }
82 }
83 // Construct StringList from a list of elements. The value type must provide method `Dump`.
84 template <typename Container>
StringList(const Container & list,Format format=kArrayBrackets)85 explicit StringList(const Container& list, Format format = kArrayBrackets) : StringList(format) {
86 for (const typename Container::value_type& current : list) {
87 current.Dump(NewEntryStream());
88 }
89 }
90
NewEntryStream()91 std::ostream& NewEntryStream() {
92 if (is_empty_) {
93 is_empty_ = false;
94 } else {
95 sstream_ << ",";
96 }
97 return sstream_;
98 }
99
100 private:
101 Format format_;
102 bool is_empty_;
103 std::ostringstream sstream_;
104
105 friend std::ostream& operator<<(std::ostream& os, const StringList& list);
106 };
107
operator <<(std::ostream & os,const StringList & list)108 std::ostream& operator<<(std::ostream& os, const StringList& list) {
109 switch (list.format_) {
110 case StringList::kArrayBrackets: return os << "[" << list.sstream_.str() << "]";
111 case StringList::kSetBrackets: return os << "{" << list.sstream_.str() << "}";
112 default:
113 LOG(FATAL) << "Invalid StringList format";
114 UNREACHABLE();
115 }
116 }
117
118 #ifndef ART_STATIC_LIBART_COMPILER
119 using create_disasm_prototype = Disassembler*(InstructionSet, DisassemblerOptions*);
120 #endif
121
122 class HGraphVisualizerDisassembler {
123 public:
HGraphVisualizerDisassembler(InstructionSet instruction_set,const uint8_t * base_address,const uint8_t * end_address)124 HGraphVisualizerDisassembler(InstructionSet instruction_set,
125 const uint8_t* base_address,
126 const uint8_t* end_address)
127 : instruction_set_(instruction_set), disassembler_(nullptr) {
128 #ifndef ART_STATIC_LIBART_COMPILER
129 constexpr const char* libart_disassembler_so_name =
130 kIsDebugBuild ? "libartd-disassembler.so" : "libart-disassembler.so";
131 libart_disassembler_handle_ = dlopen(libart_disassembler_so_name, RTLD_NOW);
132 if (libart_disassembler_handle_ == nullptr) {
133 LOG(ERROR) << "Failed to dlopen " << libart_disassembler_so_name << ": " << dlerror();
134 return;
135 }
136 constexpr const char* create_disassembler_symbol = "create_disassembler";
137 create_disasm_prototype* create_disassembler = reinterpret_cast<create_disasm_prototype*>(
138 dlsym(libart_disassembler_handle_, create_disassembler_symbol));
139 if (create_disassembler == nullptr) {
140 LOG(ERROR) << "Could not find " << create_disassembler_symbol << " entry in "
141 << libart_disassembler_so_name << ": " << dlerror();
142 return;
143 }
144 #endif
145 // Reading the disassembly from 0x0 is easier, so we print relative
146 // addresses. We will only disassemble the code once everything has
147 // been generated, so we can read data in literal pools.
148 disassembler_ = std::unique_ptr<Disassembler>(create_disassembler(
149 instruction_set,
150 new DisassemblerOptions(/* absolute_addresses= */ false,
151 base_address,
152 end_address,
153 /* can_read_literals= */ true,
154 Is64BitInstructionSet(instruction_set)
155 ? &Thread::DumpThreadOffset<PointerSize::k64>
156 : &Thread::DumpThreadOffset<PointerSize::k32>)));
157 }
158
~HGraphVisualizerDisassembler()159 ~HGraphVisualizerDisassembler() {
160 // We need to call ~Disassembler() before we close the library.
161 disassembler_.reset();
162 #ifndef ART_STATIC_LIBART_COMPILER
163 if (libart_disassembler_handle_ != nullptr) {
164 dlclose(libart_disassembler_handle_);
165 }
166 #endif
167 }
168
Disassemble(std::ostream & output,size_t start,size_t end) const169 void Disassemble(std::ostream& output, size_t start, size_t end) const {
170 if (disassembler_ == nullptr) {
171 return;
172 }
173
174 const uint8_t* base = disassembler_->GetDisassemblerOptions()->base_address_;
175 if (instruction_set_ == InstructionSet::kThumb2) {
176 // ARM and Thumb-2 use the same disassembler. The bottom bit of the
177 // address is used to distinguish between the two.
178 base += 1;
179 }
180 disassembler_->Dump(output, base + start, base + end);
181 }
182
183 private:
184 InstructionSet instruction_set_;
185 std::unique_ptr<Disassembler> disassembler_;
186
187 #ifndef ART_STATIC_LIBART_COMPILER
188 void* libart_disassembler_handle_;
189 #endif
190 };
191
192
193 /**
194 * HGraph visitor to generate a file suitable for the c1visualizer tool and IRHydra.
195 */
196 class HGraphVisualizerPrinter : public HGraphDelegateVisitor {
197 public:
HGraphVisualizerPrinter(HGraph * graph,std::ostream & output,const char * pass_name,bool is_after_pass,bool graph_in_bad_state,const CodeGenerator * codegen,const BlockNamer & namer,const DisassemblyInformation * disasm_info=nullptr)198 HGraphVisualizerPrinter(HGraph* graph,
199 std::ostream& output,
200 const char* pass_name,
201 bool is_after_pass,
202 bool graph_in_bad_state,
203 const CodeGenerator* codegen,
204 const BlockNamer& namer,
205 const DisassemblyInformation* disasm_info = nullptr)
206 : HGraphDelegateVisitor(graph),
207 output_(output),
208 pass_name_(pass_name),
209 is_after_pass_(is_after_pass),
210 graph_in_bad_state_(graph_in_bad_state),
211 codegen_(codegen),
212 disasm_info_(disasm_info),
213 namer_(namer),
214 disassembler_(disasm_info_ != nullptr
215 ? new HGraphVisualizerDisassembler(
216 codegen_->GetInstructionSet(),
217 codegen_->GetAssembler().CodeBufferBaseAddress(),
218 codegen_->GetAssembler().CodeBufferBaseAddress()
219 + codegen_->GetAssembler().CodeSize())
220 : nullptr),
221 indent_(0) {}
222
Flush()223 void Flush() {
224 // We use "\n" instead of std::endl to avoid implicit flushing which
225 // generates too many syscalls during debug-GC tests (b/27826765).
226 output_ << std::flush;
227 }
228
StartTag(const char * name)229 void StartTag(const char* name) {
230 AddIndent();
231 output_ << "begin_" << name << "\n";
232 indent_++;
233 }
234
EndTag(const char * name)235 void EndTag(const char* name) {
236 indent_--;
237 AddIndent();
238 output_ << "end_" << name << "\n";
239 }
240
PrintProperty(const char * name,HBasicBlock * blk)241 void PrintProperty(const char* name, HBasicBlock* blk) {
242 AddIndent();
243 output_ << name << " \"" << namer_.GetName(blk) << "\"\n";
244 }
245
PrintProperty(const char * name,const char * property)246 void PrintProperty(const char* name, const char* property) {
247 AddIndent();
248 output_ << name << " \"" << property << "\"\n";
249 }
250
PrintProperty(const char * name,const char * property,int id)251 void PrintProperty(const char* name, const char* property, int id) {
252 AddIndent();
253 output_ << name << " \"" << property << id << "\"\n";
254 }
255
PrintEmptyProperty(const char * name)256 void PrintEmptyProperty(const char* name) {
257 AddIndent();
258 output_ << name << "\n";
259 }
260
PrintTime(const char * name)261 void PrintTime(const char* name) {
262 AddIndent();
263 output_ << name << " " << time(nullptr) << "\n";
264 }
265
PrintInt(const char * name,int value)266 void PrintInt(const char* name, int value) {
267 AddIndent();
268 output_ << name << " " << value << "\n";
269 }
270
AddIndent()271 void AddIndent() {
272 for (size_t i = 0; i < indent_; ++i) {
273 output_ << " ";
274 }
275 }
276
PrintPredecessors(HBasicBlock * block)277 void PrintPredecessors(HBasicBlock* block) {
278 AddIndent();
279 output_ << "predecessors";
280 for (HBasicBlock* predecessor : block->GetPredecessors()) {
281 output_ << " \"" << namer_.GetName(predecessor) << "\" ";
282 }
283 if (block->IsEntryBlock() && (disasm_info_ != nullptr)) {
284 output_ << " \"" << kDisassemblyBlockFrameEntry << "\" ";
285 }
286 output_<< "\n";
287 }
288
PrintSuccessors(HBasicBlock * block)289 void PrintSuccessors(HBasicBlock* block) {
290 AddIndent();
291 output_ << "successors";
292 for (HBasicBlock* successor : block->GetNormalSuccessors()) {
293 output_ << " \"" << namer_.GetName(successor) << "\" ";
294 }
295 output_<< "\n";
296 }
297
PrintExceptionHandlers(HBasicBlock * block)298 void PrintExceptionHandlers(HBasicBlock* block) {
299 bool has_slow_paths = block->IsExitBlock() &&
300 (disasm_info_ != nullptr) &&
301 !disasm_info_->GetSlowPathIntervals().empty();
302 if (IsDebugDump() && block->GetExceptionalSuccessors().empty() && !has_slow_paths) {
303 return;
304 }
305 AddIndent();
306 output_ << "xhandlers";
307 for (HBasicBlock* handler : block->GetExceptionalSuccessors()) {
308 output_ << " \"" << namer_.GetName(handler) << "\" ";
309 }
310 if (has_slow_paths) {
311 output_ << " \"" << kDisassemblyBlockSlowPaths << "\" ";
312 }
313 output_<< "\n";
314 }
315
DumpLocation(std::ostream & stream,const Location & location)316 void DumpLocation(std::ostream& stream, const Location& location) {
317 DCHECK(codegen_ != nullptr);
318 if (location.IsRegister()) {
319 codegen_->DumpCoreRegister(stream, location.reg());
320 } else if (location.IsFpuRegister()) {
321 codegen_->DumpFloatingPointRegister(stream, location.reg());
322 } else if (location.IsConstant()) {
323 stream << "#";
324 HConstant* constant = location.GetConstant();
325 if (constant->IsIntConstant()) {
326 stream << constant->AsIntConstant()->GetValue();
327 } else if (constant->IsLongConstant()) {
328 stream << constant->AsLongConstant()->GetValue();
329 } else if (constant->IsFloatConstant()) {
330 stream << constant->AsFloatConstant()->GetValue();
331 } else if (constant->IsDoubleConstant()) {
332 stream << constant->AsDoubleConstant()->GetValue();
333 } else if (constant->IsNullConstant()) {
334 stream << "null";
335 }
336 } else if (location.IsInvalid()) {
337 stream << "invalid";
338 } else if (location.IsStackSlot()) {
339 stream << location.GetStackIndex() << "(sp)";
340 } else if (location.IsFpuRegisterPair()) {
341 codegen_->DumpFloatingPointRegister(stream, location.low());
342 stream << "|";
343 codegen_->DumpFloatingPointRegister(stream, location.high());
344 } else if (location.IsRegisterPair()) {
345 codegen_->DumpCoreRegister(stream, location.low());
346 stream << "|";
347 codegen_->DumpCoreRegister(stream, location.high());
348 } else if (location.IsUnallocated()) {
349 stream << "unallocated";
350 } else if (location.IsDoubleStackSlot()) {
351 stream << "2x" << location.GetStackIndex() << "(sp)";
352 } else {
353 DCHECK(location.IsSIMDStackSlot());
354 stream << "4x" << location.GetStackIndex() << "(sp)";
355 }
356 }
357
StartAttributeStream(const char * name=nullptr)358 std::ostream& StartAttributeStream(const char* name = nullptr) {
359 if (name == nullptr) {
360 output_ << " ";
361 } else {
362 DCHECK(!HasWhitespace(name)) << "Checker does not allow spaces in attributes";
363 output_ << " " << name << ":";
364 }
365 return output_;
366 }
367
VisitParallelMove(HParallelMove * instruction)368 void VisitParallelMove(HParallelMove* instruction) override {
369 StartAttributeStream("liveness") << instruction->GetLifetimePosition();
370 StringList moves;
371 for (size_t i = 0, e = instruction->NumMoves(); i < e; ++i) {
372 MoveOperands* move = instruction->MoveOperandsAt(i);
373 std::ostream& str = moves.NewEntryStream();
374 DumpLocation(str, move->GetSource());
375 str << "->";
376 DumpLocation(str, move->GetDestination());
377 }
378 StartAttributeStream("moves") << moves;
379 }
380
VisitIntConstant(HIntConstant * instruction)381 void VisitIntConstant(HIntConstant* instruction) override {
382 StartAttributeStream() << instruction->GetValue();
383 }
384
VisitLongConstant(HLongConstant * instruction)385 void VisitLongConstant(HLongConstant* instruction) override {
386 StartAttributeStream() << instruction->GetValue();
387 }
388
VisitFloatConstant(HFloatConstant * instruction)389 void VisitFloatConstant(HFloatConstant* instruction) override {
390 StartAttributeStream() << instruction->GetValue();
391 }
392
VisitDoubleConstant(HDoubleConstant * instruction)393 void VisitDoubleConstant(HDoubleConstant* instruction) override {
394 StartAttributeStream() << instruction->GetValue();
395 }
396
VisitPhi(HPhi * phi)397 void VisitPhi(HPhi* phi) override {
398 StartAttributeStream("reg") << phi->GetRegNumber();
399 StartAttributeStream("is_catch_phi") << std::boolalpha << phi->IsCatchPhi() << std::noboolalpha;
400 }
401
VisitMemoryBarrier(HMemoryBarrier * barrier)402 void VisitMemoryBarrier(HMemoryBarrier* barrier) override {
403 StartAttributeStream("kind") << barrier->GetBarrierKind();
404 }
405
VisitMonitorOperation(HMonitorOperation * monitor)406 void VisitMonitorOperation(HMonitorOperation* monitor) override {
407 StartAttributeStream("kind") << (monitor->IsEnter() ? "enter" : "exit");
408 }
409
VisitLoadClass(HLoadClass * load_class)410 void VisitLoadClass(HLoadClass* load_class) override {
411 StartAttributeStream("load_kind") << load_class->GetLoadKind();
412 StartAttributeStream("class_name")
413 << load_class->GetDexFile().PrettyType(load_class->GetTypeIndex());
414 StartAttributeStream("gen_clinit_check")
415 << std::boolalpha << load_class->MustGenerateClinitCheck() << std::noboolalpha;
416 StartAttributeStream("needs_access_check") << std::boolalpha
417 << load_class->NeedsAccessCheck() << std::noboolalpha;
418 }
419
VisitLoadMethodHandle(HLoadMethodHandle * load_method_handle)420 void VisitLoadMethodHandle(HLoadMethodHandle* load_method_handle) override {
421 StartAttributeStream("load_kind") << "RuntimeCall";
422 StartAttributeStream("method_handle_index") << load_method_handle->GetMethodHandleIndex();
423 }
424
VisitLoadMethodType(HLoadMethodType * load_method_type)425 void VisitLoadMethodType(HLoadMethodType* load_method_type) override {
426 StartAttributeStream("load_kind") << "RuntimeCall";
427 const DexFile& dex_file = load_method_type->GetDexFile();
428 if (dex_file.NumProtoIds() >= load_method_type->GetProtoIndex().index_) {
429 const dex::ProtoId& proto_id = dex_file.GetProtoId(load_method_type->GetProtoIndex());
430 StartAttributeStream("method_type") << dex_file.GetProtoSignature(proto_id);
431 } else {
432 StartAttributeStream("method_type")
433 << "<<Unknown proto-idx: " << load_method_type->GetProtoIndex() << ">>";
434 }
435 }
436
VisitLoadString(HLoadString * load_string)437 void VisitLoadString(HLoadString* load_string) override {
438 StartAttributeStream("load_kind") << load_string->GetLoadKind();
439 }
440
HandleTypeCheckInstruction(HTypeCheckInstruction * check)441 void HandleTypeCheckInstruction(HTypeCheckInstruction* check) {
442 StartAttributeStream("check_kind") << check->GetTypeCheckKind();
443 StartAttributeStream("must_do_null_check") << std::boolalpha
444 << check->MustDoNullCheck() << std::noboolalpha;
445 if (check->GetTypeCheckKind() == TypeCheckKind::kBitstringCheck) {
446 StartAttributeStream("path_to_root") << std::hex
447 << "0x" << check->GetBitstringPathToRoot() << std::dec;
448 StartAttributeStream("mask") << std::hex << "0x" << check->GetBitstringMask() << std::dec;
449 }
450 }
451
VisitCheckCast(HCheckCast * check_cast)452 void VisitCheckCast(HCheckCast* check_cast) override {
453 HandleTypeCheckInstruction(check_cast);
454 }
455
VisitInstanceOf(HInstanceOf * instance_of)456 void VisitInstanceOf(HInstanceOf* instance_of) override {
457 HandleTypeCheckInstruction(instance_of);
458 }
459
VisitArrayLength(HArrayLength * array_length)460 void VisitArrayLength(HArrayLength* array_length) override {
461 StartAttributeStream("is_string_length") << std::boolalpha
462 << array_length->IsStringLength() << std::noboolalpha;
463 if (array_length->IsEmittedAtUseSite()) {
464 StartAttributeStream("emitted_at_use") << "true";
465 }
466 }
467
VisitBoundsCheck(HBoundsCheck * bounds_check)468 void VisitBoundsCheck(HBoundsCheck* bounds_check) override {
469 StartAttributeStream("is_string_char_at") << std::boolalpha
470 << bounds_check->IsStringCharAt() << std::noboolalpha;
471 }
472
VisitArrayGet(HArrayGet * array_get)473 void VisitArrayGet(HArrayGet* array_get) override {
474 StartAttributeStream("is_string_char_at") << std::boolalpha
475 << array_get->IsStringCharAt() << std::noboolalpha;
476 }
477
VisitArraySet(HArraySet * array_set)478 void VisitArraySet(HArraySet* array_set) override {
479 StartAttributeStream("value_can_be_null") << std::boolalpha
480 << array_set->GetValueCanBeNull() << std::noboolalpha;
481 StartAttributeStream("needs_type_check") << std::boolalpha
482 << array_set->NeedsTypeCheck() << std::noboolalpha;
483 }
484
VisitCompare(HCompare * compare)485 void VisitCompare(HCompare* compare) override {
486 StartAttributeStream("bias") << compare->GetBias();
487 }
488
VisitInvoke(HInvoke * invoke)489 void VisitInvoke(HInvoke* invoke) override {
490 StartAttributeStream("dex_file_index") << invoke->GetMethodReference().index;
491 ArtMethod* method = invoke->GetResolvedMethod();
492 // We don't print signatures, which conflict with c1visualizer format.
493 static constexpr bool kWithSignature = false;
494 // Note that we can only use the graph's dex file for the unresolved case. The
495 // other invokes might be coming from inlined methods.
496 ScopedObjectAccess soa(Thread::Current());
497 std::string method_name = (method == nullptr)
498 ? invoke->GetMethodReference().PrettyMethod(kWithSignature)
499 : method->PrettyMethod(kWithSignature);
500 StartAttributeStream("method_name") << method_name;
501 StartAttributeStream("always_throws") << std::boolalpha
502 << invoke->AlwaysThrows()
503 << std::noboolalpha;
504 if (method != nullptr) {
505 StartAttributeStream("method_index") << method->GetMethodIndex();
506 }
507 }
508
VisitInvokeUnresolved(HInvokeUnresolved * invoke)509 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) override {
510 VisitInvoke(invoke);
511 StartAttributeStream("invoke_type") << invoke->GetInvokeType();
512 }
513
VisitInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)514 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) override {
515 VisitInvoke(invoke);
516 StartAttributeStream("method_load_kind") << invoke->GetMethodLoadKind();
517 StartAttributeStream("intrinsic") << invoke->GetIntrinsic();
518 if (invoke->IsStatic()) {
519 StartAttributeStream("clinit_check") << invoke->GetClinitCheckRequirement();
520 }
521 }
522
VisitInvokeVirtual(HInvokeVirtual * invoke)523 void VisitInvokeVirtual(HInvokeVirtual* invoke) override {
524 VisitInvoke(invoke);
525 StartAttributeStream("intrinsic") << invoke->GetIntrinsic();
526 }
527
VisitInvokePolymorphic(HInvokePolymorphic * invoke)528 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) override {
529 VisitInvoke(invoke);
530 StartAttributeStream("invoke_type") << "InvokePolymorphic";
531 }
532
VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet * iget)533 void VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet* iget) override {
534 StartAttributeStream("field_name") <<
535 iget->GetFieldInfo().GetDexFile().PrettyField(iget->GetFieldInfo().GetFieldIndex(),
536 /* with type */ false);
537 StartAttributeStream("field_type") << iget->GetFieldType();
538 }
539
VisitInstanceFieldGet(HInstanceFieldGet * iget)540 void VisitInstanceFieldGet(HInstanceFieldGet* iget) override {
541 StartAttributeStream("field_name") <<
542 iget->GetFieldInfo().GetDexFile().PrettyField(iget->GetFieldInfo().GetFieldIndex(),
543 /* with type */ false);
544 StartAttributeStream("field_type") << iget->GetFieldType();
545 }
546
VisitInstanceFieldSet(HInstanceFieldSet * iset)547 void VisitInstanceFieldSet(HInstanceFieldSet* iset) override {
548 StartAttributeStream("field_name") <<
549 iset->GetFieldInfo().GetDexFile().PrettyField(iset->GetFieldInfo().GetFieldIndex(),
550 /* with type */ false);
551 StartAttributeStream("field_type") << iset->GetFieldType();
552 StartAttributeStream("predicated") << std::boolalpha << iset->GetIsPredicatedSet();
553 }
554
VisitStaticFieldGet(HStaticFieldGet * sget)555 void VisitStaticFieldGet(HStaticFieldGet* sget) override {
556 StartAttributeStream("field_name") <<
557 sget->GetFieldInfo().GetDexFile().PrettyField(sget->GetFieldInfo().GetFieldIndex(),
558 /* with type */ false);
559 StartAttributeStream("field_type") << sget->GetFieldType();
560 }
561
VisitStaticFieldSet(HStaticFieldSet * sset)562 void VisitStaticFieldSet(HStaticFieldSet* sset) override {
563 StartAttributeStream("field_name") <<
564 sset->GetFieldInfo().GetDexFile().PrettyField(sset->GetFieldInfo().GetFieldIndex(),
565 /* with type */ false);
566 StartAttributeStream("field_type") << sset->GetFieldType();
567 }
568
VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet * field_access)569 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* field_access) override {
570 StartAttributeStream("field_type") << field_access->GetFieldType();
571 }
572
VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet * field_access)573 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* field_access) override {
574 StartAttributeStream("field_type") << field_access->GetFieldType();
575 }
576
VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet * field_access)577 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* field_access) override {
578 StartAttributeStream("field_type") << field_access->GetFieldType();
579 }
580
VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet * field_access)581 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* field_access) override {
582 StartAttributeStream("field_type") << field_access->GetFieldType();
583 }
584
VisitTryBoundary(HTryBoundary * try_boundary)585 void VisitTryBoundary(HTryBoundary* try_boundary) override {
586 StartAttributeStream("kind") << (try_boundary->IsEntry() ? "entry" : "exit");
587 }
588
VisitGoto(HGoto * instruction)589 void VisitGoto(HGoto* instruction) override {
590 StartAttributeStream("target") << namer_.GetName(instruction->GetBlock()->GetSingleSuccessor());
591 }
592
VisitDeoptimize(HDeoptimize * deoptimize)593 void VisitDeoptimize(HDeoptimize* deoptimize) override {
594 StartAttributeStream("kind") << deoptimize->GetKind();
595 }
596
VisitVecOperation(HVecOperation * vec_operation)597 void VisitVecOperation(HVecOperation* vec_operation) override {
598 StartAttributeStream("packed_type") << vec_operation->GetPackedType();
599 }
600
VisitVecMemoryOperation(HVecMemoryOperation * vec_mem_operation)601 void VisitVecMemoryOperation(HVecMemoryOperation* vec_mem_operation) override {
602 StartAttributeStream("alignment") << vec_mem_operation->GetAlignment().ToString();
603 }
604
VisitVecHalvingAdd(HVecHalvingAdd * hadd)605 void VisitVecHalvingAdd(HVecHalvingAdd* hadd) override {
606 VisitVecBinaryOperation(hadd);
607 StartAttributeStream("rounded") << std::boolalpha << hadd->IsRounded() << std::noboolalpha;
608 }
609
VisitVecMultiplyAccumulate(HVecMultiplyAccumulate * instruction)610 void VisitVecMultiplyAccumulate(HVecMultiplyAccumulate* instruction) override {
611 VisitVecOperation(instruction);
612 StartAttributeStream("kind") << instruction->GetOpKind();
613 }
614
VisitVecDotProd(HVecDotProd * instruction)615 void VisitVecDotProd(HVecDotProd* instruction) override {
616 VisitVecOperation(instruction);
617 DataType::Type arg_type = instruction->InputAt(1)->AsVecOperation()->GetPackedType();
618 StartAttributeStream("type") << (instruction->IsZeroExtending() ?
619 DataType::ToUnsigned(arg_type) :
620 DataType::ToSigned(arg_type));
621 }
622
623 #if defined(ART_ENABLE_CODEGEN_arm) || defined(ART_ENABLE_CODEGEN_arm64)
VisitMultiplyAccumulate(HMultiplyAccumulate * instruction)624 void VisitMultiplyAccumulate(HMultiplyAccumulate* instruction) override {
625 StartAttributeStream("kind") << instruction->GetOpKind();
626 }
627
VisitBitwiseNegatedRight(HBitwiseNegatedRight * instruction)628 void VisitBitwiseNegatedRight(HBitwiseNegatedRight* instruction) override {
629 StartAttributeStream("kind") << instruction->GetOpKind();
630 }
631
VisitDataProcWithShifterOp(HDataProcWithShifterOp * instruction)632 void VisitDataProcWithShifterOp(HDataProcWithShifterOp* instruction) override {
633 StartAttributeStream("kind") << instruction->GetInstrKind() << "+" << instruction->GetOpKind();
634 if (HDataProcWithShifterOp::IsShiftOp(instruction->GetOpKind())) {
635 StartAttributeStream("shift") << instruction->GetShiftAmount();
636 }
637 }
638 #endif
639
IsPass(const char * name)640 bool IsPass(const char* name) {
641 return strcmp(pass_name_, name) == 0;
642 }
643
IsDebugDump()644 bool IsDebugDump() {
645 return IsPass(kDebugDumpGraphName) || IsPass(kDebugDumpName);
646 }
647
PrintInstruction(HInstruction * instruction)648 void PrintInstruction(HInstruction* instruction) {
649 output_ << instruction->DebugName();
650 HConstInputsRef inputs = instruction->GetInputs();
651 if (!inputs.empty()) {
652 StringList input_list;
653 for (const HInstruction* input : inputs) {
654 input_list.NewEntryStream() << DataType::TypeId(input->GetType()) << input->GetId();
655 }
656 StartAttributeStream() << input_list;
657 }
658 if (instruction->GetDexPc() != kNoDexPc) {
659 StartAttributeStream("dex_pc") << instruction->GetDexPc();
660 } else {
661 StartAttributeStream("dex_pc") << "n/a";
662 }
663 HBasicBlock* block = instruction->GetBlock();
664 StartAttributeStream("block") << namer_.GetName(block);
665
666 instruction->Accept(this);
667 if (instruction->HasEnvironment()) {
668 StringList envs;
669 for (HEnvironment* environment = instruction->GetEnvironment();
670 environment != nullptr;
671 environment = environment->GetParent()) {
672 StringList vregs;
673 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
674 HInstruction* insn = environment->GetInstructionAt(i);
675 if (insn != nullptr) {
676 vregs.NewEntryStream() << DataType::TypeId(insn->GetType()) << insn->GetId();
677 } else {
678 vregs.NewEntryStream() << "_";
679 }
680 }
681 envs.NewEntryStream() << vregs;
682 }
683 StartAttributeStream("env") << envs;
684 }
685 if (IsPass(SsaLivenessAnalysis::kLivenessPassName)
686 && is_after_pass_
687 && instruction->GetLifetimePosition() != kNoLifetime) {
688 StartAttributeStream("liveness") << instruction->GetLifetimePosition();
689 if (instruction->HasLiveInterval()) {
690 LiveInterval* interval = instruction->GetLiveInterval();
691 StartAttributeStream("ranges")
692 << StringList(interval->GetFirstRange(), StringList::kSetBrackets);
693 StartAttributeStream("uses") << StringList(interval->GetUses());
694 StartAttributeStream("env_uses") << StringList(interval->GetEnvironmentUses());
695 StartAttributeStream("is_fixed") << interval->IsFixed();
696 StartAttributeStream("is_split") << interval->IsSplit();
697 StartAttributeStream("is_low") << interval->IsLowInterval();
698 StartAttributeStream("is_high") << interval->IsHighInterval();
699 }
700 }
701
702 if (IsPass(RegisterAllocator::kRegisterAllocatorPassName) && is_after_pass_) {
703 StartAttributeStream("liveness") << instruction->GetLifetimePosition();
704 LocationSummary* locations = instruction->GetLocations();
705 if (locations != nullptr) {
706 StringList input_list;
707 for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
708 DumpLocation(input_list.NewEntryStream(), locations->InAt(i));
709 }
710 std::ostream& attr = StartAttributeStream("locations");
711 attr << input_list << "->";
712 DumpLocation(attr, locations->Out());
713 }
714 }
715
716 HLoopInformation* loop_info = (block != nullptr) ? block->GetLoopInformation() : nullptr;
717 if (loop_info == nullptr) {
718 StartAttributeStream("loop") << "none";
719 } else {
720 StartAttributeStream("loop") << namer_.GetName(loop_info->GetHeader());
721 HLoopInformation* outer = loop_info->GetPreHeader()->GetLoopInformation();
722 if (outer != nullptr) {
723 StartAttributeStream("outer_loop") << namer_.GetName(outer->GetHeader());
724 } else {
725 StartAttributeStream("outer_loop") << "none";
726 }
727 StartAttributeStream("irreducible")
728 << std::boolalpha << loop_info->IsIrreducible() << std::noboolalpha;
729 }
730
731 // For the builder and the inliner, we want to add extra information on HInstructions
732 // that have reference types, and also HInstanceOf/HCheckcast.
733 if ((IsPass(HGraphBuilder::kBuilderPassName)
734 || IsPass(HInliner::kInlinerPassName)
735 || IsDebugDump())
736 && (instruction->GetType() == DataType::Type::kReference ||
737 instruction->IsInstanceOf() ||
738 instruction->IsCheckCast())) {
739 ReferenceTypeInfo info = (instruction->GetType() == DataType::Type::kReference)
740 ? instruction->IsLoadClass()
741 ? instruction->AsLoadClass()->GetLoadedClassRTI()
742 : instruction->GetReferenceTypeInfo()
743 : instruction->IsInstanceOf()
744 ? instruction->AsInstanceOf()->GetTargetClassRTI()
745 : instruction->AsCheckCast()->GetTargetClassRTI();
746 ScopedObjectAccess soa(Thread::Current());
747 if (info.IsValid()) {
748 StartAttributeStream("klass")
749 << mirror::Class::PrettyDescriptor(info.GetTypeHandle().Get());
750 if (instruction->GetType() == DataType::Type::kReference) {
751 StartAttributeStream("can_be_null")
752 << std::boolalpha << instruction->CanBeNull() << std::noboolalpha;
753 }
754 StartAttributeStream("exact") << std::boolalpha << info.IsExact() << std::noboolalpha;
755 } else if (instruction->IsLoadClass() ||
756 instruction->IsInstanceOf() ||
757 instruction->IsCheckCast()) {
758 StartAttributeStream("klass") << "unresolved";
759 } else {
760 // The NullConstant may be added to the graph during other passes that happen between
761 // ReferenceTypePropagation and Inliner (e.g. InstructionSimplifier). If the inliner
762 // doesn't run or doesn't inline anything, the NullConstant remains untyped.
763 // So we should check NullConstants for validity only after reference type propagation.
764 DCHECK(graph_in_bad_state_ ||
765 IsDebugDump() ||
766 (!is_after_pass_ && IsPass(HGraphBuilder::kBuilderPassName)))
767 << instruction->DebugName() << instruction->GetId() << " has invalid rti "
768 << (is_after_pass_ ? "after" : "before") << " pass " << pass_name_;
769 }
770 }
771 if (disasm_info_ != nullptr) {
772 DCHECK(disassembler_ != nullptr);
773 // If the information is available, disassemble the code generated for
774 // this instruction.
775 auto it = disasm_info_->GetInstructionIntervals().find(instruction);
776 if (it != disasm_info_->GetInstructionIntervals().end()
777 && it->second.start != it->second.end) {
778 output_ << "\n";
779 disassembler_->Disassemble(output_, it->second.start, it->second.end);
780 }
781 }
782 }
783
PrintInstructions(const HInstructionList & list)784 void PrintInstructions(const HInstructionList& list) {
785 for (HInstructionIterator it(list); !it.Done(); it.Advance()) {
786 HInstruction* instruction = it.Current();
787 int bci = 0;
788 size_t num_uses = instruction->GetUses().SizeSlow();
789 AddIndent();
790 output_ << bci << " " << num_uses << " "
791 << DataType::TypeId(instruction->GetType()) << instruction->GetId() << " ";
792 PrintInstruction(instruction);
793 output_ << " " << kEndInstructionMarker << "\n";
794 }
795 }
796
DumpStartOfDisassemblyBlock(const char * block_name,int predecessor_index,int successor_index)797 void DumpStartOfDisassemblyBlock(const char* block_name,
798 int predecessor_index,
799 int successor_index) {
800 StartTag("block");
801 PrintProperty("name", block_name);
802 PrintInt("from_bci", -1);
803 PrintInt("to_bci", -1);
804 if (predecessor_index != -1) {
805 PrintProperty("predecessors", "B", predecessor_index);
806 } else {
807 PrintEmptyProperty("predecessors");
808 }
809 if (successor_index != -1) {
810 PrintProperty("successors", "B", successor_index);
811 } else {
812 PrintEmptyProperty("successors");
813 }
814 PrintEmptyProperty("xhandlers");
815 PrintEmptyProperty("flags");
816 StartTag("states");
817 StartTag("locals");
818 PrintInt("size", 0);
819 PrintProperty("method", "None");
820 EndTag("locals");
821 EndTag("states");
822 StartTag("HIR");
823 }
824
DumpEndOfDisassemblyBlock()825 void DumpEndOfDisassemblyBlock() {
826 EndTag("HIR");
827 EndTag("block");
828 }
829
DumpDisassemblyBlockForFrameEntry()830 void DumpDisassemblyBlockForFrameEntry() {
831 DumpStartOfDisassemblyBlock(kDisassemblyBlockFrameEntry,
832 -1,
833 GetGraph()->GetEntryBlock()->GetBlockId());
834 output_ << " 0 0 disasm " << kDisassemblyBlockFrameEntry << " ";
835 GeneratedCodeInterval frame_entry = disasm_info_->GetFrameEntryInterval();
836 if (frame_entry.start != frame_entry.end) {
837 output_ << "\n";
838 disassembler_->Disassemble(output_, frame_entry.start, frame_entry.end);
839 }
840 output_ << kEndInstructionMarker << "\n";
841 DumpEndOfDisassemblyBlock();
842 }
843
DumpDisassemblyBlockForSlowPaths()844 void DumpDisassemblyBlockForSlowPaths() {
845 if (disasm_info_->GetSlowPathIntervals().empty()) {
846 return;
847 }
848 // If the graph has an exit block we attach the block for the slow paths
849 // after it. Else we just add the block to the graph without linking it to
850 // any other.
851 DumpStartOfDisassemblyBlock(
852 kDisassemblyBlockSlowPaths,
853 GetGraph()->HasExitBlock() ? GetGraph()->GetExitBlock()->GetBlockId() : -1,
854 -1);
855 for (SlowPathCodeInfo info : disasm_info_->GetSlowPathIntervals()) {
856 output_ << " 0 0 disasm " << info.slow_path->GetDescription() << "\n";
857 disassembler_->Disassemble(output_, info.code_interval.start, info.code_interval.end);
858 output_ << kEndInstructionMarker << "\n";
859 }
860 DumpEndOfDisassemblyBlock();
861 }
862
Run()863 void Run() {
864 StartTag("cfg");
865 std::ostringstream oss;
866 oss << pass_name_;
867 if (!IsDebugDump()) {
868 oss << " (" << (is_after_pass_ ? "after" : "before")
869 << (graph_in_bad_state_ ? ", bad_state" : "") << ")";
870 }
871 PrintProperty("name", oss.str().c_str());
872 if (disasm_info_ != nullptr) {
873 DumpDisassemblyBlockForFrameEntry();
874 }
875 VisitInsertionOrder();
876 if (disasm_info_ != nullptr) {
877 DumpDisassemblyBlockForSlowPaths();
878 }
879 EndTag("cfg");
880 Flush();
881 }
882
Run(HInstruction * instruction)883 void Run(HInstruction* instruction) {
884 output_ << DataType::TypeId(instruction->GetType()) << instruction->GetId() << " ";
885 PrintInstruction(instruction);
886 Flush();
887 }
888
VisitBasicBlock(HBasicBlock * block)889 void VisitBasicBlock(HBasicBlock* block) override {
890 StartTag("block");
891 PrintProperty("name", block);
892 if (block->GetLifetimeStart() != kNoLifetime) {
893 // Piggy back on these fields to show the lifetime of the block.
894 PrintInt("from_bci", block->GetLifetimeStart());
895 PrintInt("to_bci", block->GetLifetimeEnd());
896 } else if (!IsDebugDump()) {
897 // Don't print useless information to logcat.
898 PrintInt("from_bci", -1);
899 PrintInt("to_bci", -1);
900 }
901 PrintPredecessors(block);
902 PrintSuccessors(block);
903 PrintExceptionHandlers(block);
904
905 if (block->IsCatchBlock()) {
906 PrintProperty("flags", "catch_block");
907 } else if (!IsDebugDump()) {
908 // Don't print useless information to logcat
909 PrintEmptyProperty("flags");
910 }
911
912 if (block->GetDominator() != nullptr) {
913 PrintProperty("dominator", block->GetDominator());
914 }
915
916 if (!IsDebugDump() || !block->GetPhis().IsEmpty()) {
917 StartTag("states");
918 StartTag("locals");
919 PrintInt("size", 0);
920 PrintProperty("method", "None");
921 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
922 AddIndent();
923 HInstruction* instruction = it.Current();
924 output_ << instruction->GetId() << " " << DataType::TypeId(instruction->GetType())
925 << instruction->GetId() << "[ ";
926 for (const HInstruction* input : instruction->GetInputs()) {
927 output_ << input->GetId() << " ";
928 }
929 output_ << "]\n";
930 }
931 EndTag("locals");
932 EndTag("states");
933 }
934
935 StartTag("HIR");
936 PrintInstructions(block->GetPhis());
937 PrintInstructions(block->GetInstructions());
938 EndTag("HIR");
939 EndTag("block");
940 }
941
942 static constexpr const char* const kEndInstructionMarker = "<|@";
943 static constexpr const char* const kDisassemblyBlockFrameEntry = "FrameEntry";
944 static constexpr const char* const kDisassemblyBlockSlowPaths = "SlowPaths";
945
946 private:
947 std::ostream& output_;
948 const char* pass_name_;
949 const bool is_after_pass_;
950 const bool graph_in_bad_state_;
951 const CodeGenerator* codegen_;
952 const DisassemblyInformation* disasm_info_;
953 const BlockNamer& namer_;
954 std::unique_ptr<HGraphVisualizerDisassembler> disassembler_;
955 size_t indent_;
956
957 DISALLOW_COPY_AND_ASSIGN(HGraphVisualizerPrinter);
958 };
959
PrintName(std::ostream & os,HBasicBlock * blk) const960 std::ostream& HGraphVisualizer::OptionalDefaultNamer::PrintName(std::ostream& os,
961 HBasicBlock* blk) const {
962 if (namer_) {
963 return namer_->get().PrintName(os, blk);
964 } else {
965 return BlockNamer::PrintName(os, blk);
966 }
967 }
968
HGraphVisualizer(std::ostream * output,HGraph * graph,const CodeGenerator * codegen,std::optional<std::reference_wrapper<const BlockNamer>> namer)969 HGraphVisualizer::HGraphVisualizer(std::ostream* output,
970 HGraph* graph,
971 const CodeGenerator* codegen,
972 std::optional<std::reference_wrapper<const BlockNamer>> namer)
973 : output_(output), graph_(graph), codegen_(codegen), namer_(namer) {}
974
PrintHeader(const char * method_name) const975 void HGraphVisualizer::PrintHeader(const char* method_name) const {
976 DCHECK(output_ != nullptr);
977 HGraphVisualizerPrinter printer(graph_, *output_, "", true, false, codegen_, namer_);
978 printer.StartTag("compilation");
979 printer.PrintProperty("name", method_name);
980 printer.PrintProperty("method", method_name);
981 printer.PrintTime("date");
982 printer.EndTag("compilation");
983 printer.Flush();
984 }
985
InsertMetaDataAsCompilationBlock(const std::string & meta_data)986 std::string HGraphVisualizer::InsertMetaDataAsCompilationBlock(const std::string& meta_data) {
987 std::string time_str = std::to_string(time(nullptr));
988 std::string quoted_meta_data = "\"" + meta_data + "\"";
989 return StringPrintf("begin_compilation\n"
990 " name %s\n"
991 " method %s\n"
992 " date %s\n"
993 "end_compilation\n",
994 quoted_meta_data.c_str(),
995 quoted_meta_data.c_str(),
996 time_str.c_str());
997 }
998
DumpGraphDebug() const999 void HGraphVisualizer::DumpGraphDebug() const {
1000 DumpGraph(/* pass_name= */ kDebugDumpGraphName,
1001 /* is_after_pass= */ false,
1002 /* graph_in_bad_state= */ true);
1003 }
1004
DumpGraph(const char * pass_name,bool is_after_pass,bool graph_in_bad_state) const1005 void HGraphVisualizer::DumpGraph(const char* pass_name,
1006 bool is_after_pass,
1007 bool graph_in_bad_state) const {
1008 DCHECK(output_ != nullptr);
1009 if (!graph_->GetBlocks().empty()) {
1010 HGraphVisualizerPrinter printer(graph_,
1011 *output_,
1012 pass_name,
1013 is_after_pass,
1014 graph_in_bad_state,
1015 codegen_,
1016 namer_);
1017 printer.Run();
1018 }
1019 }
1020
DumpGraphWithDisassembly() const1021 void HGraphVisualizer::DumpGraphWithDisassembly() const {
1022 DCHECK(output_ != nullptr);
1023 if (!graph_->GetBlocks().empty()) {
1024 HGraphVisualizerPrinter printer(graph_,
1025 *output_,
1026 "disassembly",
1027 /* is_after_pass= */ true,
1028 /* graph_in_bad_state= */ false,
1029 codegen_,
1030 namer_,
1031 codegen_->GetDisassemblyInformation());
1032 printer.Run();
1033 }
1034 }
1035
DumpInstruction(std::ostream * output,HGraph * graph,HInstruction * instruction)1036 void HGraphVisualizer::DumpInstruction(std::ostream* output,
1037 HGraph* graph,
1038 HInstruction* instruction) {
1039 BlockNamer namer;
1040 HGraphVisualizerPrinter printer(graph,
1041 *output,
1042 /* pass_name= */ kDebugDumpName,
1043 /* is_after_pass= */ false,
1044 /* graph_in_bad_state= */ false,
1045 /* codegen= */ nullptr,
1046 /* namer= */ namer);
1047 printer.Run(instruction);
1048 }
1049
1050 } // namespace art
1051