• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 HIDDEN {
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     StartAttributeStream("can_trigger_gc")
484         << std::boolalpha << array_set->GetSideEffects().Includes(SideEffects::CanTriggerGC())
485         << std::noboolalpha;
486     StartAttributeStream("write_barrier_kind") << array_set->GetWriteBarrierKind();
487   }
488 
VisitCompare(HCompare * compare)489   void VisitCompare(HCompare* compare) override {
490     StartAttributeStream("bias") << compare->GetBias();
491   }
492 
VisitCondition(HCondition * condition)493   void VisitCondition(HCondition* condition) override {
494     StartAttributeStream("bias") << condition->GetBias();
495   }
496 
VisitInvoke(HInvoke * invoke)497   void VisitInvoke(HInvoke* invoke) override {
498     StartAttributeStream("dex_file_index") << invoke->GetMethodReference().index;
499     ArtMethod* method = invoke->GetResolvedMethod();
500     // We don't print signatures, which conflict with c1visualizer format.
501     static constexpr bool kWithSignature = false;
502     // Note that we can only use the graph's dex file for the unresolved case. The
503     // other invokes might be coming from inlined methods.
504     ScopedObjectAccess soa(Thread::Current());
505     std::string method_name = (method == nullptr)
506         ? invoke->GetMethodReference().PrettyMethod(kWithSignature)
507         : method->PrettyMethod(kWithSignature);
508     StartAttributeStream("method_name") << method_name;
509     StartAttributeStream("always_throws") << std::boolalpha
510                                           << invoke->AlwaysThrows()
511                                           << std::noboolalpha;
512     if (method != nullptr) {
513       StartAttributeStream("method_index") << method->GetMethodIndex();
514     }
515   }
516 
VisitInvokeUnresolved(HInvokeUnresolved * invoke)517   void VisitInvokeUnresolved(HInvokeUnresolved* invoke) override {
518     VisitInvoke(invoke);
519     StartAttributeStream("invoke_type") << invoke->GetInvokeType();
520   }
521 
VisitInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)522   void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) override {
523     VisitInvoke(invoke);
524     StartAttributeStream("method_load_kind") << invoke->GetMethodLoadKind();
525     StartAttributeStream("intrinsic") << invoke->GetIntrinsic();
526     if (invoke->IsStatic()) {
527       StartAttributeStream("clinit_check") << invoke->GetClinitCheckRequirement();
528     }
529   }
530 
VisitInvokeVirtual(HInvokeVirtual * invoke)531   void VisitInvokeVirtual(HInvokeVirtual* invoke) override {
532     VisitInvoke(invoke);
533     StartAttributeStream("intrinsic") << invoke->GetIntrinsic();
534   }
535 
VisitInvokePolymorphic(HInvokePolymorphic * invoke)536   void VisitInvokePolymorphic(HInvokePolymorphic* invoke) override {
537     VisitInvoke(invoke);
538     StartAttributeStream("invoke_type") << "InvokePolymorphic";
539   }
540 
VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet * iget)541   void VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet* iget) override {
542     StartAttributeStream("field_name") <<
543         iget->GetFieldInfo().GetDexFile().PrettyField(iget->GetFieldInfo().GetFieldIndex(),
544                                                       /* with type */ false);
545     StartAttributeStream("field_type") << iget->GetFieldType();
546   }
547 
VisitInstanceFieldGet(HInstanceFieldGet * iget)548   void VisitInstanceFieldGet(HInstanceFieldGet* iget) override {
549     StartAttributeStream("field_name") <<
550         iget->GetFieldInfo().GetDexFile().PrettyField(iget->GetFieldInfo().GetFieldIndex(),
551                                                       /* with type */ false);
552     StartAttributeStream("field_type") << iget->GetFieldType();
553   }
554 
VisitInstanceFieldSet(HInstanceFieldSet * iset)555   void VisitInstanceFieldSet(HInstanceFieldSet* iset) override {
556     StartAttributeStream("field_name") <<
557         iset->GetFieldInfo().GetDexFile().PrettyField(iset->GetFieldInfo().GetFieldIndex(),
558                                                       /* with type */ false);
559     StartAttributeStream("field_type") << iset->GetFieldType();
560     StartAttributeStream("predicated")
561         << std::boolalpha << iset->GetIsPredicatedSet() << std::noboolalpha;
562     StartAttributeStream("write_barrier_kind") << iset->GetWriteBarrierKind();
563   }
564 
VisitStaticFieldGet(HStaticFieldGet * sget)565   void VisitStaticFieldGet(HStaticFieldGet* sget) override {
566     StartAttributeStream("field_name") <<
567         sget->GetFieldInfo().GetDexFile().PrettyField(sget->GetFieldInfo().GetFieldIndex(),
568                                                       /* with type */ false);
569     StartAttributeStream("field_type") << sget->GetFieldType();
570   }
571 
VisitStaticFieldSet(HStaticFieldSet * sset)572   void VisitStaticFieldSet(HStaticFieldSet* sset) override {
573     StartAttributeStream("field_name") <<
574         sset->GetFieldInfo().GetDexFile().PrettyField(sset->GetFieldInfo().GetFieldIndex(),
575                                                       /* with type */ false);
576     StartAttributeStream("field_type") << sset->GetFieldType();
577     StartAttributeStream("write_barrier_kind") << sset->GetWriteBarrierKind();
578   }
579 
VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet * field_access)580   void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* field_access) override {
581     StartAttributeStream("field_type") << field_access->GetFieldType();
582   }
583 
VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet * field_access)584   void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* field_access) override {
585     StartAttributeStream("field_type") << field_access->GetFieldType();
586   }
587 
VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet * field_access)588   void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* field_access) override {
589     StartAttributeStream("field_type") << field_access->GetFieldType();
590   }
591 
VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet * field_access)592   void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* field_access) override {
593     StartAttributeStream("field_type") << field_access->GetFieldType();
594   }
595 
VisitTryBoundary(HTryBoundary * try_boundary)596   void VisitTryBoundary(HTryBoundary* try_boundary) override {
597     StartAttributeStream("kind") << (try_boundary->IsEntry() ? "entry" : "exit");
598   }
599 
VisitGoto(HGoto * instruction)600   void VisitGoto(HGoto* instruction) override {
601     StartAttributeStream("target") << namer_.GetName(instruction->GetBlock()->GetSingleSuccessor());
602   }
603 
VisitDeoptimize(HDeoptimize * deoptimize)604   void VisitDeoptimize(HDeoptimize* deoptimize) override {
605     StartAttributeStream("kind") << deoptimize->GetKind();
606   }
607 
VisitVecOperation(HVecOperation * vec_operation)608   void VisitVecOperation(HVecOperation* vec_operation) override {
609     StartAttributeStream("packed_type") << vec_operation->GetPackedType();
610   }
611 
VisitVecMemoryOperation(HVecMemoryOperation * vec_mem_operation)612   void VisitVecMemoryOperation(HVecMemoryOperation* vec_mem_operation) override {
613     StartAttributeStream("alignment") << vec_mem_operation->GetAlignment().ToString();
614   }
615 
VisitVecHalvingAdd(HVecHalvingAdd * hadd)616   void VisitVecHalvingAdd(HVecHalvingAdd* hadd) override {
617     VisitVecBinaryOperation(hadd);
618     StartAttributeStream("rounded") << std::boolalpha << hadd->IsRounded() << std::noboolalpha;
619   }
620 
VisitVecMultiplyAccumulate(HVecMultiplyAccumulate * instruction)621   void VisitVecMultiplyAccumulate(HVecMultiplyAccumulate* instruction) override {
622     VisitVecOperation(instruction);
623     StartAttributeStream("kind") << instruction->GetOpKind();
624   }
625 
VisitVecDotProd(HVecDotProd * instruction)626   void VisitVecDotProd(HVecDotProd* instruction) override {
627     VisitVecOperation(instruction);
628     DataType::Type arg_type = instruction->InputAt(1)->AsVecOperation()->GetPackedType();
629     StartAttributeStream("type") << (instruction->IsZeroExtending() ?
630                                     DataType::ToUnsigned(arg_type) :
631                                     DataType::ToSigned(arg_type));
632   }
633 
634 #if defined(ART_ENABLE_CODEGEN_arm) || defined(ART_ENABLE_CODEGEN_arm64)
VisitMultiplyAccumulate(HMultiplyAccumulate * instruction)635   void VisitMultiplyAccumulate(HMultiplyAccumulate* instruction) override {
636     StartAttributeStream("kind") << instruction->GetOpKind();
637   }
638 
VisitBitwiseNegatedRight(HBitwiseNegatedRight * instruction)639   void VisitBitwiseNegatedRight(HBitwiseNegatedRight* instruction) override {
640     StartAttributeStream("kind") << instruction->GetOpKind();
641   }
642 
VisitDataProcWithShifterOp(HDataProcWithShifterOp * instruction)643   void VisitDataProcWithShifterOp(HDataProcWithShifterOp* instruction) override {
644     StartAttributeStream("kind") << instruction->GetInstrKind() << "+" << instruction->GetOpKind();
645     if (HDataProcWithShifterOp::IsShiftOp(instruction->GetOpKind())) {
646       StartAttributeStream("shift") << instruction->GetShiftAmount();
647     }
648   }
649 #endif
650 
IsPass(const char * name)651   bool IsPass(const char* name) {
652     return strcmp(pass_name_, name) == 0;
653   }
654 
IsDebugDump()655   bool IsDebugDump() {
656     return IsPass(kDebugDumpGraphName) || IsPass(kDebugDumpName);
657   }
658 
PrintInstruction(HInstruction * instruction)659   void PrintInstruction(HInstruction* instruction) {
660     output_ << instruction->DebugName();
661     HConstInputsRef inputs = instruction->GetInputs();
662     if (!inputs.empty()) {
663       StringList input_list;
664       for (const HInstruction* input : inputs) {
665         input_list.NewEntryStream() << DataType::TypeId(input->GetType()) << input->GetId();
666       }
667       StartAttributeStream() << input_list;
668     }
669     if (instruction->GetDexPc() != kNoDexPc) {
670       StartAttributeStream("dex_pc") << instruction->GetDexPc();
671     } else {
672       StartAttributeStream("dex_pc") << "n/a";
673     }
674     HBasicBlock* block = instruction->GetBlock();
675     StartAttributeStream("block") << namer_.GetName(block);
676 
677     instruction->Accept(this);
678     if (instruction->HasEnvironment()) {
679       StringList envs;
680       for (HEnvironment* environment = instruction->GetEnvironment();
681            environment != nullptr;
682            environment = environment->GetParent()) {
683         StringList vregs;
684         for (size_t i = 0, e = environment->Size(); i < e; ++i) {
685           HInstruction* insn = environment->GetInstructionAt(i);
686           if (insn != nullptr) {
687             vregs.NewEntryStream() << DataType::TypeId(insn->GetType()) << insn->GetId();
688           } else {
689             vregs.NewEntryStream() << "_";
690           }
691         }
692         envs.NewEntryStream() << vregs;
693       }
694       StartAttributeStream("env") << envs;
695     }
696     if (IsPass(SsaLivenessAnalysis::kLivenessPassName)
697         && is_after_pass_
698         && instruction->GetLifetimePosition() != kNoLifetime) {
699       StartAttributeStream("liveness") << instruction->GetLifetimePosition();
700       if (instruction->HasLiveInterval()) {
701         LiveInterval* interval = instruction->GetLiveInterval();
702         StartAttributeStream("ranges")
703             << StringList(interval->GetFirstRange(), StringList::kSetBrackets);
704         StartAttributeStream("uses") << StringList(interval->GetUses());
705         StartAttributeStream("env_uses") << StringList(interval->GetEnvironmentUses());
706         StartAttributeStream("is_fixed") << interval->IsFixed();
707         StartAttributeStream("is_split") << interval->IsSplit();
708         StartAttributeStream("is_low") << interval->IsLowInterval();
709         StartAttributeStream("is_high") << interval->IsHighInterval();
710       }
711     }
712 
713     if (IsPass(RegisterAllocator::kRegisterAllocatorPassName) && is_after_pass_) {
714       StartAttributeStream("liveness") << instruction->GetLifetimePosition();
715       LocationSummary* locations = instruction->GetLocations();
716       if (locations != nullptr) {
717         StringList input_list;
718         for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
719           DumpLocation(input_list.NewEntryStream(), locations->InAt(i));
720         }
721         std::ostream& attr = StartAttributeStream("locations");
722         attr << input_list << "->";
723         DumpLocation(attr, locations->Out());
724       }
725     }
726 
727     HLoopInformation* loop_info = (block != nullptr) ? block->GetLoopInformation() : nullptr;
728     if (loop_info == nullptr) {
729       StartAttributeStream("loop") << "none";
730     } else {
731       StartAttributeStream("loop") << namer_.GetName(loop_info->GetHeader());
732       HLoopInformation* outer = loop_info->GetPreHeader()->GetLoopInformation();
733       if (outer != nullptr) {
734         StartAttributeStream("outer_loop") << namer_.GetName(outer->GetHeader());
735       } else {
736         StartAttributeStream("outer_loop") << "none";
737       }
738       StartAttributeStream("irreducible")
739           << std::boolalpha << loop_info->IsIrreducible() << std::noboolalpha;
740     }
741 
742     // For the builder and the inliner, we want to add extra information on HInstructions
743     // that have reference types, and also HInstanceOf/HCheckcast.
744     if ((IsPass(HGraphBuilder::kBuilderPassName)
745         || IsPass(HInliner::kInlinerPassName)
746         || IsDebugDump())
747         && (instruction->GetType() == DataType::Type::kReference ||
748             instruction->IsInstanceOf() ||
749             instruction->IsCheckCast())) {
750       ReferenceTypeInfo info = (instruction->GetType() == DataType::Type::kReference)
751           ? instruction->IsLoadClass()
752               ? instruction->AsLoadClass()->GetLoadedClassRTI()
753               : instruction->GetReferenceTypeInfo()
754           : instruction->IsInstanceOf()
755               ? instruction->AsInstanceOf()->GetTargetClassRTI()
756               : instruction->AsCheckCast()->GetTargetClassRTI();
757       ScopedObjectAccess soa(Thread::Current());
758       if (info.IsValid()) {
759         StartAttributeStream("klass")
760             << mirror::Class::PrettyDescriptor(info.GetTypeHandle().Get());
761         if (instruction->GetType() == DataType::Type::kReference) {
762           StartAttributeStream("can_be_null")
763               << std::boolalpha << instruction->CanBeNull() << std::noboolalpha;
764         }
765         StartAttributeStream("exact") << std::boolalpha << info.IsExact() << std::noboolalpha;
766       } else if (instruction->IsLoadClass() ||
767                  instruction->IsInstanceOf() ||
768                  instruction->IsCheckCast()) {
769         StartAttributeStream("klass") << "unresolved";
770       } else {
771         StartAttributeStream("klass") << "invalid";
772       }
773     }
774     if (disasm_info_ != nullptr) {
775       DCHECK(disassembler_ != nullptr);
776       // If the information is available, disassemble the code generated for
777       // this instruction.
778       auto it = disasm_info_->GetInstructionIntervals().find(instruction);
779       if (it != disasm_info_->GetInstructionIntervals().end()
780           && it->second.start != it->second.end) {
781         output_ << "\n";
782         disassembler_->Disassemble(output_, it->second.start, it->second.end);
783       }
784     }
785   }
786 
PrintInstructions(const HInstructionList & list)787   void PrintInstructions(const HInstructionList& list) {
788     for (HInstructionIterator it(list); !it.Done(); it.Advance()) {
789       HInstruction* instruction = it.Current();
790       int bci = 0;
791       size_t num_uses = instruction->GetUses().SizeSlow();
792       AddIndent();
793       output_ << bci << " " << num_uses << " "
794               << DataType::TypeId(instruction->GetType()) << instruction->GetId() << " ";
795       PrintInstruction(instruction);
796       output_ << " " << kEndInstructionMarker << "\n";
797     }
798   }
799 
DumpStartOfDisassemblyBlock(const char * block_name,int predecessor_index,int successor_index)800   void DumpStartOfDisassemblyBlock(const char* block_name,
801                                    int predecessor_index,
802                                    int successor_index) {
803     StartTag("block");
804     PrintProperty("name", block_name);
805     PrintInt("from_bci", -1);
806     PrintInt("to_bci", -1);
807     if (predecessor_index != -1) {
808       PrintProperty("predecessors", "B", predecessor_index);
809     } else {
810       PrintEmptyProperty("predecessors");
811     }
812     if (successor_index != -1) {
813       PrintProperty("successors", "B", successor_index);
814     } else {
815       PrintEmptyProperty("successors");
816     }
817     PrintEmptyProperty("xhandlers");
818     PrintEmptyProperty("flags");
819     StartTag("states");
820     StartTag("locals");
821     PrintInt("size", 0);
822     PrintProperty("method", "None");
823     EndTag("locals");
824     EndTag("states");
825     StartTag("HIR");
826   }
827 
DumpEndOfDisassemblyBlock()828   void DumpEndOfDisassemblyBlock() {
829     EndTag("HIR");
830     EndTag("block");
831   }
832 
DumpDisassemblyBlockForFrameEntry()833   void DumpDisassemblyBlockForFrameEntry() {
834     DumpStartOfDisassemblyBlock(kDisassemblyBlockFrameEntry,
835                                 -1,
836                                 GetGraph()->GetEntryBlock()->GetBlockId());
837     output_ << "    0 0 disasm " << kDisassemblyBlockFrameEntry << " ";
838     GeneratedCodeInterval frame_entry = disasm_info_->GetFrameEntryInterval();
839     if (frame_entry.start != frame_entry.end) {
840       output_ << "\n";
841       disassembler_->Disassemble(output_, frame_entry.start, frame_entry.end);
842     }
843     output_ << kEndInstructionMarker << "\n";
844     DumpEndOfDisassemblyBlock();
845   }
846 
DumpDisassemblyBlockForSlowPaths()847   void DumpDisassemblyBlockForSlowPaths() {
848     if (disasm_info_->GetSlowPathIntervals().empty()) {
849       return;
850     }
851     // If the graph has an exit block we attach the block for the slow paths
852     // after it. Else we just add the block to the graph without linking it to
853     // any other.
854     DumpStartOfDisassemblyBlock(
855         kDisassemblyBlockSlowPaths,
856         GetGraph()->HasExitBlock() ? GetGraph()->GetExitBlock()->GetBlockId() : -1,
857         -1);
858     for (SlowPathCodeInfo info : disasm_info_->GetSlowPathIntervals()) {
859       output_ << "    0 0 disasm " << info.slow_path->GetDescription() << "\n";
860       disassembler_->Disassemble(output_, info.code_interval.start, info.code_interval.end);
861       output_ << kEndInstructionMarker << "\n";
862     }
863     DumpEndOfDisassemblyBlock();
864   }
865 
Run()866   void Run() {
867     StartTag("cfg");
868     std::ostringstream oss;
869     oss << pass_name_;
870     if (!IsDebugDump()) {
871       oss << " (" << (is_after_pass_ ? "after" : "before")
872           << (graph_in_bad_state_ ? ", bad_state" : "") << ")";
873     }
874     PrintProperty("name", oss.str().c_str());
875     if (disasm_info_ != nullptr) {
876       DumpDisassemblyBlockForFrameEntry();
877     }
878     VisitInsertionOrder();
879     if (disasm_info_ != nullptr) {
880       DumpDisassemblyBlockForSlowPaths();
881     }
882     EndTag("cfg");
883     Flush();
884   }
885 
Run(HInstruction * instruction)886   void Run(HInstruction* instruction) {
887     output_ << DataType::TypeId(instruction->GetType()) << instruction->GetId() << " ";
888     PrintInstruction(instruction);
889     Flush();
890   }
891 
VisitBasicBlock(HBasicBlock * block)892   void VisitBasicBlock(HBasicBlock* block) override {
893     StartTag("block");
894     PrintProperty("name", block);
895     if (block->GetLifetimeStart() != kNoLifetime) {
896       // Piggy back on these fields to show the lifetime of the block.
897       PrintInt("from_bci", block->GetLifetimeStart());
898       PrintInt("to_bci", block->GetLifetimeEnd());
899     } else if (!IsDebugDump()) {
900       // Don't print useless information to logcat.
901       PrintInt("from_bci", -1);
902       PrintInt("to_bci", -1);
903     }
904     PrintPredecessors(block);
905     PrintSuccessors(block);
906     PrintExceptionHandlers(block);
907 
908     if (block->IsCatchBlock()) {
909       PrintProperty("flags", "catch_block");
910     } else if (block->IsTryBlock()) {
911       std::stringstream flags_properties;
912       flags_properties << "try_start "
913                        << namer_.GetName(block->GetTryCatchInformation()->GetTryEntry().GetBlock());
914       PrintProperty("flags", flags_properties.str().c_str());
915     } else if (!IsDebugDump()) {
916       // Don't print useless information to logcat
917       PrintEmptyProperty("flags");
918     }
919 
920     if (block->GetDominator() != nullptr) {
921       PrintProperty("dominator", block->GetDominator());
922     }
923 
924     if (!IsDebugDump() || !block->GetPhis().IsEmpty()) {
925       StartTag("states");
926       StartTag("locals");
927       PrintInt("size", 0);
928       PrintProperty("method", "None");
929       for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
930         AddIndent();
931         HInstruction* instruction = it.Current();
932         output_ << instruction->GetId() << " " << DataType::TypeId(instruction->GetType())
933                 << instruction->GetId() << "[ ";
934         for (const HInstruction* input : instruction->GetInputs()) {
935           output_ << input->GetId() << " ";
936         }
937         output_ << "]\n";
938       }
939       EndTag("locals");
940       EndTag("states");
941     }
942 
943     StartTag("HIR");
944     PrintInstructions(block->GetPhis());
945     PrintInstructions(block->GetInstructions());
946     EndTag("HIR");
947     EndTag("block");
948   }
949 
950   static constexpr const char* const kEndInstructionMarker = "<|@";
951   static constexpr const char* const kDisassemblyBlockFrameEntry = "FrameEntry";
952   static constexpr const char* const kDisassemblyBlockSlowPaths = "SlowPaths";
953 
954  private:
955   std::ostream& output_;
956   const char* pass_name_;
957   const bool is_after_pass_;
958   const bool graph_in_bad_state_;
959   const CodeGenerator* codegen_;
960   const DisassemblyInformation* disasm_info_;
961   const BlockNamer& namer_;
962   std::unique_ptr<HGraphVisualizerDisassembler> disassembler_;
963   size_t indent_;
964 
965   DISALLOW_COPY_AND_ASSIGN(HGraphVisualizerPrinter);
966 };
967 
PrintName(std::ostream & os,HBasicBlock * blk) const968 std::ostream& HGraphVisualizer::OptionalDefaultNamer::PrintName(std::ostream& os,
969                                                                 HBasicBlock* blk) const {
970   if (namer_) {
971     return namer_->get().PrintName(os, blk);
972   } else {
973     return BlockNamer::PrintName(os, blk);
974   }
975 }
976 
HGraphVisualizer(std::ostream * output,HGraph * graph,const CodeGenerator * codegen,std::optional<std::reference_wrapper<const BlockNamer>> namer)977 HGraphVisualizer::HGraphVisualizer(std::ostream* output,
978                                    HGraph* graph,
979                                    const CodeGenerator* codegen,
980                                    std::optional<std::reference_wrapper<const BlockNamer>> namer)
981     : output_(output), graph_(graph), codegen_(codegen), namer_(namer) {}
982 
PrintHeader(const char * method_name) const983 void HGraphVisualizer::PrintHeader(const char* method_name) const {
984   DCHECK(output_ != nullptr);
985   HGraphVisualizerPrinter printer(graph_, *output_, "", true, false, codegen_, namer_);
986   printer.StartTag("compilation");
987   printer.PrintProperty("name", method_name);
988   printer.PrintProperty("method", method_name);
989   printer.PrintTime("date");
990   printer.EndTag("compilation");
991   printer.Flush();
992 }
993 
InsertMetaDataAsCompilationBlock(const std::string & meta_data)994 std::string HGraphVisualizer::InsertMetaDataAsCompilationBlock(const std::string& meta_data) {
995   std::string time_str = std::to_string(time(nullptr));
996   std::string quoted_meta_data = "\"" + meta_data + "\"";
997   return StringPrintf("begin_compilation\n"
998                       "  name %s\n"
999                       "  method %s\n"
1000                       "  date %s\n"
1001                       "end_compilation\n",
1002                       quoted_meta_data.c_str(),
1003                       quoted_meta_data.c_str(),
1004                       time_str.c_str());
1005 }
1006 
DumpGraphDebug() const1007 void HGraphVisualizer::DumpGraphDebug() const {
1008   DumpGraph(/* pass_name= */ kDebugDumpGraphName,
1009             /* is_after_pass= */ false,
1010             /* graph_in_bad_state= */ true);
1011 }
1012 
DumpGraph(const char * pass_name,bool is_after_pass,bool graph_in_bad_state) const1013 void HGraphVisualizer::DumpGraph(const char* pass_name,
1014                                  bool is_after_pass,
1015                                  bool graph_in_bad_state) const {
1016   DCHECK(output_ != nullptr);
1017   if (!graph_->GetBlocks().empty()) {
1018     HGraphVisualizerPrinter printer(graph_,
1019                                     *output_,
1020                                     pass_name,
1021                                     is_after_pass,
1022                                     graph_in_bad_state,
1023                                     codegen_,
1024                                     namer_);
1025     printer.Run();
1026   }
1027 }
1028 
DumpGraphWithDisassembly() const1029 void HGraphVisualizer::DumpGraphWithDisassembly() const {
1030   DCHECK(output_ != nullptr);
1031   if (!graph_->GetBlocks().empty()) {
1032     HGraphVisualizerPrinter printer(graph_,
1033                                     *output_,
1034                                     "disassembly",
1035                                     /* is_after_pass= */ true,
1036                                     /* graph_in_bad_state= */ false,
1037                                     codegen_,
1038                                     namer_,
1039                                     codegen_->GetDisassemblyInformation());
1040     printer.Run();
1041   }
1042 }
1043 
DumpInstruction(std::ostream * output,HGraph * graph,HInstruction * instruction)1044 void HGraphVisualizer::DumpInstruction(std::ostream* output,
1045                                        HGraph* graph,
1046                                        HInstruction* instruction) {
1047   BlockNamer namer;
1048   HGraphVisualizerPrinter printer(graph,
1049                                   *output,
1050                                   /* pass_name= */ kDebugDumpName,
1051                                   /* is_after_pass= */ false,
1052                                   /* graph_in_bad_state= */ false,
1053                                   /* codegen= */ nullptr,
1054                                   /* namer= */ namer);
1055   printer.Run(instruction);
1056 }
1057 
1058 }  // namespace art
1059