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