• 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_checker.h"
18 
19 #include <algorithm>
20 #include <sstream>
21 #include <string>
22 
23 #include "android-base/stringprintf.h"
24 
25 #include "base/bit_vector-inl.h"
26 #include "base/scoped_arena_allocator.h"
27 #include "base/scoped_arena_containers.h"
28 #include "code_generator.h"
29 #include "handle.h"
30 #include "mirror/class.h"
31 #include "obj_ptr-inl.h"
32 #include "scoped_thread_state_change-inl.h"
33 #include "subtype_check.h"
34 
35 namespace art HIDDEN {
36 
37 using android::base::StringPrintf;
38 
IsAllowedToJumpToExitBlock(HInstruction * instruction)39 static bool IsAllowedToJumpToExitBlock(HInstruction* instruction) {
40   // Anything that returns is allowed to jump into the exit block.
41   if (instruction->IsReturn() || instruction->IsReturnVoid()) {
42     return true;
43   }
44   // Anything that always throws is allowed to jump into the exit block.
45   if (instruction->IsGoto() && instruction->GetPrevious() != nullptr) {
46     instruction = instruction->GetPrevious();
47   }
48   return instruction->AlwaysThrows();
49 }
50 
IsExitTryBoundaryIntoExitBlock(HBasicBlock * block)51 static bool IsExitTryBoundaryIntoExitBlock(HBasicBlock* block) {
52   if (!block->IsSingleTryBoundary()) {
53     return false;
54   }
55 
56   HTryBoundary* boundary = block->GetLastInstruction()->AsTryBoundary();
57   return block->GetPredecessors().size() == 1u &&
58          boundary->GetNormalFlowSuccessor()->IsExitBlock() &&
59          !boundary->IsEntry();
60 }
61 
62 
Run(bool pass_change,size_t last_size)63 size_t GraphChecker::Run(bool pass_change, size_t last_size) {
64   size_t current_size = GetGraph()->GetReversePostOrder().size();
65   if (!pass_change) {
66     // Nothing changed for certain. Do a quick check of the validity on that assertion
67     // for anything other than the first call (when last size was still 0).
68     if (last_size != 0) {
69       if (current_size != last_size) {
70         AddError(StringPrintf("Incorrect no-change assertion, "
71                               "last graph size %zu vs current graph size %zu",
72                               last_size, current_size));
73       }
74     }
75     // TODO: if we would trust the "false" value of the flag completely, we
76     // could skip checking the graph at this point.
77   }
78 
79   // VisitReversePostOrder is used instead of VisitInsertionOrder,
80   // as the latter might visit dead blocks removed by the dominator
81   // computation.
82   VisitReversePostOrder();
83   CheckGraphFlags();
84   return current_size;
85 }
86 
VisitReversePostOrder()87 void GraphChecker::VisitReversePostOrder() {
88   for (HBasicBlock* block : GetGraph()->GetReversePostOrder()) {
89     if (block->IsInLoop()) {
90       flag_info_.seen_loop = true;
91       if (block->GetLoopInformation()->IsIrreducible()) {
92         flag_info_.seen_irreducible_loop = true;
93       }
94     }
95 
96     VisitBasicBlock(block);
97   }
98 }
99 
StrBool(bool val)100 static const char* StrBool(bool val) {
101   return val ? "true" : "false";
102 }
103 
CheckGraphFlags()104 void GraphChecker::CheckGraphFlags() {
105   if (GetGraph()->HasMonitorOperations() != flag_info_.seen_monitor_operation) {
106     AddError(
107         StringPrintf("Flag mismatch: HasMonitorOperations() (%s) should be equal to "
108                      "flag_info_.seen_monitor_operation (%s)",
109                      StrBool(GetGraph()->HasMonitorOperations()),
110                      StrBool(flag_info_.seen_monitor_operation)));
111   }
112 
113   if (GetGraph()->HasTryCatch() != flag_info_.seen_try_boundary) {
114     AddError(
115         StringPrintf("Flag mismatch: HasTryCatch() (%s) should be equal to "
116                      "flag_info_.seen_try_boundary (%s)",
117                      StrBool(GetGraph()->HasTryCatch()),
118                      StrBool(flag_info_.seen_try_boundary)));
119   }
120 
121   if (GetGraph()->HasLoops() != flag_info_.seen_loop) {
122     AddError(
123         StringPrintf("Flag mismatch: HasLoops() (%s) should be equal to "
124                      "flag_info_.seen_loop (%s)",
125                      StrBool(GetGraph()->HasLoops()),
126                      StrBool(flag_info_.seen_loop)));
127   }
128 
129   if (GetGraph()->HasIrreducibleLoops() && !GetGraph()->HasLoops()) {
130     AddError(StringPrintf("Flag mismatch: HasIrreducibleLoops() (%s) implies HasLoops() (%s)",
131                           StrBool(GetGraph()->HasIrreducibleLoops()),
132                           StrBool(GetGraph()->HasLoops())));
133   }
134 
135   if (GetGraph()->HasIrreducibleLoops() != flag_info_.seen_irreducible_loop) {
136     AddError(
137         StringPrintf("Flag mismatch: HasIrreducibleLoops() (%s) should be equal to "
138                      "flag_info_.seen_irreducible_loop (%s)",
139                      StrBool(GetGraph()->HasIrreducibleLoops()),
140                      StrBool(flag_info_.seen_irreducible_loop)));
141   }
142 
143   if (GetGraph()->HasSIMD() != flag_info_.seen_SIMD) {
144     AddError(
145         StringPrintf("Flag mismatch: HasSIMD() (%s) should be equal to "
146                      "flag_info_.seen_SIMD (%s)",
147                      StrBool(GetGraph()->HasSIMD()),
148                      StrBool(flag_info_.seen_SIMD)));
149   }
150 
151   if (GetGraph()->HasBoundsChecks() != flag_info_.seen_bounds_checks) {
152     AddError(
153         StringPrintf("Flag mismatch: HasBoundsChecks() (%s) should be equal to "
154                      "flag_info_.seen_bounds_checks (%s)",
155                      StrBool(GetGraph()->HasBoundsChecks()),
156                      StrBool(flag_info_.seen_bounds_checks)));
157   }
158 
159   if (GetGraph()->HasAlwaysThrowingInvokes() != flag_info_.seen_always_throwing_invokes) {
160     AddError(
161         StringPrintf("Flag mismatch: HasAlwaysThrowingInvokes() (%s) should be equal to "
162                      "flag_info_.seen_always_throwing_invokes (%s)",
163                      StrBool(GetGraph()->HasAlwaysThrowingInvokes()),
164                      StrBool(flag_info_.seen_always_throwing_invokes)));
165   }
166 }
167 
VisitBasicBlock(HBasicBlock * block)168 void GraphChecker::VisitBasicBlock(HBasicBlock* block) {
169   current_block_ = block;
170 
171   // Use local allocator for allocating memory.
172   ScopedArenaAllocator allocator(GetGraph()->GetArenaStack());
173 
174   // Check consistency with respect to predecessors of `block`.
175   // Note: Counting duplicates with a sorted vector uses up to 6x less memory
176   // than ArenaSafeMap<HBasicBlock*, size_t> and also allows storage reuse.
177   ScopedArenaVector<HBasicBlock*> sorted_predecessors(allocator.Adapter(kArenaAllocGraphChecker));
178   sorted_predecessors.assign(block->GetPredecessors().begin(), block->GetPredecessors().end());
179   std::sort(sorted_predecessors.begin(), sorted_predecessors.end());
180   for (auto it = sorted_predecessors.begin(), end = sorted_predecessors.end(); it != end; ) {
181     HBasicBlock* p = *it++;
182     size_t p_count_in_block_predecessors = 1u;
183     for (; it != end && *it == p; ++it) {
184       ++p_count_in_block_predecessors;
185     }
186     size_t block_count_in_p_successors =
187         std::count(p->GetSuccessors().begin(), p->GetSuccessors().end(), block);
188     if (p_count_in_block_predecessors != block_count_in_p_successors) {
189       AddError(StringPrintf(
190           "Block %d lists %zu occurrences of block %d in its predecessors, whereas "
191           "block %d lists %zu occurrences of block %d in its successors.",
192           block->GetBlockId(), p_count_in_block_predecessors, p->GetBlockId(),
193           p->GetBlockId(), block_count_in_p_successors, block->GetBlockId()));
194     }
195   }
196 
197   // Check consistency with respect to successors of `block`.
198   // Note: Counting duplicates with a sorted vector uses up to 6x less memory
199   // than ArenaSafeMap<HBasicBlock*, size_t> and also allows storage reuse.
200   ScopedArenaVector<HBasicBlock*> sorted_successors(allocator.Adapter(kArenaAllocGraphChecker));
201   sorted_successors.assign(block->GetSuccessors().begin(), block->GetSuccessors().end());
202   std::sort(sorted_successors.begin(), sorted_successors.end());
203   for (auto it = sorted_successors.begin(), end = sorted_successors.end(); it != end; ) {
204     HBasicBlock* s = *it++;
205     size_t s_count_in_block_successors = 1u;
206     for (; it != end && *it == s; ++it) {
207       ++s_count_in_block_successors;
208     }
209     size_t block_count_in_s_predecessors =
210         std::count(s->GetPredecessors().begin(), s->GetPredecessors().end(), block);
211     if (s_count_in_block_successors != block_count_in_s_predecessors) {
212       AddError(StringPrintf(
213           "Block %d lists %zu occurrences of block %d in its successors, whereas "
214           "block %d lists %zu occurrences of block %d in its predecessors.",
215           block->GetBlockId(), s_count_in_block_successors, s->GetBlockId(),
216           s->GetBlockId(), block_count_in_s_predecessors, block->GetBlockId()));
217     }
218   }
219 
220   // Ensure `block` ends with a branch instruction.
221   // This invariant is not enforced on non-SSA graphs. Graph built from DEX with
222   // dead code that falls out of the method will not end with a control-flow
223   // instruction. Such code is removed during the SSA-building DCE phase.
224   if (GetGraph()->IsInSsaForm() && !block->EndsWithControlFlowInstruction()) {
225     AddError(StringPrintf("Block %d does not end with a branch instruction.",
226                           block->GetBlockId()));
227   }
228 
229   // Ensure that only Return(Void) and Throw jump to Exit. An exiting TryBoundary
230   // may be between the instructions if the Throw/Return(Void) is in a try block.
231   if (block->IsExitBlock()) {
232     for (HBasicBlock* predecessor : block->GetPredecessors()) {
233       HInstruction* last_instruction = IsExitTryBoundaryIntoExitBlock(predecessor) ?
234         predecessor->GetSinglePredecessor()->GetLastInstruction() :
235         predecessor->GetLastInstruction();
236       if (!IsAllowedToJumpToExitBlock(last_instruction)) {
237         AddError(StringPrintf("Unexpected instruction %s:%d jumps into the exit block.",
238                               last_instruction->DebugName(),
239                               last_instruction->GetId()));
240       }
241     }
242   }
243 
244   // Make sure the first instruction of a catch block is always a Nop that emits an environment.
245   if (block->IsCatchBlock()) {
246     if (!block->GetFirstInstruction()->IsNop()) {
247       AddError(StringPrintf("Block %d doesn't have a Nop as its first instruction.",
248                             current_block_->GetBlockId()));
249     } else {
250       HNop* nop = block->GetFirstInstruction()->AsNop();
251       if (!nop->NeedsEnvironment()) {
252         AddError(
253             StringPrintf("%s:%d is a Nop and the first instruction of block %d, but it doesn't "
254                          "need an environment.",
255                          nop->DebugName(),
256                          nop->GetId(),
257                          current_block_->GetBlockId()));
258       }
259     }
260   }
261 
262   // Visit this block's list of phis.
263   for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
264     HInstruction* current = it.Current();
265     // Ensure this block's list of phis contains only phis.
266     if (!current->IsPhi()) {
267       AddError(StringPrintf("Block %d has a non-phi in its phi list.",
268                             current_block_->GetBlockId()));
269     }
270     if (current->GetNext() == nullptr && current != block->GetLastPhi()) {
271       AddError(StringPrintf("The recorded last phi of block %d does not match "
272                             "the actual last phi %d.",
273                             current_block_->GetBlockId(),
274                             current->GetId()));
275     }
276     current->Accept(this);
277   }
278 
279   // Visit this block's list of instructions.
280   for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
281     HInstruction* current = it.Current();
282     // Ensure this block's list of instructions does not contains phis.
283     if (current->IsPhi()) {
284       AddError(StringPrintf("Block %d has a phi in its non-phi list.",
285                             current_block_->GetBlockId()));
286     }
287     if (current->GetNext() == nullptr && current != block->GetLastInstruction()) {
288       AddError(StringPrintf("The recorded last instruction of block %d does not match "
289                             "the actual last instruction %d.",
290                             current_block_->GetBlockId(),
291                             current->GetId()));
292     }
293     current->Accept(this);
294   }
295 
296   // Ensure that catch blocks are not normal successors, and normal blocks are
297   // never exceptional successors.
298   for (HBasicBlock* successor : block->GetNormalSuccessors()) {
299     if (successor->IsCatchBlock()) {
300       AddError(StringPrintf("Catch block %d is a normal successor of block %d.",
301                             successor->GetBlockId(),
302                             block->GetBlockId()));
303     }
304   }
305   for (HBasicBlock* successor : block->GetExceptionalSuccessors()) {
306     if (!successor->IsCatchBlock()) {
307       AddError(StringPrintf("Normal block %d is an exceptional successor of block %d.",
308                             successor->GetBlockId(),
309                             block->GetBlockId()));
310     }
311   }
312 
313   // Ensure dominated blocks have `block` as the dominator.
314   for (HBasicBlock* dominated : block->GetDominatedBlocks()) {
315     if (dominated->GetDominator() != block) {
316       AddError(StringPrintf("Block %d should be the dominator of %d.",
317                             block->GetBlockId(),
318                             dominated->GetBlockId()));
319     }
320   }
321 
322   // Ensure all blocks have at least one successor, except the Exit block.
323   if (block->GetSuccessors().empty() && !block->IsExitBlock()) {
324     AddError(StringPrintf("Block %d has no successor and it is not the Exit block.",
325                           block->GetBlockId()));
326   }
327 
328   // Ensure there is no critical edge (i.e., an edge connecting a
329   // block with multiple successors to a block with multiple
330   // predecessors). Exceptional edges are synthesized and hence
331   // not accounted for.
332   if (block->GetSuccessors().size() > 1) {
333     if (IsExitTryBoundaryIntoExitBlock(block)) {
334       // Allowed critical edge (Throw/Return/ReturnVoid)->TryBoundary->Exit.
335     } else {
336       for (HBasicBlock* successor : block->GetNormalSuccessors()) {
337         if (successor->GetPredecessors().size() > 1) {
338           AddError(StringPrintf("Critical edge between blocks %d and %d.",
339                                 block->GetBlockId(),
340                                 successor->GetBlockId()));
341         }
342       }
343     }
344   }
345 
346   // Ensure try membership information is consistent.
347   if (block->IsCatchBlock()) {
348     if (block->IsTryBlock()) {
349       const HTryBoundary& try_entry = block->GetTryCatchInformation()->GetTryEntry();
350       AddError(StringPrintf("Catch blocks should not be try blocks but catch block %d "
351                             "has try entry %s:%d.",
352                             block->GetBlockId(),
353                             try_entry.DebugName(),
354                             try_entry.GetId()));
355     }
356 
357     if (block->IsLoopHeader()) {
358       AddError(StringPrintf("Catch blocks should not be loop headers but catch block %d is.",
359                             block->GetBlockId()));
360     }
361   } else {
362     for (HBasicBlock* predecessor : block->GetPredecessors()) {
363       const HTryBoundary* incoming_try_entry = predecessor->ComputeTryEntryOfSuccessors();
364       if (block->IsTryBlock()) {
365         const HTryBoundary& stored_try_entry = block->GetTryCatchInformation()->GetTryEntry();
366         if (incoming_try_entry == nullptr) {
367           AddError(StringPrintf("Block %d has try entry %s:%d but no try entry follows "
368                                 "from predecessor %d.",
369                                 block->GetBlockId(),
370                                 stored_try_entry.DebugName(),
371                                 stored_try_entry.GetId(),
372                                 predecessor->GetBlockId()));
373         } else if (!incoming_try_entry->HasSameExceptionHandlersAs(stored_try_entry)) {
374           AddError(StringPrintf("Block %d has try entry %s:%d which is not consistent "
375                                 "with %s:%d that follows from predecessor %d.",
376                                 block->GetBlockId(),
377                                 stored_try_entry.DebugName(),
378                                 stored_try_entry.GetId(),
379                                 incoming_try_entry->DebugName(),
380                                 incoming_try_entry->GetId(),
381                                 predecessor->GetBlockId()));
382         }
383       } else if (incoming_try_entry != nullptr) {
384         AddError(StringPrintf("Block %d is not a try block but try entry %s:%d follows "
385                               "from predecessor %d.",
386                               block->GetBlockId(),
387                               incoming_try_entry->DebugName(),
388                               incoming_try_entry->GetId(),
389                               predecessor->GetBlockId()));
390       }
391     }
392   }
393 
394   if (block->IsLoopHeader()) {
395     HandleLoop(block);
396   }
397 }
398 
VisitBoundsCheck(HBoundsCheck * check)399 void GraphChecker::VisitBoundsCheck(HBoundsCheck* check) {
400   VisitInstruction(check);
401 
402   if (!GetGraph()->HasBoundsChecks()) {
403     AddError(
404         StringPrintf("The graph doesn't have the HasBoundsChecks flag set but we saw "
405                      "%s:%d in block %d.",
406                      check->DebugName(),
407                      check->GetId(),
408                      check->GetBlock()->GetBlockId()));
409   }
410 
411   flag_info_.seen_bounds_checks = true;
412 }
413 
VisitDeoptimize(HDeoptimize * deopt)414 void GraphChecker::VisitDeoptimize(HDeoptimize* deopt) {
415   VisitInstruction(deopt);
416   if (GetGraph()->IsCompilingOsr()) {
417     AddError(StringPrintf("A graph compiled OSR cannot have a HDeoptimize instruction"));
418   }
419 }
420 
VisitTryBoundary(HTryBoundary * try_boundary)421 void GraphChecker::VisitTryBoundary(HTryBoundary* try_boundary) {
422   VisitInstruction(try_boundary);
423 
424   ArrayRef<HBasicBlock* const> handlers = try_boundary->GetExceptionHandlers();
425 
426   // Ensure that all exception handlers are catch blocks.
427   // Note that a normal-flow successor may be a catch block before CFG
428   // simplification. We only test normal-flow successors in GraphChecker.
429   for (HBasicBlock* handler : handlers) {
430     if (!handler->IsCatchBlock()) {
431       AddError(StringPrintf("Block %d with %s:%d has exceptional successor %d which "
432                             "is not a catch block.",
433                             current_block_->GetBlockId(),
434                             try_boundary->DebugName(),
435                             try_boundary->GetId(),
436                             handler->GetBlockId()));
437     }
438   }
439 
440   // Ensure that handlers are not listed multiple times.
441   for (size_t i = 0, e = handlers.size(); i < e; ++i) {
442     if (ContainsElement(handlers, handlers[i], i + 1)) {
443         AddError(StringPrintf("Exception handler block %d of %s:%d is listed multiple times.",
444                             handlers[i]->GetBlockId(),
445                             try_boundary->DebugName(),
446                             try_boundary->GetId()));
447     }
448   }
449 
450   if (!GetGraph()->HasTryCatch()) {
451     AddError(
452         StringPrintf("The graph doesn't have the HasTryCatch flag set but we saw "
453                      "%s:%d in block %d.",
454                      try_boundary->DebugName(),
455                      try_boundary->GetId(),
456                      try_boundary->GetBlock()->GetBlockId()));
457   }
458 
459   flag_info_.seen_try_boundary = true;
460 }
461 
VisitLoadClass(HLoadClass * load)462 void GraphChecker::VisitLoadClass(HLoadClass* load) {
463   VisitInstruction(load);
464 
465   if (load->GetLoadedClassRTI().IsValid() && !load->GetLoadedClassRTI().IsExact()) {
466     std::stringstream ssRTI;
467     ssRTI << load->GetLoadedClassRTI();
468     AddError(StringPrintf("%s:%d in block %d with RTI %s has valid but inexact RTI.",
469                           load->DebugName(),
470                           load->GetId(),
471                           load->GetBlock()->GetBlockId(),
472                           ssRTI.str().c_str()));
473   }
474 }
475 
VisitLoadException(HLoadException * load)476 void GraphChecker::VisitLoadException(HLoadException* load) {
477   VisitInstruction(load);
478 
479   // Ensure that LoadException is the second instruction in a catch block. The first one should be a
480   // Nop (checked separately).
481   if (!load->GetBlock()->IsCatchBlock()) {
482     AddError(StringPrintf("%s:%d is in a non-catch block %d.",
483                           load->DebugName(),
484                           load->GetId(),
485                           load->GetBlock()->GetBlockId()));
486   } else if (load->GetBlock()->GetFirstInstruction()->GetNext() != load) {
487     AddError(StringPrintf("%s:%d is not the second instruction in catch block %d.",
488                           load->DebugName(),
489                           load->GetId(),
490                           load->GetBlock()->GetBlockId()));
491   }
492 }
493 
VisitMonitorOperation(HMonitorOperation * monitor_op)494 void GraphChecker::VisitMonitorOperation(HMonitorOperation* monitor_op) {
495   VisitInstruction(monitor_op);
496 
497   if (!GetGraph()->HasMonitorOperations()) {
498     AddError(
499         StringPrintf("The graph doesn't have the HasMonitorOperations flag set but we saw "
500                      "%s:%d in block %d.",
501                      monitor_op->DebugName(),
502                      monitor_op->GetId(),
503                      monitor_op->GetBlock()->GetBlockId()));
504   }
505 
506   flag_info_.seen_monitor_operation = true;
507 }
508 
VisitInstruction(HInstruction * instruction)509 void GraphChecker::VisitInstruction(HInstruction* instruction) {
510   if (seen_ids_.IsBitSet(instruction->GetId())) {
511     AddError(StringPrintf("Instruction id %d is duplicate in graph.",
512                           instruction->GetId()));
513   } else {
514     seen_ids_.SetBit(instruction->GetId());
515   }
516 
517   // Ensure `instruction` is associated with `current_block_`.
518   if (instruction->GetBlock() == nullptr) {
519     AddError(StringPrintf("%s %d in block %d not associated with any block.",
520                           instruction->IsPhi() ? "Phi" : "Instruction",
521                           instruction->GetId(),
522                           current_block_->GetBlockId()));
523   } else if (instruction->GetBlock() != current_block_) {
524     AddError(StringPrintf("%s %d in block %d associated with block %d.",
525                           instruction->IsPhi() ? "Phi" : "Instruction",
526                           instruction->GetId(),
527                           current_block_->GetBlockId(),
528                           instruction->GetBlock()->GetBlockId()));
529   }
530 
531   // Ensure the inputs of `instruction` are defined in a block of the graph.
532   for (HInstruction* input : instruction->GetInputs()) {
533     if (input->GetBlock() == nullptr) {
534       AddError(StringPrintf("Input %d of instruction %d is not in any "
535                             "basic block of the control-flow graph.",
536                             input->GetId(),
537                             instruction->GetId()));
538     } else {
539       const HInstructionList& list = input->IsPhi()
540           ? input->GetBlock()->GetPhis()
541           : input->GetBlock()->GetInstructions();
542       if (!list.Contains(input)) {
543         AddError(StringPrintf("Input %d of instruction %d is not defined "
544                               "in a basic block of the control-flow graph.",
545                               input->GetId(),
546                               instruction->GetId()));
547       }
548     }
549   }
550 
551   // Ensure the uses of `instruction` are defined in a block of the graph,
552   // and the entry in the use list is consistent.
553   for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
554     HInstruction* user = use.GetUser();
555     const HInstructionList& list = user->IsPhi()
556         ? user->GetBlock()->GetPhis()
557         : user->GetBlock()->GetInstructions();
558     if (!list.Contains(user)) {
559       AddError(StringPrintf("User %s:%d of instruction %d is not defined "
560                             "in a basic block of the control-flow graph.",
561                             user->DebugName(),
562                             user->GetId(),
563                             instruction->GetId()));
564     }
565     size_t use_index = use.GetIndex();
566     HConstInputsRef user_inputs = user->GetInputs();
567     if ((use_index >= user_inputs.size()) || (user_inputs[use_index] != instruction)) {
568       AddError(StringPrintf("User %s:%d of instruction %s:%d has a wrong "
569                             "UseListNode index.",
570                             user->DebugName(),
571                             user->GetId(),
572                             instruction->DebugName(),
573                             instruction->GetId()));
574     }
575   }
576 
577   // Ensure the environment uses entries are consistent.
578   for (const HUseListNode<HEnvironment*>& use : instruction->GetEnvUses()) {
579     HEnvironment* user = use.GetUser();
580     size_t use_index = use.GetIndex();
581     if ((use_index >= user->Size()) || (user->GetInstructionAt(use_index) != instruction)) {
582       AddError(StringPrintf("Environment user of %s:%d has a wrong "
583                             "UseListNode index.",
584                             instruction->DebugName(),
585                             instruction->GetId()));
586     }
587   }
588 
589   // Ensure 'instruction' has pointers to its inputs' use entries.
590   auto&& input_records = instruction->GetInputRecords();
591   for (size_t i = 0; i < input_records.size(); ++i) {
592     const HUserRecord<HInstruction*>& input_record = input_records[i];
593     HInstruction* input = input_record.GetInstruction();
594     if ((input_record.GetBeforeUseNode() == input->GetUses().end()) ||
595         (input_record.GetUseNode() == input->GetUses().end()) ||
596         !input->GetUses().ContainsNode(*input_record.GetUseNode()) ||
597         (input_record.GetUseNode()->GetIndex() != i)) {
598       AddError(StringPrintf("Instruction %s:%d has an invalid iterator before use entry "
599                             "at input %u (%s:%d).",
600                             instruction->DebugName(),
601                             instruction->GetId(),
602                             static_cast<unsigned>(i),
603                             input->DebugName(),
604                             input->GetId()));
605     }
606   }
607 
608   // Ensure an instruction dominates all its uses.
609   for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
610     HInstruction* user = use.GetUser();
611     if (!user->IsPhi() && !instruction->StrictlyDominates(user)) {
612       AddError(StringPrintf("Instruction %s:%d in block %d does not dominate "
613                             "use %s:%d in block %d.",
614                             instruction->DebugName(),
615                             instruction->GetId(),
616                             current_block_->GetBlockId(),
617                             user->DebugName(),
618                             user->GetId(),
619                             user->GetBlock()->GetBlockId()));
620     }
621   }
622 
623   if (instruction->NeedsEnvironment() && !instruction->HasEnvironment()) {
624     AddError(StringPrintf("Instruction %s:%d in block %d requires an environment "
625                           "but does not have one.",
626                           instruction->DebugName(),
627                           instruction->GetId(),
628                           current_block_->GetBlockId()));
629   }
630 
631   // Ensure an instruction having an environment is dominated by the
632   // instructions contained in the environment.
633   for (HEnvironment* environment = instruction->GetEnvironment();
634        environment != nullptr;
635        environment = environment->GetParent()) {
636     for (size_t i = 0, e = environment->Size(); i < e; ++i) {
637       HInstruction* env_instruction = environment->GetInstructionAt(i);
638       if (env_instruction != nullptr
639           && !env_instruction->StrictlyDominates(instruction)) {
640         AddError(StringPrintf("Instruction %d in environment of instruction %d "
641                               "from block %d does not dominate instruction %d.",
642                               env_instruction->GetId(),
643                               instruction->GetId(),
644                               current_block_->GetBlockId(),
645                               instruction->GetId()));
646       }
647     }
648   }
649 
650   if (instruction->CanThrow() && !instruction->HasEnvironment()) {
651     AddError(StringPrintf("Throwing instruction %s:%d in block %d does not have an environment.",
652                           instruction->DebugName(),
653                           instruction->GetId(),
654                           current_block_->GetBlockId()));
655   } else if (instruction->CanThrowIntoCatchBlock()) {
656     // Find all catch blocks and test that `instruction` has an environment value for each one.
657     const HTryBoundary& entry = instruction->GetBlock()->GetTryCatchInformation()->GetTryEntry();
658     for (HBasicBlock* catch_block : entry.GetExceptionHandlers()) {
659       const HEnvironment* environment = catch_block->GetFirstInstruction()->GetEnvironment();
660       for (HInstructionIterator phi_it(catch_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
661         HPhi* catch_phi = phi_it.Current()->AsPhi();
662         if (environment->GetInstructionAt(catch_phi->GetRegNumber()) == nullptr) {
663           AddError(StringPrintf("Instruction %s:%d throws into catch block %d "
664                                 "with catch phi %d for vreg %d but its "
665                                 "corresponding environment slot is empty.",
666                                 instruction->DebugName(),
667                                 instruction->GetId(),
668                                 catch_block->GetBlockId(),
669                                 catch_phi->GetId(),
670                                 catch_phi->GetRegNumber()));
671         }
672       }
673     }
674   }
675 }
676 
VisitInvoke(HInvoke * invoke)677 void GraphChecker::VisitInvoke(HInvoke* invoke) {
678   VisitInstruction(invoke);
679 
680   if (invoke->AlwaysThrows()) {
681     if (!GetGraph()->HasAlwaysThrowingInvokes()) {
682       AddError(
683           StringPrintf("The graph doesn't have the HasAlwaysThrowingInvokes flag set but we saw "
684                        "%s:%d in block %d and it always throws.",
685                        invoke->DebugName(),
686                        invoke->GetId(),
687                        invoke->GetBlock()->GetBlockId()));
688     }
689     flag_info_.seen_always_throwing_invokes = true;
690   }
691 }
692 
VisitInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)693 void GraphChecker::VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) {
694   // We call VisitInvoke and not VisitInstruction to de-duplicate the always throwing code check.
695   VisitInvoke(invoke);
696 
697   if (invoke->IsStaticWithExplicitClinitCheck()) {
698     const HInstruction* last_input = invoke->GetInputs().back();
699     if (last_input == nullptr) {
700       AddError(StringPrintf("Static invoke %s:%d marked as having an explicit clinit check "
701                             "has a null pointer as last input.",
702                             invoke->DebugName(),
703                             invoke->GetId()));
704     } else if (!last_input->IsClinitCheck() && !last_input->IsLoadClass()) {
705       AddError(StringPrintf("Static invoke %s:%d marked as having an explicit clinit check "
706                             "has a last instruction (%s:%d) which is neither a clinit check "
707                             "nor a load class instruction.",
708                             invoke->DebugName(),
709                             invoke->GetId(),
710                             last_input->DebugName(),
711                             last_input->GetId()));
712     }
713   }
714 }
715 
VisitReturn(HReturn * ret)716 void GraphChecker::VisitReturn(HReturn* ret) {
717   VisitInstruction(ret);
718   HBasicBlock* successor = ret->GetBlock()->GetSingleSuccessor();
719   if (!successor->IsExitBlock() && !IsExitTryBoundaryIntoExitBlock(successor)) {
720     AddError(StringPrintf("%s:%d does not jump to the exit block.",
721                           ret->DebugName(),
722                           ret->GetId()));
723   }
724 }
725 
VisitReturnVoid(HReturnVoid * ret)726 void GraphChecker::VisitReturnVoid(HReturnVoid* ret) {
727   VisitInstruction(ret);
728   HBasicBlock* successor = ret->GetBlock()->GetSingleSuccessor();
729   if (!successor->IsExitBlock() && !IsExitTryBoundaryIntoExitBlock(successor)) {
730     AddError(StringPrintf("%s:%d does not jump to the exit block.",
731                           ret->DebugName(),
732                           ret->GetId()));
733   }
734 }
735 
CheckTypeCheckBitstringInput(HTypeCheckInstruction * check,size_t input_pos,bool check_value,uint32_t expected_value,const char * name)736 void GraphChecker::CheckTypeCheckBitstringInput(HTypeCheckInstruction* check,
737                                                 size_t input_pos,
738                                                 bool check_value,
739                                                 uint32_t expected_value,
740                                                 const char* name) {
741   if (!check->InputAt(input_pos)->IsIntConstant()) {
742     AddError(StringPrintf("%s:%d (bitstring) expects a HIntConstant input %zu (%s), not %s:%d.",
743                           check->DebugName(),
744                           check->GetId(),
745                           input_pos,
746                           name,
747                           check->InputAt(2)->DebugName(),
748                           check->InputAt(2)->GetId()));
749   } else if (check_value) {
750     uint32_t actual_value =
751         static_cast<uint32_t>(check->InputAt(input_pos)->AsIntConstant()->GetValue());
752     if (actual_value != expected_value) {
753       AddError(StringPrintf("%s:%d (bitstring) has %s 0x%x, not 0x%x as expected.",
754                             check->DebugName(),
755                             check->GetId(),
756                             name,
757                             actual_value,
758                             expected_value));
759     }
760   }
761 }
762 
HandleTypeCheckInstruction(HTypeCheckInstruction * check)763 void GraphChecker::HandleTypeCheckInstruction(HTypeCheckInstruction* check) {
764   VisitInstruction(check);
765 
766   if (check->GetTargetClassRTI().IsValid() && !check->GetTargetClassRTI().IsExact()) {
767     std::stringstream ssRTI;
768     ssRTI << check->GetTargetClassRTI();
769     AddError(StringPrintf("%s:%d in block %d with RTI %s has valid but inexact RTI.",
770                           check->DebugName(),
771                           check->GetId(),
772                           check->GetBlock()->GetBlockId(),
773                           ssRTI.str().c_str()));
774   }
775 
776   HInstruction* input = check->InputAt(1);
777   if (check->GetTypeCheckKind() == TypeCheckKind::kBitstringCheck) {
778     if (!input->IsNullConstant()) {
779       AddError(StringPrintf("%s:%d (bitstring) expects a HNullConstant as second input, not %s:%d.",
780                             check->DebugName(),
781                             check->GetId(),
782                             input->DebugName(),
783                             input->GetId()));
784     }
785     bool check_values = false;
786     BitString::StorageType expected_path_to_root = 0u;
787     BitString::StorageType expected_mask = 0u;
788     {
789       ScopedObjectAccess soa(Thread::Current());
790       ObjPtr<mirror::Class> klass = check->GetClass().Get();
791       MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
792       SubtypeCheckInfo::State state = SubtypeCheck<ObjPtr<mirror::Class>>::GetState(klass);
793       if (state == SubtypeCheckInfo::kAssigned) {
794         expected_path_to_root =
795             SubtypeCheck<ObjPtr<mirror::Class>>::GetEncodedPathToRootForTarget(klass);
796         expected_mask = SubtypeCheck<ObjPtr<mirror::Class>>::GetEncodedPathToRootMask(klass);
797         check_values = true;
798       } else {
799         AddError(StringPrintf("%s:%d (bitstring) references a class with unassigned bitstring.",
800                               check->DebugName(),
801                               check->GetId()));
802       }
803     }
804     CheckTypeCheckBitstringInput(
805         check, /* input_pos= */ 2, check_values, expected_path_to_root, "path_to_root");
806     CheckTypeCheckBitstringInput(check, /* input_pos= */ 3, check_values, expected_mask, "mask");
807   } else {
808     if (!input->IsLoadClass()) {
809       AddError(StringPrintf("%s:%d (classic) expects a HLoadClass as second input, not %s:%d.",
810                             check->DebugName(),
811                             check->GetId(),
812                             input->DebugName(),
813                             input->GetId()));
814     }
815   }
816 }
817 
VisitCheckCast(HCheckCast * check)818 void GraphChecker::VisitCheckCast(HCheckCast* check) {
819   HandleTypeCheckInstruction(check);
820 }
821 
VisitInstanceOf(HInstanceOf * instruction)822 void GraphChecker::VisitInstanceOf(HInstanceOf* instruction) {
823   HandleTypeCheckInstruction(instruction);
824 }
825 
HandleLoop(HBasicBlock * loop_header)826 void GraphChecker::HandleLoop(HBasicBlock* loop_header) {
827   int id = loop_header->GetBlockId();
828   HLoopInformation* loop_information = loop_header->GetLoopInformation();
829 
830   if (loop_information->GetPreHeader()->GetSuccessors().size() != 1) {
831     AddError(StringPrintf(
832         "Loop pre-header %d of loop defined by header %d has %zu successors.",
833         loop_information->GetPreHeader()->GetBlockId(),
834         id,
835         loop_information->GetPreHeader()->GetSuccessors().size()));
836   }
837 
838   if (!GetGraph()->SuspendChecksAreAllowedToNoOp() &&
839       loop_information->GetSuspendCheck() == nullptr) {
840     AddError(StringPrintf("Loop with header %d does not have a suspend check.",
841                           loop_header->GetBlockId()));
842   }
843 
844   if (!GetGraph()->SuspendChecksAreAllowedToNoOp() &&
845       loop_information->GetSuspendCheck() != loop_header->GetFirstInstructionDisregardMoves()) {
846     AddError(StringPrintf(
847         "Loop header %d does not have the loop suspend check as the first instruction.",
848         loop_header->GetBlockId()));
849   }
850 
851   // Ensure the loop header has only one incoming branch and the remaining
852   // predecessors are back edges.
853   size_t num_preds = loop_header->GetPredecessors().size();
854   if (num_preds < 2) {
855     AddError(StringPrintf(
856         "Loop header %d has less than two predecessors: %zu.",
857         id,
858         num_preds));
859   } else {
860     HBasicBlock* first_predecessor = loop_header->GetPredecessors()[0];
861     if (loop_information->IsBackEdge(*first_predecessor)) {
862       AddError(StringPrintf(
863           "First predecessor of loop header %d is a back edge.",
864           id));
865     }
866     for (size_t i = 1, e = loop_header->GetPredecessors().size(); i < e; ++i) {
867       HBasicBlock* predecessor = loop_header->GetPredecessors()[i];
868       if (!loop_information->IsBackEdge(*predecessor)) {
869         AddError(StringPrintf(
870             "Loop header %d has multiple incoming (non back edge) blocks: %d.",
871             id,
872             predecessor->GetBlockId()));
873       }
874     }
875   }
876 
877   const ArenaBitVector& loop_blocks = loop_information->GetBlocks();
878 
879   // Ensure back edges belong to the loop.
880   if (loop_information->NumberOfBackEdges() == 0) {
881     AddError(StringPrintf(
882         "Loop defined by header %d has no back edge.",
883         id));
884   } else {
885     for (HBasicBlock* back_edge : loop_information->GetBackEdges()) {
886       int back_edge_id = back_edge->GetBlockId();
887       if (!loop_blocks.IsBitSet(back_edge_id)) {
888         AddError(StringPrintf(
889             "Loop defined by header %d has an invalid back edge %d.",
890             id,
891             back_edge_id));
892       } else if (back_edge->GetLoopInformation() != loop_information) {
893         AddError(StringPrintf(
894             "Back edge %d of loop defined by header %d belongs to nested loop "
895             "with header %d.",
896             back_edge_id,
897             id,
898             back_edge->GetLoopInformation()->GetHeader()->GetBlockId()));
899       }
900     }
901   }
902 
903   // If this is a nested loop, ensure the outer loops contain a superset of the blocks.
904   for (HLoopInformationOutwardIterator it(*loop_header); !it.Done(); it.Advance()) {
905     HLoopInformation* outer_info = it.Current();
906     if (!loop_blocks.IsSubsetOf(&outer_info->GetBlocks())) {
907       AddError(StringPrintf("Blocks of loop defined by header %d are not a subset of blocks of "
908                             "an outer loop defined by header %d.",
909                             id,
910                             outer_info->GetHeader()->GetBlockId()));
911     }
912   }
913 
914   // Ensure the pre-header block is first in the list of predecessors of a loop
915   // header and that the header block is its only successor.
916   if (!loop_header->IsLoopPreHeaderFirstPredecessor()) {
917     AddError(StringPrintf(
918         "Loop pre-header is not the first predecessor of the loop header %d.",
919         id));
920   }
921 
922   // Ensure all blocks in the loop are live and dominated by the loop header in
923   // the case of natural loops.
924   for (uint32_t i : loop_blocks.Indexes()) {
925     HBasicBlock* loop_block = GetGraph()->GetBlocks()[i];
926     if (loop_block == nullptr) {
927       AddError(StringPrintf("Loop defined by header %d contains a previously removed block %d.",
928                             id,
929                             i));
930     } else if (!loop_information->IsIrreducible() && !loop_header->Dominates(loop_block)) {
931       AddError(StringPrintf("Loop block %d not dominated by loop header %d.",
932                             i,
933                             id));
934     }
935   }
936 }
937 
IsSameSizeConstant(const HInstruction * insn1,const HInstruction * insn2)938 static bool IsSameSizeConstant(const HInstruction* insn1, const HInstruction* insn2) {
939   return insn1->IsConstant()
940       && insn2->IsConstant()
941       && DataType::Is64BitType(insn1->GetType()) == DataType::Is64BitType(insn2->GetType());
942 }
943 
IsConstantEquivalent(const HInstruction * insn1,const HInstruction * insn2,BitVector * visited)944 static bool IsConstantEquivalent(const HInstruction* insn1,
945                                  const HInstruction* insn2,
946                                  BitVector* visited) {
947   if (insn1->IsPhi() &&
948       insn1->AsPhi()->IsVRegEquivalentOf(insn2)) {
949     HConstInputsRef insn1_inputs = insn1->GetInputs();
950     HConstInputsRef insn2_inputs = insn2->GetInputs();
951     if (insn1_inputs.size() != insn2_inputs.size()) {
952       return false;
953     }
954 
955     // Testing only one of the two inputs for recursion is sufficient.
956     if (visited->IsBitSet(insn1->GetId())) {
957       return true;
958     }
959     visited->SetBit(insn1->GetId());
960 
961     for (size_t i = 0; i < insn1_inputs.size(); ++i) {
962       if (!IsConstantEquivalent(insn1_inputs[i], insn2_inputs[i], visited)) {
963         return false;
964       }
965     }
966     return true;
967   } else if (IsSameSizeConstant(insn1, insn2)) {
968     return insn1->AsConstant()->GetValueAsUint64() == insn2->AsConstant()->GetValueAsUint64();
969   } else {
970     return false;
971   }
972 }
973 
VisitPhi(HPhi * phi)974 void GraphChecker::VisitPhi(HPhi* phi) {
975   VisitInstruction(phi);
976 
977   // Ensure the first input of a phi is not itself.
978   ArrayRef<HUserRecord<HInstruction*>> input_records = phi->GetInputRecords();
979   if (input_records[0].GetInstruction() == phi) {
980     AddError(StringPrintf("Loop phi %d in block %d is its own first input.",
981                           phi->GetId(),
982                           phi->GetBlock()->GetBlockId()));
983   }
984 
985   // Ensure that the inputs have the same primitive kind as the phi.
986   for (size_t i = 0; i < input_records.size(); ++i) {
987     HInstruction* input = input_records[i].GetInstruction();
988     if (DataType::Kind(input->GetType()) != DataType::Kind(phi->GetType())) {
989         AddError(StringPrintf(
990             "Input %d at index %zu of phi %d from block %d does not have the "
991             "same kind as the phi: %s versus %s",
992             input->GetId(), i, phi->GetId(), phi->GetBlock()->GetBlockId(),
993             DataType::PrettyDescriptor(input->GetType()),
994             DataType::PrettyDescriptor(phi->GetType())));
995     }
996   }
997   if (phi->GetType() != HPhi::ToPhiType(phi->GetType())) {
998     AddError(StringPrintf("Phi %d in block %d does not have an expected phi type: %s",
999                           phi->GetId(),
1000                           phi->GetBlock()->GetBlockId(),
1001                           DataType::PrettyDescriptor(phi->GetType())));
1002   }
1003 
1004   if (phi->IsCatchPhi()) {
1005     // The number of inputs of a catch phi should be the total number of throwing
1006     // instructions caught by this catch block. We do not enforce this, however,
1007     // because we do not remove the corresponding inputs when we prove that an
1008     // instruction cannot throw. Instead, we at least test that all phis have the
1009     // same, non-zero number of inputs (b/24054676).
1010     if (input_records.empty()) {
1011       AddError(StringPrintf("Phi %d in catch block %d has zero inputs.",
1012                             phi->GetId(),
1013                             phi->GetBlock()->GetBlockId()));
1014     } else {
1015       HInstruction* next_phi = phi->GetNext();
1016       if (next_phi != nullptr) {
1017         size_t input_count_next = next_phi->InputCount();
1018         if (input_records.size() != input_count_next) {
1019           AddError(StringPrintf("Phi %d in catch block %d has %zu inputs, "
1020                                 "but phi %d has %zu inputs.",
1021                                 phi->GetId(),
1022                                 phi->GetBlock()->GetBlockId(),
1023                                 input_records.size(),
1024                                 next_phi->GetId(),
1025                                 input_count_next));
1026         }
1027       }
1028     }
1029   } else {
1030     // Ensure the number of inputs of a non-catch phi is the same as the number
1031     // of its predecessors.
1032     const ArenaVector<HBasicBlock*>& predecessors = phi->GetBlock()->GetPredecessors();
1033     if (input_records.size() != predecessors.size()) {
1034       AddError(StringPrintf(
1035           "Phi %d in block %d has %zu inputs, "
1036           "but block %d has %zu predecessors.",
1037           phi->GetId(), phi->GetBlock()->GetBlockId(), input_records.size(),
1038           phi->GetBlock()->GetBlockId(), predecessors.size()));
1039     } else {
1040       // Ensure phi input at index I either comes from the Ith
1041       // predecessor or from a block that dominates this predecessor.
1042       for (size_t i = 0; i < input_records.size(); ++i) {
1043         HInstruction* input = input_records[i].GetInstruction();
1044         HBasicBlock* predecessor = predecessors[i];
1045         if (!(input->GetBlock() == predecessor
1046               || input->GetBlock()->Dominates(predecessor))) {
1047           AddError(StringPrintf(
1048               "Input %d at index %zu of phi %d from block %d is not defined in "
1049               "predecessor number %zu nor in a block dominating it.",
1050               input->GetId(), i, phi->GetId(), phi->GetBlock()->GetBlockId(),
1051               i));
1052         }
1053       }
1054     }
1055   }
1056 
1057   // Ensure that catch phis are sorted by their vreg number, as required by
1058   // the register allocator and code generator. This does not apply to normal
1059   // phis which can be constructed artifically.
1060   if (phi->IsCatchPhi()) {
1061     HInstruction* next_phi = phi->GetNext();
1062     if (next_phi != nullptr && phi->GetRegNumber() > next_phi->AsPhi()->GetRegNumber()) {
1063       AddError(StringPrintf("Catch phis %d and %d in block %d are not sorted by their "
1064                             "vreg numbers.",
1065                             phi->GetId(),
1066                             next_phi->GetId(),
1067                             phi->GetBlock()->GetBlockId()));
1068     }
1069   }
1070 
1071   // Test phi equivalents. There should not be two of the same type and they should only be
1072   // created for constants which were untyped in DEX. Note that this test can be skipped for
1073   // a synthetic phi (indicated by lack of a virtual register).
1074   if (phi->GetRegNumber() != kNoRegNumber) {
1075     for (HInstructionIterator phi_it(phi->GetBlock()->GetPhis());
1076          !phi_it.Done();
1077          phi_it.Advance()) {
1078       HPhi* other_phi = phi_it.Current()->AsPhi();
1079       if (phi != other_phi && phi->GetRegNumber() == other_phi->GetRegNumber()) {
1080         if (phi->GetType() == other_phi->GetType()) {
1081           std::stringstream type_str;
1082           type_str << phi->GetType();
1083           AddError(StringPrintf("Equivalent phi (%d) found for VReg %d with type: %s.",
1084                                 phi->GetId(),
1085                                 phi->GetRegNumber(),
1086                                 type_str.str().c_str()));
1087         } else if (phi->GetType() == DataType::Type::kReference) {
1088           std::stringstream type_str;
1089           type_str << other_phi->GetType();
1090           AddError(StringPrintf(
1091               "Equivalent non-reference phi (%d) found for VReg %d with type: %s.",
1092               phi->GetId(),
1093               phi->GetRegNumber(),
1094               type_str.str().c_str()));
1095         } else {
1096           // Use local allocator for allocating memory.
1097           ScopedArenaAllocator allocator(GetGraph()->GetArenaStack());
1098           // If we get here, make sure we allocate all the necessary storage at once
1099           // because the BitVector reallocation strategy has very bad worst-case behavior.
1100           ArenaBitVector visited(&allocator,
1101                                  GetGraph()->GetCurrentInstructionId(),
1102                                  /* expandable= */ false,
1103                                  kArenaAllocGraphChecker);
1104           visited.ClearAllBits();
1105           if (!IsConstantEquivalent(phi, other_phi, &visited)) {
1106             AddError(StringPrintf("Two phis (%d and %d) found for VReg %d but they "
1107                                   "are not equivalents of constants.",
1108                                   phi->GetId(),
1109                                   other_phi->GetId(),
1110                                   phi->GetRegNumber()));
1111           }
1112         }
1113       }
1114     }
1115   }
1116 }
1117 
HandleBooleanInput(HInstruction * instruction,size_t input_index)1118 void GraphChecker::HandleBooleanInput(HInstruction* instruction, size_t input_index) {
1119   HInstruction* input = instruction->InputAt(input_index);
1120   if (input->IsIntConstant()) {
1121     int32_t value = input->AsIntConstant()->GetValue();
1122     if (value != 0 && value != 1) {
1123       AddError(StringPrintf(
1124           "%s instruction %d has a non-Boolean constant input %d whose value is: %d.",
1125           instruction->DebugName(),
1126           instruction->GetId(),
1127           static_cast<int>(input_index),
1128           value));
1129     }
1130   } else if (DataType::Kind(input->GetType()) != DataType::Type::kInt32) {
1131     // TODO: We need a data-flow analysis to determine if an input like Phi,
1132     //       Select or a binary operation is actually Boolean. Allow for now.
1133     AddError(StringPrintf(
1134         "%s instruction %d has a non-integer input %d whose type is: %s.",
1135         instruction->DebugName(),
1136         instruction->GetId(),
1137         static_cast<int>(input_index),
1138         DataType::PrettyDescriptor(input->GetType())));
1139   }
1140 }
1141 
VisitPackedSwitch(HPackedSwitch * instruction)1142 void GraphChecker::VisitPackedSwitch(HPackedSwitch* instruction) {
1143   VisitInstruction(instruction);
1144   // Check that the number of block successors matches the switch count plus
1145   // one for the default block.
1146   HBasicBlock* block = instruction->GetBlock();
1147   if (instruction->GetNumEntries() + 1u != block->GetSuccessors().size()) {
1148     AddError(StringPrintf(
1149         "%s instruction %d in block %d expects %u successors to the block, but found: %zu.",
1150         instruction->DebugName(),
1151         instruction->GetId(),
1152         block->GetBlockId(),
1153         instruction->GetNumEntries() + 1u,
1154         block->GetSuccessors().size()));
1155   }
1156 }
1157 
VisitIf(HIf * instruction)1158 void GraphChecker::VisitIf(HIf* instruction) {
1159   VisitInstruction(instruction);
1160   HandleBooleanInput(instruction, 0);
1161 }
1162 
VisitSelect(HSelect * instruction)1163 void GraphChecker::VisitSelect(HSelect* instruction) {
1164   VisitInstruction(instruction);
1165   HandleBooleanInput(instruction, 2);
1166 }
1167 
VisitBooleanNot(HBooleanNot * instruction)1168 void GraphChecker::VisitBooleanNot(HBooleanNot* instruction) {
1169   VisitInstruction(instruction);
1170   HandleBooleanInput(instruction, 0);
1171 }
1172 
VisitCondition(HCondition * op)1173 void GraphChecker::VisitCondition(HCondition* op) {
1174   VisitInstruction(op);
1175   if (op->GetType() != DataType::Type::kBool) {
1176     AddError(StringPrintf(
1177         "Condition %s %d has a non-Boolean result type: %s.",
1178         op->DebugName(), op->GetId(),
1179         DataType::PrettyDescriptor(op->GetType())));
1180   }
1181   HInstruction* lhs = op->InputAt(0);
1182   HInstruction* rhs = op->InputAt(1);
1183   if (DataType::Kind(lhs->GetType()) != DataType::Kind(rhs->GetType())) {
1184     AddError(StringPrintf(
1185         "Condition %s %d has inputs of different kinds: %s, and %s.",
1186         op->DebugName(), op->GetId(),
1187         DataType::PrettyDescriptor(lhs->GetType()),
1188         DataType::PrettyDescriptor(rhs->GetType())));
1189   }
1190   if (!op->IsEqual() && !op->IsNotEqual()) {
1191     if ((lhs->GetType() == DataType::Type::kReference)) {
1192       AddError(StringPrintf(
1193           "Condition %s %d uses an object as left-hand side input.",
1194           op->DebugName(), op->GetId()));
1195     } else if (rhs->GetType() == DataType::Type::kReference) {
1196       AddError(StringPrintf(
1197           "Condition %s %d uses an object as right-hand side input.",
1198           op->DebugName(), op->GetId()));
1199     }
1200   }
1201 }
1202 
VisitNeg(HNeg * instruction)1203 void GraphChecker::VisitNeg(HNeg* instruction) {
1204   VisitInstruction(instruction);
1205   DataType::Type input_type = instruction->InputAt(0)->GetType();
1206   DataType::Type result_type = instruction->GetType();
1207   if (result_type != DataType::Kind(input_type)) {
1208     AddError(StringPrintf("Binary operation %s %d has a result type different "
1209                           "from its input kind: %s vs %s.",
1210                           instruction->DebugName(), instruction->GetId(),
1211                           DataType::PrettyDescriptor(result_type),
1212                           DataType::PrettyDescriptor(input_type)));
1213   }
1214 }
1215 
VisitArraySet(HArraySet * instruction)1216 void GraphChecker::VisitArraySet(HArraySet* instruction) {
1217   VisitInstruction(instruction);
1218 
1219   if (instruction->NeedsTypeCheck() !=
1220       instruction->GetSideEffects().Includes(SideEffects::CanTriggerGC())) {
1221     AddError(
1222         StringPrintf("%s %d has a flag mismatch. An ArraySet instruction can trigger a GC iff it "
1223                      "needs a type check. Needs type check: %s, Can trigger GC: %s",
1224                      instruction->DebugName(),
1225                      instruction->GetId(),
1226                      StrBool(instruction->NeedsTypeCheck()),
1227                      StrBool(instruction->GetSideEffects().Includes(SideEffects::CanTriggerGC()))));
1228   }
1229 }
1230 
VisitBinaryOperation(HBinaryOperation * op)1231 void GraphChecker::VisitBinaryOperation(HBinaryOperation* op) {
1232   VisitInstruction(op);
1233   DataType::Type lhs_type = op->InputAt(0)->GetType();
1234   DataType::Type rhs_type = op->InputAt(1)->GetType();
1235   DataType::Type result_type = op->GetType();
1236 
1237   // Type consistency between inputs.
1238   if (op->IsUShr() || op->IsShr() || op->IsShl() || op->IsRor()) {
1239     if (DataType::Kind(rhs_type) != DataType::Type::kInt32) {
1240       AddError(StringPrintf("Shift/rotate operation %s %d has a non-int kind second input: "
1241                             "%s of type %s.",
1242                             op->DebugName(), op->GetId(),
1243                             op->InputAt(1)->DebugName(),
1244                             DataType::PrettyDescriptor(rhs_type)));
1245     }
1246   } else {
1247     if (DataType::Kind(lhs_type) != DataType::Kind(rhs_type)) {
1248       AddError(StringPrintf("Binary operation %s %d has inputs of different kinds: %s, and %s.",
1249                             op->DebugName(), op->GetId(),
1250                             DataType::PrettyDescriptor(lhs_type),
1251                             DataType::PrettyDescriptor(rhs_type)));
1252     }
1253   }
1254 
1255   // Type consistency between result and input(s).
1256   if (op->IsCompare()) {
1257     if (result_type != DataType::Type::kInt32) {
1258       AddError(StringPrintf("Compare operation %d has a non-int result type: %s.",
1259                             op->GetId(),
1260                             DataType::PrettyDescriptor(result_type)));
1261     }
1262   } else if (op->IsUShr() || op->IsShr() || op->IsShl() || op->IsRor()) {
1263     // Only check the first input (value), as the second one (distance)
1264     // must invariably be of kind `int`.
1265     if (result_type != DataType::Kind(lhs_type)) {
1266       AddError(StringPrintf("Shift/rotate operation %s %d has a result type different "
1267                             "from its left-hand side (value) input kind: %s vs %s.",
1268                             op->DebugName(), op->GetId(),
1269                             DataType::PrettyDescriptor(result_type),
1270                             DataType::PrettyDescriptor(lhs_type)));
1271     }
1272   } else {
1273     if (DataType::Kind(result_type) != DataType::Kind(lhs_type)) {
1274       AddError(StringPrintf("Binary operation %s %d has a result kind different "
1275                             "from its left-hand side input kind: %s vs %s.",
1276                             op->DebugName(), op->GetId(),
1277                             DataType::PrettyDescriptor(result_type),
1278                             DataType::PrettyDescriptor(lhs_type)));
1279     }
1280     if (DataType::Kind(result_type) != DataType::Kind(rhs_type)) {
1281       AddError(StringPrintf("Binary operation %s %d has a result kind different "
1282                             "from its right-hand side input kind: %s vs %s.",
1283                             op->DebugName(), op->GetId(),
1284                             DataType::PrettyDescriptor(result_type),
1285                             DataType::PrettyDescriptor(rhs_type)));
1286     }
1287   }
1288 }
1289 
VisitConstant(HConstant * instruction)1290 void GraphChecker::VisitConstant(HConstant* instruction) {
1291   VisitInstruction(instruction);
1292 
1293   HBasicBlock* block = instruction->GetBlock();
1294   if (!block->IsEntryBlock()) {
1295     AddError(StringPrintf(
1296         "%s %d should be in the entry block but is in block %d.",
1297         instruction->DebugName(),
1298         instruction->GetId(),
1299         block->GetBlockId()));
1300   }
1301 }
1302 
VisitBoundType(HBoundType * instruction)1303 void GraphChecker::VisitBoundType(HBoundType* instruction) {
1304   VisitInstruction(instruction);
1305 
1306   if (!instruction->GetUpperBound().IsValid()) {
1307     AddError(StringPrintf(
1308         "%s %d does not have a valid upper bound RTI.",
1309         instruction->DebugName(),
1310         instruction->GetId()));
1311   }
1312 }
1313 
VisitTypeConversion(HTypeConversion * instruction)1314 void GraphChecker::VisitTypeConversion(HTypeConversion* instruction) {
1315   VisitInstruction(instruction);
1316   DataType::Type result_type = instruction->GetResultType();
1317   DataType::Type input_type = instruction->GetInputType();
1318   // Invariant: We should never generate a conversion to a Boolean value.
1319   if (result_type == DataType::Type::kBool) {
1320     AddError(StringPrintf(
1321         "%s %d converts to a %s (from a %s).",
1322         instruction->DebugName(),
1323         instruction->GetId(),
1324         DataType::PrettyDescriptor(result_type),
1325         DataType::PrettyDescriptor(input_type)));
1326   }
1327 }
1328 
VisitVecOperation(HVecOperation * instruction)1329 void GraphChecker::VisitVecOperation(HVecOperation* instruction) {
1330   VisitInstruction(instruction);
1331 
1332   if (!GetGraph()->HasSIMD()) {
1333     AddError(
1334         StringPrintf("The graph doesn't have the HasSIMD flag set but we saw "
1335                      "%s:%d in block %d.",
1336                      instruction->DebugName(),
1337                      instruction->GetId(),
1338                      instruction->GetBlock()->GetBlockId()));
1339   }
1340 
1341   flag_info_.seen_SIMD = true;
1342 
1343   if (codegen_ == nullptr) {
1344     return;
1345   }
1346 
1347   if (!codegen_->SupportsPredicatedSIMD() && instruction->IsPredicated()) {
1348     AddError(StringPrintf(
1349              "%s %d must not be predicated.",
1350              instruction->DebugName(),
1351              instruction->GetId()));
1352   }
1353 
1354   if (codegen_->SupportsPredicatedSIMD() &&
1355       (instruction->MustBePredicatedInPredicatedSIMDMode() != instruction->IsPredicated())) {
1356     AddError(StringPrintf(
1357              "%s %d predication mode is incorrect; see HVecOperation::MustBePredicated.",
1358              instruction->DebugName(),
1359              instruction->GetId()));
1360   }
1361 }
1362 
1363 }  // namespace art
1364