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 }
113 }
114
115 // On target: load `libart-disassembler` only when required (to save on memory).
116 // On host: `libart-disassembler` should be linked directly (either as a static or dynamic lib)
117 #ifdef ART_TARGET
118 using create_disasm_prototype = Disassembler*(InstructionSet, DisassemblerOptions*);
119 #endif
120
121 class HGraphVisualizerDisassembler {
122 public:
HGraphVisualizerDisassembler(InstructionSet instruction_set,const uint8_t * base_address,const uint8_t * end_address)123 HGraphVisualizerDisassembler(InstructionSet instruction_set,
124 const uint8_t* base_address,
125 const uint8_t* end_address)
126 : instruction_set_(instruction_set), disassembler_(nullptr) {
127 #ifdef ART_TARGET
128 constexpr const char* libart_disassembler_so_name =
129 kIsDebugBuild ? "libartd-disassembler.so" : "libart-disassembler.so";
130 libart_disassembler_handle_ = dlopen(libart_disassembler_so_name, RTLD_NOW);
131 if (libart_disassembler_handle_ == nullptr) {
132 LOG(ERROR) << "Failed to dlopen " << libart_disassembler_so_name << ": " << dlerror();
133 return;
134 }
135 constexpr const char* create_disassembler_symbol = "create_disassembler";
136 create_disasm_prototype* create_disassembler = reinterpret_cast<create_disasm_prototype*>(
137 dlsym(libart_disassembler_handle_, create_disassembler_symbol));
138 if (create_disassembler == nullptr) {
139 LOG(ERROR) << "Could not find " << create_disassembler_symbol << " entry in "
140 << libart_disassembler_so_name << ": " << dlerror();
141 return;
142 }
143 #endif
144 // Reading the disassembly from 0x0 is easier, so we print relative
145 // addresses. We will only disassemble the code once everything has
146 // been generated, so we can read data in literal pools.
147 disassembler_ = std::unique_ptr<Disassembler>(create_disassembler(
148 instruction_set,
149 new DisassemblerOptions(/* absolute_addresses= */ false,
150 base_address,
151 end_address,
152 /* can_read_literals= */ true,
153 Is64BitInstructionSet(instruction_set)
154 ? &Thread::DumpThreadOffset<PointerSize::k64>
155 : &Thread::DumpThreadOffset<PointerSize::k32>)));
156 }
157
~HGraphVisualizerDisassembler()158 ~HGraphVisualizerDisassembler() {
159 // We need to call ~Disassembler() before we close the library.
160 disassembler_.reset();
161 #ifdef ART_TARGET
162 if (libart_disassembler_handle_ != nullptr) {
163 dlclose(libart_disassembler_handle_);
164 }
165 #endif
166 }
167
Disassemble(std::ostream & output,size_t start,size_t end) const168 void Disassemble(std::ostream& output, size_t start, size_t end) const {
169 if (disassembler_ == nullptr) {
170 return;
171 }
172
173 const uint8_t* base = disassembler_->GetDisassemblerOptions()->base_address_;
174 if (instruction_set_ == InstructionSet::kThumb2) {
175 // ARM and Thumb-2 use the same disassembler. The bottom bit of the
176 // address is used to distinguish between the two.
177 base += 1;
178 }
179 disassembler_->Dump(output, base + start, base + end);
180 }
181
182 private:
183 InstructionSet instruction_set_;
184 std::unique_ptr<Disassembler> disassembler_;
185
186 #ifdef ART_TARGET
187 void* libart_disassembler_handle_;
188 #endif
189 };
190
191
192 /**
193 * HGraph visitor to generate a file suitable for the c1visualizer tool and IRHydra.
194 */
195 class HGraphVisualizerPrinter final : public HGraphDelegateVisitor {
196 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)197 HGraphVisualizerPrinter(HGraph* graph,
198 std::ostream& output,
199 const char* pass_name,
200 bool is_after_pass,
201 bool graph_in_bad_state,
202 const CodeGenerator* codegen,
203 const BlockNamer& namer,
204 const DisassemblyInformation* disasm_info = nullptr)
205 : HGraphDelegateVisitor(graph),
206 output_(output),
207 pass_name_(pass_name),
208 is_after_pass_(is_after_pass),
209 graph_in_bad_state_(graph_in_bad_state),
210 codegen_(codegen),
211 disasm_info_(disasm_info),
212 namer_(namer),
213 disassembler_(disasm_info_ != nullptr
214 ? new HGraphVisualizerDisassembler(
215 codegen_->GetInstructionSet(),
216 codegen_->GetAssembler().CodeBufferBaseAddress(),
217 codegen_->GetAssembler().CodeBufferBaseAddress()
218 + codegen_->GetAssembler().CodeSize())
219 : nullptr),
220 indent_(0) {}
221
Flush()222 void Flush() {
223 // We use "\n" instead of std::endl to avoid implicit flushing which
224 // generates too many syscalls during debug-GC tests (b/27826765).
225 output_ << std::flush;
226 }
227
StartTag(const char * name)228 void StartTag(const char* name) {
229 AddIndent();
230 output_ << "begin_" << name << "\n";
231 indent_++;
232 }
233
EndTag(const char * name)234 void EndTag(const char* name) {
235 indent_--;
236 AddIndent();
237 output_ << "end_" << name << "\n";
238 }
239
PrintProperty(const char * name,HBasicBlock * blk)240 void PrintProperty(const char* name, HBasicBlock* blk) {
241 AddIndent();
242 output_ << name << " \"" << namer_.GetName(blk) << "\"\n";
243 }
244
PrintProperty(const char * name,const char * property)245 void PrintProperty(const char* name, const char* property) {
246 AddIndent();
247 output_ << name << " \"" << property << "\"\n";
248 }
249
PrintProperty(const char * name,const char * property,int id)250 void PrintProperty(const char* name, const char* property, int id) {
251 AddIndent();
252 output_ << name << " \"" << property << id << "\"\n";
253 }
254
PrintEmptyProperty(const char * name)255 void PrintEmptyProperty(const char* name) {
256 AddIndent();
257 output_ << name << "\n";
258 }
259
PrintTime(const char * name)260 void PrintTime(const char* name) {
261 AddIndent();
262 output_ << name << " " << time(nullptr) << "\n";
263 }
264
PrintInt(const char * name,int value)265 void PrintInt(const char* name, int value) {
266 AddIndent();
267 output_ << name << " " << value << "\n";
268 }
269
AddIndent()270 void AddIndent() {
271 for (size_t i = 0; i < indent_; ++i) {
272 output_ << " ";
273 }
274 }
275
PrintPredecessors(HBasicBlock * block)276 void PrintPredecessors(HBasicBlock* block) {
277 AddIndent();
278 output_ << "predecessors";
279 for (HBasicBlock* predecessor : block->GetPredecessors()) {
280 output_ << " \"" << namer_.GetName(predecessor) << "\" ";
281 }
282 if (block->IsEntryBlock() && (disasm_info_ != nullptr)) {
283 output_ << " \"" << kDisassemblyBlockFrameEntry << "\" ";
284 }
285 output_<< "\n";
286 }
287
PrintSuccessors(HBasicBlock * block)288 void PrintSuccessors(HBasicBlock* block) {
289 AddIndent();
290 output_ << "successors";
291 for (HBasicBlock* successor : block->GetNormalSuccessors()) {
292 output_ << " \"" << namer_.GetName(successor) << "\" ";
293 }
294 output_<< "\n";
295 }
296
PrintExceptionHandlers(HBasicBlock * block)297 void PrintExceptionHandlers(HBasicBlock* block) {
298 bool has_slow_paths = block->IsExitBlock() &&
299 (disasm_info_ != nullptr) &&
300 !disasm_info_->GetSlowPathIntervals().empty();
301 if (IsDebugDump() && block->GetExceptionalSuccessors().empty() && !has_slow_paths) {
302 return;
303 }
304 AddIndent();
305 output_ << "xhandlers";
306 for (HBasicBlock* handler : block->GetExceptionalSuccessors()) {
307 output_ << " \"" << namer_.GetName(handler) << "\" ";
308 }
309 if (has_slow_paths) {
310 output_ << " \"" << kDisassemblyBlockSlowPaths << "\" ";
311 }
312 output_<< "\n";
313 }
314
DumpLocation(std::ostream & stream,const Location & location)315 void DumpLocation(std::ostream& stream, const Location& location) {
316 DCHECK(codegen_ != nullptr);
317 if (location.IsRegister()) {
318 codegen_->DumpCoreRegister(stream, location.reg());
319 } else if (location.IsFpuRegister()) {
320 codegen_->DumpFloatingPointRegister(stream, location.reg());
321 } else if (location.IsConstant()) {
322 stream << "#";
323 HConstant* constant = location.GetConstant();
324 if (constant->IsIntConstant()) {
325 stream << constant->AsIntConstant()->GetValue();
326 } else if (constant->IsLongConstant()) {
327 stream << constant->AsLongConstant()->GetValue();
328 } else if (constant->IsFloatConstant()) {
329 stream << constant->AsFloatConstant()->GetValue();
330 } else if (constant->IsDoubleConstant()) {
331 stream << constant->AsDoubleConstant()->GetValue();
332 } else if (constant->IsNullConstant()) {
333 stream << "null";
334 }
335 } else if (location.IsInvalid()) {
336 stream << "invalid";
337 } else if (location.IsStackSlot()) {
338 stream << location.GetStackIndex() << "(sp)";
339 } else if (location.IsFpuRegisterPair()) {
340 codegen_->DumpFloatingPointRegister(stream, location.low());
341 stream << "|";
342 codegen_->DumpFloatingPointRegister(stream, location.high());
343 } else if (location.IsRegisterPair()) {
344 codegen_->DumpCoreRegister(stream, location.low());
345 stream << "|";
346 codegen_->DumpCoreRegister(stream, location.high());
347 } else if (location.IsUnallocated()) {
348 stream << "unallocated";
349 } else if (location.IsDoubleStackSlot()) {
350 stream << "2x" << location.GetStackIndex() << "(sp)";
351 } else {
352 DCHECK(location.IsSIMDStackSlot());
353 stream << "4x" << location.GetStackIndex() << "(sp)";
354 }
355 }
356
StartAttributeStream(const char * name=nullptr)357 std::ostream& StartAttributeStream(const char* name = nullptr) {
358 if (name == nullptr) {
359 output_ << " ";
360 } else {
361 DCHECK(!HasWhitespace(name)) << "Checker does not allow spaces in attributes";
362 output_ << " " << name << ":";
363 }
364 return output_;
365 }
366
VisitParallelMove(HParallelMove * instruction)367 void VisitParallelMove(HParallelMove* instruction) override {
368 StartAttributeStream("liveness") << instruction->GetLifetimePosition();
369 StringList moves;
370 for (size_t i = 0, e = instruction->NumMoves(); i < e; ++i) {
371 MoveOperands* move = instruction->MoveOperandsAt(i);
372 std::ostream& str = moves.NewEntryStream();
373 DumpLocation(str, move->GetSource());
374 str << "->";
375 DumpLocation(str, move->GetDestination());
376 }
377 StartAttributeStream("moves") << moves;
378 }
379
VisitIntConstant(HIntConstant * instruction)380 void VisitIntConstant(HIntConstant* instruction) override {
381 StartAttributeStream() << instruction->GetValue();
382 }
383
VisitLongConstant(HLongConstant * instruction)384 void VisitLongConstant(HLongConstant* instruction) override {
385 StartAttributeStream() << instruction->GetValue();
386 }
387
VisitFloatConstant(HFloatConstant * instruction)388 void VisitFloatConstant(HFloatConstant* instruction) override {
389 StartAttributeStream() << instruction->GetValue();
390 }
391
VisitDoubleConstant(HDoubleConstant * instruction)392 void VisitDoubleConstant(HDoubleConstant* instruction) override {
393 StartAttributeStream() << instruction->GetValue();
394 }
395
VisitPhi(HPhi * phi)396 void VisitPhi(HPhi* phi) override {
397 StartAttributeStream("reg") << phi->GetRegNumber();
398 StartAttributeStream("is_catch_phi") << std::boolalpha << phi->IsCatchPhi() << std::noboolalpha;
399 }
400
VisitMemoryBarrier(HMemoryBarrier * barrier)401 void VisitMemoryBarrier(HMemoryBarrier* barrier) override {
402 StartAttributeStream("kind") << barrier->GetBarrierKind();
403 }
404
VisitMonitorOperation(HMonitorOperation * monitor)405 void VisitMonitorOperation(HMonitorOperation* monitor) override {
406 StartAttributeStream("kind") << (monitor->IsEnter() ? "enter" : "exit");
407 }
408
VisitLoadClass(HLoadClass * load_class)409 void VisitLoadClass(HLoadClass* load_class) override {
410 StartAttributeStream("load_kind") << load_class->GetLoadKind();
411 StartAttributeStream("in_image") << std::boolalpha << load_class->IsInImage();
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
VisitIf(HIf * if_instr)497 void VisitIf(HIf* if_instr) override {
498 StartAttributeStream("true_count") << if_instr->GetTrueCount();
499 StartAttributeStream("false_count") << if_instr->GetFalseCount();
500 }
501
VisitInvoke(HInvoke * invoke)502 void VisitInvoke(HInvoke* invoke) override {
503 StartAttributeStream("dex_file_index") << invoke->GetMethodReference().index;
504 ArtMethod* method = invoke->GetResolvedMethod();
505 // We don't print signatures, which conflict with c1visualizer format.
506 static constexpr bool kWithSignature = false;
507 // Note that we can only use the graph's dex file for the unresolved case. The
508 // other invokes might be coming from inlined methods.
509 ScopedObjectAccess soa(Thread::Current());
510 std::string method_name = (method == nullptr)
511 ? invoke->GetMethodReference().PrettyMethod(kWithSignature)
512 : method->PrettyMethod(kWithSignature);
513 StartAttributeStream("method_name") << method_name;
514 StartAttributeStream("always_throws") << std::boolalpha
515 << invoke->AlwaysThrows()
516 << std::noboolalpha;
517 if (method != nullptr) {
518 StartAttributeStream("method_index") << method->GetMethodIndex();
519 }
520 }
521
VisitInvokeUnresolved(HInvokeUnresolved * invoke)522 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) override {
523 VisitInvoke(invoke);
524 StartAttributeStream("invoke_type") << invoke->GetInvokeType();
525 }
526
VisitInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)527 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) override {
528 VisitInvoke(invoke);
529 StartAttributeStream("method_load_kind") << invoke->GetMethodLoadKind();
530 StartAttributeStream("intrinsic") << invoke->GetIntrinsic();
531 if (invoke->IsStatic()) {
532 StartAttributeStream("clinit_check") << invoke->GetClinitCheckRequirement();
533 }
534 }
535
VisitInvokeVirtual(HInvokeVirtual * invoke)536 void VisitInvokeVirtual(HInvokeVirtual* invoke) override {
537 VisitInvoke(invoke);
538 StartAttributeStream("intrinsic") << invoke->GetIntrinsic();
539 }
540
VisitInvokePolymorphic(HInvokePolymorphic * invoke)541 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) override {
542 VisitInvoke(invoke);
543 StartAttributeStream("invoke_type") << "InvokePolymorphic";
544 }
545
VisitInstanceFieldGet(HInstanceFieldGet * iget)546 void VisitInstanceFieldGet(HInstanceFieldGet* iget) override {
547 StartAttributeStream("field_name") <<
548 iget->GetFieldInfo().GetDexFile().PrettyField(iget->GetFieldInfo().GetFieldIndex(),
549 /* with type */ false);
550 StartAttributeStream("field_type") << iget->GetFieldType();
551 }
552
VisitInstanceFieldSet(HInstanceFieldSet * iset)553 void VisitInstanceFieldSet(HInstanceFieldSet* iset) override {
554 StartAttributeStream("field_name") <<
555 iset->GetFieldInfo().GetDexFile().PrettyField(iset->GetFieldInfo().GetFieldIndex(),
556 /* with type */ false);
557 StartAttributeStream("field_type") << iset->GetFieldType();
558 StartAttributeStream("write_barrier_kind") << iset->GetWriteBarrierKind();
559 }
560
VisitStaticFieldGet(HStaticFieldGet * sget)561 void VisitStaticFieldGet(HStaticFieldGet* sget) override {
562 StartAttributeStream("field_name") <<
563 sget->GetFieldInfo().GetDexFile().PrettyField(sget->GetFieldInfo().GetFieldIndex(),
564 /* with type */ false);
565 StartAttributeStream("field_type") << sget->GetFieldType();
566 }
567
VisitStaticFieldSet(HStaticFieldSet * sset)568 void VisitStaticFieldSet(HStaticFieldSet* sset) override {
569 StartAttributeStream("field_name") <<
570 sset->GetFieldInfo().GetDexFile().PrettyField(sset->GetFieldInfo().GetFieldIndex(),
571 /* with type */ false);
572 StartAttributeStream("field_type") << sset->GetFieldType();
573 StartAttributeStream("write_barrier_kind") << sset->GetWriteBarrierKind();
574 }
575
VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet * field_access)576 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* field_access) override {
577 StartAttributeStream("field_type") << field_access->GetFieldType();
578 }
579
VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet * field_access)580 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* field_access) override {
581 StartAttributeStream("field_type") << field_access->GetFieldType();
582 }
583
VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet * field_access)584 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* field_access) override {
585 StartAttributeStream("field_type") << field_access->GetFieldType();
586 }
587
VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet * field_access)588 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* field_access) override {
589 StartAttributeStream("field_type") << field_access->GetFieldType();
590 }
591
VisitTryBoundary(HTryBoundary * try_boundary)592 void VisitTryBoundary(HTryBoundary* try_boundary) override {
593 StartAttributeStream("kind") << (try_boundary->IsEntry() ? "entry" : "exit");
594 }
595
VisitGoto(HGoto * instruction)596 void VisitGoto(HGoto* instruction) override {
597 StartAttributeStream("target") << namer_.GetName(instruction->GetBlock()->GetSingleSuccessor());
598 }
599
VisitDeoptimize(HDeoptimize * deoptimize)600 void VisitDeoptimize(HDeoptimize* deoptimize) override {
601 StartAttributeStream("kind") << deoptimize->GetKind();
602 }
603
VisitVecOperation(HVecOperation * vec_operation)604 void VisitVecOperation(HVecOperation* vec_operation) override {
605 StartAttributeStream("packed_type") << vec_operation->GetPackedType();
606 }
607
VisitVecMemoryOperation(HVecMemoryOperation * vec_mem_operation)608 void VisitVecMemoryOperation(HVecMemoryOperation* vec_mem_operation) override {
609 VisitVecOperation(vec_mem_operation);
610 StartAttributeStream("alignment") << vec_mem_operation->GetAlignment().ToString();
611 }
612
VisitVecHalvingAdd(HVecHalvingAdd * hadd)613 void VisitVecHalvingAdd(HVecHalvingAdd* hadd) override {
614 VisitVecBinaryOperation(hadd);
615 StartAttributeStream("rounded") << std::boolalpha << hadd->IsRounded() << std::noboolalpha;
616 }
617
VisitVecMultiplyAccumulate(HVecMultiplyAccumulate * instruction)618 void VisitVecMultiplyAccumulate(HVecMultiplyAccumulate* instruction) override {
619 VisitVecOperation(instruction);
620 StartAttributeStream("kind") << instruction->GetOpKind();
621 }
622
VisitVecDotProd(HVecDotProd * instruction)623 void VisitVecDotProd(HVecDotProd* instruction) override {
624 VisitVecOperation(instruction);
625 DataType::Type arg_type = instruction->InputAt(1)->AsVecOperation()->GetPackedType();
626 StartAttributeStream("type") << (instruction->IsZeroExtending() ?
627 DataType::ToUnsigned(arg_type) :
628 DataType::ToSigned(arg_type));
629 }
630
VisitBitwiseNegatedRight(HBitwiseNegatedRight * instruction)631 void VisitBitwiseNegatedRight(HBitwiseNegatedRight* instruction) override {
632 StartAttributeStream("kind") << instruction->GetOpKind();
633 }
634
635 #if defined(ART_ENABLE_CODEGEN_arm) || defined(ART_ENABLE_CODEGEN_arm64)
VisitMultiplyAccumulate(HMultiplyAccumulate * instruction)636 void VisitMultiplyAccumulate(HMultiplyAccumulate* instruction) override {
637 StartAttributeStream("kind") << instruction->GetOpKind();
638 }
639
VisitDataProcWithShifterOp(HDataProcWithShifterOp * instruction)640 void VisitDataProcWithShifterOp(HDataProcWithShifterOp* instruction) override {
641 StartAttributeStream("kind") << instruction->GetInstrKind() << "+" << instruction->GetOpKind();
642 if (HDataProcWithShifterOp::IsShiftOp(instruction->GetOpKind())) {
643 StartAttributeStream("shift") << instruction->GetShiftAmount();
644 }
645 }
646 #endif
647
648 #if defined(ART_ENABLE_CODEGEN_riscv64)
VisitRiscv64ShiftAdd(HRiscv64ShiftAdd * instruction)649 void VisitRiscv64ShiftAdd(HRiscv64ShiftAdd* instruction) override {
650 StartAttributeStream("distance") << instruction->GetDistance();
651 }
652 #endif
653
IsPass(const char * name)654 bool IsPass(const char* name) {
655 return strcmp(pass_name_, name) == 0;
656 }
657
IsDebugDump()658 bool IsDebugDump() {
659 return IsPass(kDebugDumpGraphName) || IsPass(kDebugDumpName);
660 }
661
PrintInstruction(HInstruction * instruction)662 void PrintInstruction(HInstruction* instruction) {
663 output_ << instruction->DebugName();
664 HConstInputsRef inputs = instruction->GetInputs();
665 if (!inputs.empty()) {
666 StringList input_list;
667 for (const HInstruction* input : inputs) {
668 input_list.NewEntryStream() << DataType::TypeId(input->GetType()) << input->GetId();
669 }
670 StartAttributeStream() << input_list;
671 }
672 if (instruction->GetDexPc() != kNoDexPc) {
673 StartAttributeStream("dex_pc") << instruction->GetDexPc();
674 } else {
675 StartAttributeStream("dex_pc") << "n/a";
676 }
677 HBasicBlock* block = instruction->GetBlock();
678 StartAttributeStream("block") << namer_.GetName(block);
679
680 instruction->Accept(this);
681 if (instruction->HasEnvironment()) {
682 StringList envs;
683 for (HEnvironment* environment = instruction->GetEnvironment();
684 environment != nullptr;
685 environment = environment->GetParent()) {
686 StringList vregs;
687 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
688 HInstruction* insn = environment->GetInstructionAt(i);
689 if (insn != nullptr) {
690 vregs.NewEntryStream() << DataType::TypeId(insn->GetType()) << insn->GetId();
691 } else {
692 vregs.NewEntryStream() << "_";
693 }
694 }
695 envs.NewEntryStream() << vregs;
696 }
697 StartAttributeStream("env") << envs;
698 }
699 if (IsPass(SsaLivenessAnalysis::kLivenessPassName)
700 && is_after_pass_
701 && instruction->GetLifetimePosition() != kNoLifetime) {
702 StartAttributeStream("liveness") << instruction->GetLifetimePosition();
703 if (instruction->HasLiveInterval()) {
704 LiveInterval* interval = instruction->GetLiveInterval();
705 StartAttributeStream("ranges")
706 << StringList(interval->GetFirstRange(), StringList::kSetBrackets);
707 StartAttributeStream("uses") << StringList(interval->GetUses());
708 StartAttributeStream("env_uses") << StringList(interval->GetEnvironmentUses());
709 StartAttributeStream("is_fixed") << interval->IsFixed();
710 StartAttributeStream("is_split") << interval->IsSplit();
711 StartAttributeStream("is_low") << interval->IsLowInterval();
712 StartAttributeStream("is_high") << interval->IsHighInterval();
713 }
714 }
715
716 if (IsPass(RegisterAllocator::kRegisterAllocatorPassName) && is_after_pass_) {
717 StartAttributeStream("liveness") << instruction->GetLifetimePosition();
718 LocationSummary* locations = instruction->GetLocations();
719 if (locations != nullptr) {
720 StringList input_list;
721 for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
722 DumpLocation(input_list.NewEntryStream(), locations->InAt(i));
723 }
724 std::ostream& attr = StartAttributeStream("locations");
725 attr << input_list << "->";
726 DumpLocation(attr, locations->Out());
727 }
728 }
729
730 HLoopInformation* loop_info = (block != nullptr) ? block->GetLoopInformation() : nullptr;
731 if (loop_info == nullptr) {
732 StartAttributeStream("loop") << "none";
733 } else {
734 StartAttributeStream("loop") << namer_.GetName(loop_info->GetHeader());
735 HLoopInformation* outer = loop_info->GetPreHeader()->GetLoopInformation();
736 if (outer != nullptr) {
737 StartAttributeStream("outer_loop") << namer_.GetName(outer->GetHeader());
738 } else {
739 StartAttributeStream("outer_loop") << "none";
740 }
741 StartAttributeStream("irreducible")
742 << std::boolalpha << loop_info->IsIrreducible() << std::noboolalpha;
743 }
744
745 // For the builder and the inliner, we want to add extra information on HInstructions
746 // that have reference types, and also HInstanceOf/HCheckcast.
747 if ((IsPass(HGraphBuilder::kBuilderPassName)
748 || IsPass(HInliner::kInlinerPassName)
749 || IsDebugDump())
750 && (instruction->GetType() == DataType::Type::kReference ||
751 instruction->IsInstanceOf() ||
752 instruction->IsCheckCast())) {
753 ReferenceTypeInfo info = (instruction->GetType() == DataType::Type::kReference)
754 ? instruction->IsLoadClass()
755 ? instruction->AsLoadClass()->GetLoadedClassRTI()
756 : instruction->GetReferenceTypeInfo()
757 : instruction->IsInstanceOf()
758 ? instruction->AsInstanceOf()->GetTargetClassRTI()
759 : instruction->AsCheckCast()->GetTargetClassRTI();
760 ScopedObjectAccess soa(Thread::Current());
761 if (info.IsValid()) {
762 StartAttributeStream("klass")
763 << mirror::Class::PrettyDescriptor(info.GetTypeHandle().Get());
764 if (instruction->GetType() == DataType::Type::kReference) {
765 StartAttributeStream("can_be_null")
766 << std::boolalpha << instruction->CanBeNull() << std::noboolalpha;
767 }
768 StartAttributeStream("exact") << std::boolalpha << info.IsExact() << std::noboolalpha;
769 } else if (instruction->IsLoadClass() ||
770 instruction->IsInstanceOf() ||
771 instruction->IsCheckCast()) {
772 StartAttributeStream("klass") << "unresolved";
773 } else {
774 StartAttributeStream("klass") << "invalid";
775 }
776 }
777 if (disasm_info_ != nullptr) {
778 DCHECK(disassembler_ != nullptr);
779 // If the information is available, disassemble the code generated for
780 // this instruction.
781 auto it = disasm_info_->GetInstructionIntervals().find(instruction);
782 if (it != disasm_info_->GetInstructionIntervals().end()
783 && it->second.start != it->second.end) {
784 output_ << "\n";
785 disassembler_->Disassemble(output_, it->second.start, it->second.end);
786 }
787 }
788 }
789
PrintInstructions(const HInstructionList & list)790 void PrintInstructions(const HInstructionList& list) {
791 for (HInstructionIterator it(list); !it.Done(); it.Advance()) {
792 HInstruction* instruction = it.Current();
793 int bci = 0;
794 size_t num_uses = instruction->GetUses().SizeSlow();
795 AddIndent();
796 output_ << bci << " " << num_uses << " "
797 << DataType::TypeId(instruction->GetType()) << instruction->GetId() << " ";
798 PrintInstruction(instruction);
799 output_ << " " << kEndInstructionMarker << "\n";
800 }
801 }
802
DumpStartOfDisassemblyBlock(const char * block_name,int predecessor_index,int successor_index)803 void DumpStartOfDisassemblyBlock(const char* block_name,
804 int predecessor_index,
805 int successor_index) {
806 StartTag("block");
807 PrintProperty("name", block_name);
808 PrintInt("from_bci", -1);
809 PrintInt("to_bci", -1);
810 if (predecessor_index != -1) {
811 PrintProperty("predecessors", "B", predecessor_index);
812 } else {
813 PrintEmptyProperty("predecessors");
814 }
815 if (successor_index != -1) {
816 PrintProperty("successors", "B", successor_index);
817 } else {
818 PrintEmptyProperty("successors");
819 }
820 PrintEmptyProperty("xhandlers");
821 PrintEmptyProperty("flags");
822 StartTag("states");
823 StartTag("locals");
824 PrintInt("size", 0);
825 PrintProperty("method", "None");
826 EndTag("locals");
827 EndTag("states");
828 StartTag("HIR");
829 }
830
DumpEndOfDisassemblyBlock()831 void DumpEndOfDisassemblyBlock() {
832 EndTag("HIR");
833 EndTag("block");
834 }
835
DumpDisassemblyBlockForFrameEntry()836 void DumpDisassemblyBlockForFrameEntry() {
837 DumpStartOfDisassemblyBlock(kDisassemblyBlockFrameEntry,
838 -1,
839 GetGraph()->GetEntryBlock()->GetBlockId());
840 output_ << " 0 0 disasm " << kDisassemblyBlockFrameEntry << " ";
841 GeneratedCodeInterval frame_entry = disasm_info_->GetFrameEntryInterval();
842 if (frame_entry.start != frame_entry.end) {
843 output_ << "\n";
844 disassembler_->Disassemble(output_, frame_entry.start, frame_entry.end);
845 }
846 output_ << kEndInstructionMarker << "\n";
847 DumpEndOfDisassemblyBlock();
848 }
849
DumpDisassemblyBlockForSlowPaths()850 void DumpDisassemblyBlockForSlowPaths() {
851 if (disasm_info_->GetSlowPathIntervals().empty()) {
852 return;
853 }
854 // If the graph has an exit block we attach the block for the slow paths
855 // after it. Else we just add the block to the graph without linking it to
856 // any other.
857 DumpStartOfDisassemblyBlock(
858 kDisassemblyBlockSlowPaths,
859 GetGraph()->HasExitBlock() ? GetGraph()->GetExitBlock()->GetBlockId() : -1,
860 -1);
861 for (SlowPathCodeInfo info : disasm_info_->GetSlowPathIntervals()) {
862 output_ << " 0 0 disasm " << info.slow_path->GetDescription() << "\n";
863 disassembler_->Disassemble(output_, info.code_interval.start, info.code_interval.end);
864 output_ << kEndInstructionMarker << "\n";
865 }
866 DumpEndOfDisassemblyBlock();
867 }
868
Run()869 void Run() {
870 StartTag("cfg");
871 std::ostringstream oss;
872 oss << pass_name_;
873 if (!IsDebugDump()) {
874 oss << " (" << (GetGraph()->IsCompilingBaseline() ? "baseline " : "")
875 << (is_after_pass_ ? "after" : "before")
876 << (graph_in_bad_state_ ? ", bad_state" : "") << ")";
877 }
878 PrintProperty("name", oss.str().c_str());
879 if (disasm_info_ != nullptr) {
880 DumpDisassemblyBlockForFrameEntry();
881 }
882 VisitInsertionOrder();
883 if (disasm_info_ != nullptr) {
884 DumpDisassemblyBlockForSlowPaths();
885 }
886 EndTag("cfg");
887 Flush();
888 }
889
Run(HInstruction * instruction)890 void Run(HInstruction* instruction) {
891 output_ << DataType::TypeId(instruction->GetType()) << instruction->GetId() << " ";
892 PrintInstruction(instruction);
893 Flush();
894 }
895
VisitBasicBlock(HBasicBlock * block)896 void VisitBasicBlock(HBasicBlock* block) override {
897 StartTag("block");
898 PrintProperty("name", block);
899 if (block->GetLifetimeStart() != kNoLifetime) {
900 // Piggy back on these fields to show the lifetime of the block.
901 PrintInt("from_bci", block->GetLifetimeStart());
902 PrintInt("to_bci", block->GetLifetimeEnd());
903 } else if (!IsDebugDump()) {
904 // Don't print useless information to logcat.
905 PrintInt("from_bci", -1);
906 PrintInt("to_bci", -1);
907 }
908 PrintPredecessors(block);
909 PrintSuccessors(block);
910 PrintExceptionHandlers(block);
911
912 if (block->IsCatchBlock()) {
913 PrintProperty("flags", "catch_block");
914 } else if (block->IsTryBlock()) {
915 std::stringstream flags_properties;
916 flags_properties << "try_start "
917 << namer_.GetName(block->GetTryCatchInformation()->GetTryEntry().GetBlock());
918 PrintProperty("flags", flags_properties.str().c_str());
919 } else if (!IsDebugDump()) {
920 // Don't print useless information to logcat
921 PrintEmptyProperty("flags");
922 }
923
924 if (block->GetDominator() != nullptr) {
925 PrintProperty("dominator", block->GetDominator());
926 }
927
928 if (!IsDebugDump() || !block->GetPhis().IsEmpty()) {
929 StartTag("states");
930 StartTag("locals");
931 PrintInt("size", 0);
932 PrintProperty("method", "None");
933 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
934 AddIndent();
935 HInstruction* instruction = it.Current();
936 output_ << instruction->GetId() << " " << DataType::TypeId(instruction->GetType())
937 << instruction->GetId() << "[ ";
938 for (const HInstruction* input : instruction->GetInputs()) {
939 output_ << input->GetId() << " ";
940 }
941 output_ << "]\n";
942 }
943 EndTag("locals");
944 EndTag("states");
945 }
946
947 StartTag("HIR");
948 PrintInstructions(block->GetPhis());
949 PrintInstructions(block->GetInstructions());
950 EndTag("HIR");
951 EndTag("block");
952 }
953
954 static constexpr const char* const kEndInstructionMarker = "<|@";
955 static constexpr const char* const kDisassemblyBlockFrameEntry = "FrameEntry";
956 static constexpr const char* const kDisassemblyBlockSlowPaths = "SlowPaths";
957
958 private:
959 std::ostream& output_;
960 const char* pass_name_;
961 const bool is_after_pass_;
962 const bool graph_in_bad_state_;
963 const CodeGenerator* codegen_;
964 const DisassemblyInformation* disasm_info_;
965 const BlockNamer& namer_;
966 std::unique_ptr<HGraphVisualizerDisassembler> disassembler_;
967 size_t indent_;
968
969 DISALLOW_COPY_AND_ASSIGN(HGraphVisualizerPrinter);
970 };
971
PrintName(std::ostream & os,HBasicBlock * blk) const972 std::ostream& HGraphVisualizer::OptionalDefaultNamer::PrintName(std::ostream& os,
973 HBasicBlock* blk) const {
974 if (namer_) {
975 return namer_->get().PrintName(os, blk);
976 } else {
977 return BlockNamer::PrintName(os, blk);
978 }
979 }
980
HGraphVisualizer(std::ostream * output,HGraph * graph,const CodeGenerator * codegen,std::optional<std::reference_wrapper<const BlockNamer>> namer)981 HGraphVisualizer::HGraphVisualizer(std::ostream* output,
982 HGraph* graph,
983 const CodeGenerator* codegen,
984 std::optional<std::reference_wrapper<const BlockNamer>> namer)
985 : output_(output), graph_(graph), codegen_(codegen), namer_(namer) {}
986
PrintHeader(const char * method_name) const987 void HGraphVisualizer::PrintHeader(const char* method_name) const {
988 DCHECK(output_ != nullptr);
989 HGraphVisualizerPrinter printer(graph_, *output_, "", true, false, codegen_, namer_);
990 printer.StartTag("compilation");
991 printer.PrintProperty("name", method_name);
992 printer.PrintProperty("method", method_name);
993 printer.PrintTime("date");
994 printer.EndTag("compilation");
995 printer.Flush();
996 }
997
InsertMetaDataAsCompilationBlock(const std::string & meta_data)998 std::string HGraphVisualizer::InsertMetaDataAsCompilationBlock(const std::string& meta_data) {
999 std::string time_str = std::to_string(time(nullptr));
1000 std::string quoted_meta_data = "\"" + meta_data + "\"";
1001 return StringPrintf("begin_compilation\n"
1002 " name %s\n"
1003 " method %s\n"
1004 " date %s\n"
1005 "end_compilation\n",
1006 quoted_meta_data.c_str(),
1007 quoted_meta_data.c_str(),
1008 time_str.c_str());
1009 }
1010
DumpGraphDebug() const1011 void HGraphVisualizer::DumpGraphDebug() const {
1012 DumpGraph(/* pass_name= */ kDebugDumpGraphName,
1013 /* is_after_pass= */ false,
1014 /* graph_in_bad_state= */ true);
1015 }
1016
DumpGraph(const char * pass_name,bool is_after_pass,bool graph_in_bad_state) const1017 void HGraphVisualizer::DumpGraph(const char* pass_name,
1018 bool is_after_pass,
1019 bool graph_in_bad_state) const {
1020 DCHECK(output_ != nullptr);
1021 if (!graph_->GetBlocks().empty()) {
1022 HGraphVisualizerPrinter printer(graph_,
1023 *output_,
1024 pass_name,
1025 is_after_pass,
1026 graph_in_bad_state,
1027 codegen_,
1028 namer_);
1029 printer.Run();
1030 }
1031 }
1032
DumpGraphWithDisassembly() const1033 void HGraphVisualizer::DumpGraphWithDisassembly() const {
1034 DCHECK(output_ != nullptr);
1035 if (!graph_->GetBlocks().empty()) {
1036 HGraphVisualizerPrinter printer(graph_,
1037 *output_,
1038 "disassembly",
1039 /* is_after_pass= */ true,
1040 /* graph_in_bad_state= */ false,
1041 codegen_,
1042 namer_,
1043 codegen_->GetDisassemblyInformation());
1044 printer.Run();
1045 }
1046 }
1047
DumpInstruction(std::ostream * output,HGraph * graph,HInstruction * instruction)1048 void HGraphVisualizer::DumpInstruction(std::ostream* output,
1049 HGraph* graph,
1050 HInstruction* instruction) {
1051 BlockNamer namer;
1052 HGraphVisualizerPrinter printer(graph,
1053 *output,
1054 /* pass_name= */ kDebugDumpName,
1055 /* is_after_pass= */ false,
1056 /* graph_in_bad_state= */ false,
1057 /* codegen= */ nullptr,
1058 /* namer= */ namer);
1059 printer.Run(instruction);
1060 }
1061
1062 } // namespace art
1063