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