• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 "loop_optimization.h"
18 
19 #include "arch/arm/instruction_set_features_arm.h"
20 #include "arch/arm64/instruction_set_features_arm64.h"
21 #include "arch/instruction_set.h"
22 #include "arch/x86/instruction_set_features_x86.h"
23 #include "arch/x86_64/instruction_set_features_x86_64.h"
24 #include "code_generator.h"
25 #include "driver/compiler_options.h"
26 #include "linear_order.h"
27 #include "mirror/array-inl.h"
28 #include "mirror/string.h"
29 
30 namespace art {
31 
32 // Enables vectorization (SIMDization) in the loop optimizer.
33 static constexpr bool kEnableVectorization = true;
34 
35 //
36 // Static helpers.
37 //
38 
39 // Base alignment for arrays/strings guaranteed by the Android runtime.
BaseAlignment()40 static uint32_t BaseAlignment() {
41   return kObjectAlignment;
42 }
43 
44 // Hidden offset for arrays/strings guaranteed by the Android runtime.
HiddenOffset(DataType::Type type,bool is_string_char_at)45 static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
46   return is_string_char_at
47       ? mirror::String::ValueOffset().Uint32Value()
48       : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
49 }
50 
51 // Remove the instruction from the graph. A bit more elaborate than the usual
52 // instruction removal, since there may be a cycle in the use structure.
RemoveFromCycle(HInstruction * instruction)53 static void RemoveFromCycle(HInstruction* instruction) {
54   instruction->RemoveAsUserOfAllInputs();
55   instruction->RemoveEnvironmentUsers();
56   instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
57   RemoveEnvironmentUses(instruction);
58   ResetEnvironmentInputRecords(instruction);
59 }
60 
61 // Detect a goto block and sets succ to the single successor.
IsGotoBlock(HBasicBlock * block,HBasicBlock ** succ)62 static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
63   if (block->GetPredecessors().size() == 1 &&
64       block->GetSuccessors().size() == 1 &&
65       block->IsSingleGoto()) {
66     *succ = block->GetSingleSuccessor();
67     return true;
68   }
69   return false;
70 }
71 
72 // Detect an early exit loop.
IsEarlyExit(HLoopInformation * loop_info)73 static bool IsEarlyExit(HLoopInformation* loop_info) {
74   HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
75   for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
76     for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
77       if (!loop_info->Contains(*successor)) {
78         return true;
79       }
80     }
81   }
82   return false;
83 }
84 
85 // Forward declaration.
86 static bool IsZeroExtensionAndGet(HInstruction* instruction,
87                                   DataType::Type type,
88                                   /*out*/ HInstruction** operand);
89 
90 // Detect a sign extension in instruction from the given type.
91 // Returns the promoted operand on success.
IsSignExtensionAndGet(HInstruction * instruction,DataType::Type type,HInstruction ** operand)92 static bool IsSignExtensionAndGet(HInstruction* instruction,
93                                   DataType::Type type,
94                                   /*out*/ HInstruction** operand) {
95   // Accept any already wider constant that would be handled properly by sign
96   // extension when represented in the *width* of the given narrower data type
97   // (the fact that Uint8/Uint16 normally zero extend does not matter here).
98   int64_t value = 0;
99   if (IsInt64AndGet(instruction, /*out*/ &value)) {
100     switch (type) {
101       case DataType::Type::kUint8:
102       case DataType::Type::kInt8:
103         if (IsInt<8>(value)) {
104           *operand = instruction;
105           return true;
106         }
107         return false;
108       case DataType::Type::kUint16:
109       case DataType::Type::kInt16:
110         if (IsInt<16>(value)) {
111           *operand = instruction;
112           return true;
113         }
114         return false;
115       default:
116         return false;
117     }
118   }
119   // An implicit widening conversion of any signed expression sign-extends.
120   if (instruction->GetType() == type) {
121     switch (type) {
122       case DataType::Type::kInt8:
123       case DataType::Type::kInt16:
124         *operand = instruction;
125         return true;
126       default:
127         return false;
128     }
129   }
130   // An explicit widening conversion of a signed expression sign-extends.
131   if (instruction->IsTypeConversion()) {
132     HInstruction* conv = instruction->InputAt(0);
133     DataType::Type from = conv->GetType();
134     switch (instruction->GetType()) {
135       case DataType::Type::kInt32:
136       case DataType::Type::kInt64:
137         if (type == from && (from == DataType::Type::kInt8 ||
138                              from == DataType::Type::kInt16 ||
139                              from == DataType::Type::kInt32)) {
140           *operand = conv;
141           return true;
142         }
143         return false;
144       case DataType::Type::kInt16:
145         return type == DataType::Type::kUint16 &&
146                from == DataType::Type::kUint16 &&
147                IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
148       default:
149         return false;
150     }
151   }
152   return false;
153 }
154 
155 // Detect a zero extension in instruction from the given type.
156 // Returns the promoted operand on success.
IsZeroExtensionAndGet(HInstruction * instruction,DataType::Type type,HInstruction ** operand)157 static bool IsZeroExtensionAndGet(HInstruction* instruction,
158                                   DataType::Type type,
159                                   /*out*/ HInstruction** operand) {
160   // Accept any already wider constant that would be handled properly by zero
161   // extension when represented in the *width* of the given narrower data type
162   // (the fact that Int8/Int16 normally sign extend does not matter here).
163   int64_t value = 0;
164   if (IsInt64AndGet(instruction, /*out*/ &value)) {
165     switch (type) {
166       case DataType::Type::kUint8:
167       case DataType::Type::kInt8:
168         if (IsUint<8>(value)) {
169           *operand = instruction;
170           return true;
171         }
172         return false;
173       case DataType::Type::kUint16:
174       case DataType::Type::kInt16:
175         if (IsUint<16>(value)) {
176           *operand = instruction;
177           return true;
178         }
179         return false;
180       default:
181         return false;
182     }
183   }
184   // An implicit widening conversion of any unsigned expression zero-extends.
185   if (instruction->GetType() == type) {
186     switch (type) {
187       case DataType::Type::kUint8:
188       case DataType::Type::kUint16:
189         *operand = instruction;
190         return true;
191       default:
192         return false;
193     }
194   }
195   // An explicit widening conversion of an unsigned expression zero-extends.
196   if (instruction->IsTypeConversion()) {
197     HInstruction* conv = instruction->InputAt(0);
198     DataType::Type from = conv->GetType();
199     switch (instruction->GetType()) {
200       case DataType::Type::kInt32:
201       case DataType::Type::kInt64:
202         if (type == from && from == DataType::Type::kUint16) {
203           *operand = conv;
204           return true;
205         }
206         return false;
207       case DataType::Type::kUint16:
208         return type == DataType::Type::kInt16 &&
209                from == DataType::Type::kInt16 &&
210                IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
211       default:
212         return false;
213     }
214   }
215   return false;
216 }
217 
218 // Detect situations with same-extension narrower operands.
219 // Returns true on success and sets is_unsigned accordingly.
IsNarrowerOperands(HInstruction * a,HInstruction * b,DataType::Type type,HInstruction ** r,HInstruction ** s,bool * is_unsigned)220 static bool IsNarrowerOperands(HInstruction* a,
221                                HInstruction* b,
222                                DataType::Type type,
223                                /*out*/ HInstruction** r,
224                                /*out*/ HInstruction** s,
225                                /*out*/ bool* is_unsigned) {
226   DCHECK(a != nullptr && b != nullptr);
227   // Look for a matching sign extension.
228   DataType::Type stype = HVecOperation::ToSignedType(type);
229   if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
230     *is_unsigned = false;
231     return true;
232   }
233   // Look for a matching zero extension.
234   DataType::Type utype = HVecOperation::ToUnsignedType(type);
235   if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
236     *is_unsigned = true;
237     return true;
238   }
239   return false;
240 }
241 
242 // As above, single operand.
IsNarrowerOperand(HInstruction * a,DataType::Type type,HInstruction ** r,bool * is_unsigned)243 static bool IsNarrowerOperand(HInstruction* a,
244                               DataType::Type type,
245                               /*out*/ HInstruction** r,
246                               /*out*/ bool* is_unsigned) {
247   DCHECK(a != nullptr);
248   // Look for a matching sign extension.
249   DataType::Type stype = HVecOperation::ToSignedType(type);
250   if (IsSignExtensionAndGet(a, stype, r)) {
251     *is_unsigned = false;
252     return true;
253   }
254   // Look for a matching zero extension.
255   DataType::Type utype = HVecOperation::ToUnsignedType(type);
256   if (IsZeroExtensionAndGet(a, utype, r)) {
257     *is_unsigned = true;
258     return true;
259   }
260   return false;
261 }
262 
263 // Compute relative vector length based on type difference.
GetOtherVL(DataType::Type other_type,DataType::Type vector_type,uint32_t vl)264 static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
265   DCHECK(DataType::IsIntegralType(other_type));
266   DCHECK(DataType::IsIntegralType(vector_type));
267   DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
268   return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
269 }
270 
271 // Detect up to two added operands a and b and an acccumulated constant c.
IsAddConst(HInstruction * instruction,HInstruction ** a,HInstruction ** b,int64_t * c,int32_t depth=8)272 static bool IsAddConst(HInstruction* instruction,
273                        /*out*/ HInstruction** a,
274                        /*out*/ HInstruction** b,
275                        /*out*/ int64_t* c,
276                        int32_t depth = 8) {  // don't search too deep
277   int64_t value = 0;
278   // Enter add/sub while still within reasonable depth.
279   if (depth > 0) {
280     if (instruction->IsAdd()) {
281       return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
282              IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
283     } else if (instruction->IsSub() &&
284                IsInt64AndGet(instruction->InputAt(1), &value)) {
285       *c -= value;
286       return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
287     }
288   }
289   // Otherwise, deal with leaf nodes.
290   if (IsInt64AndGet(instruction, &value)) {
291     *c += value;
292     return true;
293   } else if (*a == nullptr) {
294     *a = instruction;
295     return true;
296   } else if (*b == nullptr) {
297     *b = instruction;
298     return true;
299   }
300   return false;  // too many operands
301 }
302 
303 // Detect a + b + c with optional constant c.
IsAddConst2(HGraph * graph,HInstruction * instruction,HInstruction ** a,HInstruction ** b,int64_t * c)304 static bool IsAddConst2(HGraph* graph,
305                         HInstruction* instruction,
306                         /*out*/ HInstruction** a,
307                         /*out*/ HInstruction** b,
308                         /*out*/ int64_t* c) {
309   // We want an actual add/sub and not the trivial case where {b: 0, c: 0}.
310   if (IsAddOrSub(instruction) && IsAddConst(instruction, a, b, c) && *a != nullptr) {
311     if (*b == nullptr) {
312       // Constant is usually already present, unless accumulated.
313       *b = graph->GetConstant(instruction->GetType(), (*c));
314       *c = 0;
315     }
316     return true;
317   }
318   return false;
319 }
320 
321 // Detect a direct a - b or a hidden a - (-c).
IsSubConst2(HGraph * graph,HInstruction * instruction,HInstruction ** a,HInstruction ** b)322 static bool IsSubConst2(HGraph* graph,
323                         HInstruction* instruction,
324                         /*out*/ HInstruction** a,
325                         /*out*/ HInstruction** b) {
326   int64_t c = 0;
327   if (instruction->IsSub()) {
328     *a = instruction->InputAt(0);
329     *b = instruction->InputAt(1);
330     return true;
331   } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
332     // Constant for the hidden subtraction.
333     *b = graph->GetConstant(instruction->GetType(), -c);
334     return true;
335   }
336   return false;
337 }
338 
339 // Detect reductions of the following forms,
340 //   x = x_phi + ..
341 //   x = x_phi - ..
HasReductionFormat(HInstruction * reduction,HInstruction * phi)342 static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
343   if (reduction->IsAdd()) {
344     return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
345            (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
346   } else if (reduction->IsSub()) {
347     return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
348   }
349   return false;
350 }
351 
352 // Translates vector operation to reduction kind.
GetReductionKind(HVecOperation * reduction)353 static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
354   if (reduction->IsVecAdd()  ||
355       reduction->IsVecSub() ||
356       reduction->IsVecSADAccumulate() ||
357       reduction->IsVecDotProd()) {
358     return HVecReduce::kSum;
359   }
360   LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
361   UNREACHABLE();
362 }
363 
364 // Test vector restrictions.
HasVectorRestrictions(uint64_t restrictions,uint64_t tested)365 static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
366   return (restrictions & tested) != 0;
367 }
368 
369 // Insert an instruction.
Insert(HBasicBlock * block,HInstruction * instruction)370 static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
371   DCHECK(block != nullptr);
372   DCHECK(instruction != nullptr);
373   block->InsertInstructionBefore(instruction, block->GetLastInstruction());
374   return instruction;
375 }
376 
377 // Check that instructions from the induction sets are fully removed: have no uses
378 // and no other instructions use them.
CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction * > * iset)379 static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
380   for (HInstruction* instr : *iset) {
381     if (instr->GetBlock() != nullptr ||
382         !instr->GetUses().empty() ||
383         !instr->GetEnvUses().empty() ||
384         HasEnvironmentUsedByOthers(instr)) {
385       return false;
386     }
387   }
388   return true;
389 }
390 
391 // Tries to statically evaluate condition of the specified "HIf" for other condition checks.
TryToEvaluateIfCondition(HIf * instruction,HGraph * graph)392 static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
393   HInstruction* cond = instruction->InputAt(0);
394 
395   // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
396   // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
397   // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
398   // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
399   // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
400   //     if (cond) {               if(cond) {
401   //       if (cond) {}              if (1) {}
402   //     } else {        =======>  } else {
403   //       if (cond) {}              if (0) {}
404   //     }                         }
405   if (!cond->IsConstant()) {
406     HBasicBlock* true_succ = instruction->IfTrueSuccessor();
407     HBasicBlock* false_succ = instruction->IfFalseSuccessor();
408 
409     DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
410     DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
411 
412     const HUseList<HInstruction*>& uses = cond->GetUses();
413     for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
414       HInstruction* user = it->GetUser();
415       size_t index = it->GetIndex();
416       HBasicBlock* user_block = user->GetBlock();
417       // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
418       ++it;
419       if (true_succ->Dominates(user_block)) {
420         user->ReplaceInput(graph->GetIntConstant(1), index);
421      } else if (false_succ->Dominates(user_block)) {
422         user->ReplaceInput(graph->GetIntConstant(0), index);
423       }
424     }
425   }
426 }
427 
428 // Peel the first 'count' iterations of the loop.
PeelByCount(HLoopInformation * loop_info,int count,InductionVarRange * induction_range)429 static void PeelByCount(HLoopInformation* loop_info,
430                         int count,
431                         InductionVarRange* induction_range) {
432   for (int i = 0; i < count; i++) {
433     // Perform peeling.
434     LoopClonerSimpleHelper helper(loop_info, induction_range);
435     helper.DoPeeling();
436   }
437 }
438 
439 // Returns the narrower type out of instructions a and b types.
GetNarrowerType(HInstruction * a,HInstruction * b)440 static DataType::Type GetNarrowerType(HInstruction* a, HInstruction* b) {
441   DataType::Type type = a->GetType();
442   if (DataType::Size(b->GetType()) < DataType::Size(type)) {
443     type = b->GetType();
444   }
445   if (a->IsTypeConversion() &&
446       DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(type)) {
447     type = a->InputAt(0)->GetType();
448   }
449   if (b->IsTypeConversion() &&
450       DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(type)) {
451     type = b->InputAt(0)->GetType();
452   }
453   return type;
454 }
455 
456 //
457 // Public methods.
458 //
459 
HLoopOptimization(HGraph * graph,const CodeGenerator & codegen,HInductionVarAnalysis * induction_analysis,OptimizingCompilerStats * stats,const char * name)460 HLoopOptimization::HLoopOptimization(HGraph* graph,
461                                      const CodeGenerator& codegen,
462                                      HInductionVarAnalysis* induction_analysis,
463                                      OptimizingCompilerStats* stats,
464                                      const char* name)
465     : HOptimization(graph, name, stats),
466       compiler_options_(&codegen.GetCompilerOptions()),
467       simd_register_size_(codegen.GetSIMDRegisterWidth()),
468       induction_range_(induction_analysis),
469       loop_allocator_(nullptr),
470       global_allocator_(graph_->GetAllocator()),
471       top_loop_(nullptr),
472       last_loop_(nullptr),
473       iset_(nullptr),
474       reductions_(nullptr),
475       simplified_(false),
476       predicated_vectorization_mode_(codegen.SupportsPredicatedSIMD()),
477       vector_length_(0),
478       vector_refs_(nullptr),
479       vector_static_peeling_factor_(0),
480       vector_dynamic_peeling_candidate_(nullptr),
481       vector_runtime_test_a_(nullptr),
482       vector_runtime_test_b_(nullptr),
483       vector_map_(nullptr),
484       vector_permanent_map_(nullptr),
485       vector_mode_(kSequential),
486       vector_preheader_(nullptr),
487       vector_header_(nullptr),
488       vector_body_(nullptr),
489       vector_index_(nullptr),
490       arch_loop_helper_(ArchNoOptsLoopHelper::Create(codegen, global_allocator_)) {
491 }
492 
Run()493 bool HLoopOptimization::Run() {
494   // Skip if there is no loop or the graph has try-catch/irreducible loops.
495   // TODO: make this less of a sledgehammer.
496   if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
497     return false;
498   }
499 
500   // Phase-local allocator.
501   ScopedArenaAllocator allocator(graph_->GetArenaStack());
502   loop_allocator_ = &allocator;
503 
504   // Perform loop optimizations.
505   bool didLoopOpt = LocalRun();
506   if (top_loop_ == nullptr) {
507     graph_->SetHasLoops(false);  // no more loops
508   }
509 
510   // Detach.
511   loop_allocator_ = nullptr;
512   last_loop_ = top_loop_ = nullptr;
513 
514   return didLoopOpt;
515 }
516 
517 //
518 // Loop setup and traversal.
519 //
520 
LocalRun()521 bool HLoopOptimization::LocalRun() {
522   bool didLoopOpt = false;
523   // Build the linear order using the phase-local allocator. This step enables building
524   // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
525   ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
526   LinearizeGraph(graph_, &linear_order);
527 
528   // Build the loop hierarchy.
529   for (HBasicBlock* block : linear_order) {
530     if (block->IsLoopHeader()) {
531       AddLoop(block->GetLoopInformation());
532     }
533   }
534 
535   // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
536   // temporary data structures using the phase-local allocator. All new HIR
537   // should use the global allocator.
538   if (top_loop_ != nullptr) {
539     ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
540     ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
541         std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
542     ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
543     ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
544         std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
545     ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
546         std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
547     // Attach.
548     iset_ = &iset;
549     reductions_ = &reds;
550     vector_refs_ = &refs;
551     vector_map_ = &map;
552     vector_permanent_map_ = &perm;
553     // Traverse.
554     didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
555     // Detach.
556     iset_ = nullptr;
557     reductions_ = nullptr;
558     vector_refs_ = nullptr;
559     vector_map_ = nullptr;
560     vector_permanent_map_ = nullptr;
561   }
562   return didLoopOpt;
563 }
564 
AddLoop(HLoopInformation * loop_info)565 void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
566   DCHECK(loop_info != nullptr);
567   LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
568   if (last_loop_ == nullptr) {
569     // First loop.
570     DCHECK(top_loop_ == nullptr);
571     last_loop_ = top_loop_ = node;
572   } else if (loop_info->IsIn(*last_loop_->loop_info)) {
573     // Inner loop.
574     node->outer = last_loop_;
575     DCHECK(last_loop_->inner == nullptr);
576     last_loop_ = last_loop_->inner = node;
577   } else {
578     // Subsequent loop.
579     while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
580       last_loop_ = last_loop_->outer;
581     }
582     node->outer = last_loop_->outer;
583     node->previous = last_loop_;
584     DCHECK(last_loop_->next == nullptr);
585     last_loop_ = last_loop_->next = node;
586   }
587 }
588 
RemoveLoop(LoopNode * node)589 void HLoopOptimization::RemoveLoop(LoopNode* node) {
590   DCHECK(node != nullptr);
591   DCHECK(node->inner == nullptr);
592   if (node->previous != nullptr) {
593     // Within sequence.
594     node->previous->next = node->next;
595     if (node->next != nullptr) {
596       node->next->previous = node->previous;
597     }
598   } else {
599     // First of sequence.
600     if (node->outer != nullptr) {
601       node->outer->inner = node->next;
602     } else {
603       top_loop_ = node->next;
604     }
605     if (node->next != nullptr) {
606       node->next->outer = node->outer;
607       node->next->previous = nullptr;
608     }
609   }
610 }
611 
TraverseLoopsInnerToOuter(LoopNode * node)612 bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
613   bool changed = false;
614   for ( ; node != nullptr; node = node->next) {
615     // Visit inner loops first. Recompute induction information for this
616     // loop if the induction of any inner loop has changed.
617     if (TraverseLoopsInnerToOuter(node->inner)) {
618       induction_range_.ReVisit(node->loop_info);
619       changed = true;
620     }
621     // Repeat simplifications in the loop-body until no more changes occur.
622     // Note that since each simplification consists of eliminating code (without
623     // introducing new code), this process is always finite.
624     do {
625       simplified_ = false;
626       SimplifyInduction(node);
627       SimplifyBlocks(node);
628       changed = simplified_ || changed;
629     } while (simplified_);
630     // Optimize inner loop.
631     if (node->inner == nullptr) {
632       changed = OptimizeInnerLoop(node) || changed;
633     }
634   }
635   return changed;
636 }
637 
638 //
639 // Optimization.
640 //
641 
SimplifyInduction(LoopNode * node)642 void HLoopOptimization::SimplifyInduction(LoopNode* node) {
643   HBasicBlock* header = node->loop_info->GetHeader();
644   HBasicBlock* preheader = node->loop_info->GetPreHeader();
645   // Scan the phis in the header to find opportunities to simplify an induction
646   // cycle that is only used outside the loop. Replace these uses, if any, with
647   // the last value and remove the induction cycle.
648   // Examples: for (int i = 0; x != null;   i++) { .... no i .... }
649   //           for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
650   for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
651     HPhi* phi = it.Current()->AsPhi();
652     if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
653         TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
654       // Note that it's ok to have replaced uses after the loop with the last value, without
655       // being able to remove the cycle. Environment uses (which are the reason we may not be
656       // able to remove the cycle) within the loop will still hold the right value. We must
657       // have tried first, however, to replace outside uses.
658       if (CanRemoveCycle()) {
659         simplified_ = true;
660         for (HInstruction* i : *iset_) {
661           RemoveFromCycle(i);
662         }
663         DCHECK(CheckInductionSetFullyRemoved(iset_));
664       }
665     }
666   }
667 }
668 
SimplifyBlocks(LoopNode * node)669 void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
670   // Iterate over all basic blocks in the loop-body.
671   for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
672     HBasicBlock* block = it.Current();
673     // Remove dead instructions from the loop-body.
674     RemoveDeadInstructions(block->GetPhis());
675     RemoveDeadInstructions(block->GetInstructions());
676     // Remove trivial control flow blocks from the loop-body.
677     if (block->GetPredecessors().size() == 1 &&
678         block->GetSuccessors().size() == 1 &&
679         block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
680       simplified_ = true;
681       block->MergeWith(block->GetSingleSuccessor());
682     } else if (block->GetSuccessors().size() == 2) {
683       // Trivial if block can be bypassed to either branch.
684       HBasicBlock* succ0 = block->GetSuccessors()[0];
685       HBasicBlock* succ1 = block->GetSuccessors()[1];
686       HBasicBlock* meet0 = nullptr;
687       HBasicBlock* meet1 = nullptr;
688       if (succ0 != succ1 &&
689           IsGotoBlock(succ0, &meet0) &&
690           IsGotoBlock(succ1, &meet1) &&
691           meet0 == meet1 &&  // meets again
692           meet0 != block &&  // no self-loop
693           meet0->GetPhis().IsEmpty()) {  // not used for merging
694         simplified_ = true;
695         succ0->DisconnectAndDelete();
696         if (block->Dominates(meet0)) {
697           block->RemoveDominatedBlock(meet0);
698           succ1->AddDominatedBlock(meet0);
699           meet0->SetDominator(succ1);
700         }
701       }
702     }
703   }
704 }
705 
TryOptimizeInnerLoopFinite(LoopNode * node)706 bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
707   HBasicBlock* header = node->loop_info->GetHeader();
708   HBasicBlock* preheader = node->loop_info->GetPreHeader();
709   // Ensure loop header logic is finite.
710   int64_t trip_count = 0;
711   if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
712     return false;
713   }
714   // Ensure there is only a single loop-body (besides the header).
715   HBasicBlock* body = nullptr;
716   for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
717     if (it.Current() != header) {
718       if (body != nullptr) {
719         return false;
720       }
721       body = it.Current();
722     }
723   }
724   CHECK(body != nullptr);
725   // Ensure there is only a single exit point.
726   if (header->GetSuccessors().size() != 2) {
727     return false;
728   }
729   HBasicBlock* exit = (header->GetSuccessors()[0] == body)
730       ? header->GetSuccessors()[1]
731       : header->GetSuccessors()[0];
732   // Ensure exit can only be reached by exiting loop.
733   if (exit->GetPredecessors().size() != 1) {
734     return false;
735   }
736   // Detect either an empty loop (no side effects other than plain iteration) or
737   // a trivial loop (just iterating once). Replace subsequent index uses, if any,
738   // with the last value and remove the loop, possibly after unrolling its body.
739   HPhi* main_phi = nullptr;
740   if (TrySetSimpleLoopHeader(header, &main_phi)) {
741     bool is_empty = IsEmptyBody(body);
742     if (reductions_->empty() &&  // TODO: possible with some effort
743         (is_empty || trip_count == 1) &&
744         TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
745       if (!is_empty) {
746         // Unroll the loop-body, which sees initial value of the index.
747         main_phi->ReplaceWith(main_phi->InputAt(0));
748         preheader->MergeInstructionsWith(body);
749       }
750       body->DisconnectAndDelete();
751       exit->RemovePredecessor(header);
752       header->RemoveSuccessor(exit);
753       header->RemoveDominatedBlock(exit);
754       header->DisconnectAndDelete();
755       preheader->AddSuccessor(exit);
756       preheader->AddInstruction(new (global_allocator_) HGoto());
757       preheader->AddDominatedBlock(exit);
758       exit->SetDominator(preheader);
759       RemoveLoop(node);  // update hierarchy
760       return true;
761     }
762   }
763   // Vectorize loop, if possible and valid.
764   if (kEnableVectorization &&
765       // Disable vectorization for debuggable graphs: this is a workaround for the bug
766       // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
767       // TODO: b/138601207, investigate other possible cases with wrong environment values and
768       // possibly switch back vectorization on for debuggable graphs.
769       !graph_->IsDebuggable() &&
770       TrySetSimpleLoopHeader(header, &main_phi) &&
771       ShouldVectorize(node, body, trip_count) &&
772       TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
773     Vectorize(node, body, exit, trip_count);
774     graph_->SetHasSIMD(true);  // flag SIMD usage
775     MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
776     return true;
777   }
778   return false;
779 }
780 
OptimizeInnerLoop(LoopNode * node)781 bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
782   return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
783 }
784 
785 
786 
787 //
788 // Scalar loop peeling and unrolling: generic part methods.
789 //
790 
TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo * analysis_info,bool generate_code)791 bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
792                                                               bool generate_code) {
793   if (analysis_info->GetNumberOfExits() > 1) {
794     return false;
795   }
796 
797   uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
798   if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
799     return false;
800   }
801 
802   if (generate_code) {
803     // TODO: support other unrolling factors.
804     DCHECK_EQ(unrolling_factor, 2u);
805 
806     // Perform unrolling.
807     HLoopInformation* loop_info = analysis_info->GetLoopInfo();
808     LoopClonerSimpleHelper helper(loop_info, &induction_range_);
809     helper.DoUnrolling();
810 
811     // Remove the redundant loop check after unrolling.
812     HIf* copy_hif =
813         helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
814     int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
815     copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
816   }
817   return true;
818 }
819 
TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo * analysis_info,bool generate_code)820 bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
821                                                                    bool generate_code) {
822   HLoopInformation* loop_info = analysis_info->GetLoopInfo();
823   if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
824     return false;
825   }
826 
827   if (analysis_info->GetNumberOfInvariantExits() == 0) {
828     return false;
829   }
830 
831   if (generate_code) {
832     // Perform peeling.
833     LoopClonerSimpleHelper helper(loop_info, &induction_range_);
834     helper.DoPeeling();
835 
836     // Statically evaluate loop check after peeling for loop invariant condition.
837     const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
838     for (auto entry : *hir_map) {
839       HInstruction* copy = entry.second;
840       if (copy->IsIf()) {
841         TryToEvaluateIfCondition(copy->AsIf(), graph_);
842       }
843     }
844   }
845 
846   return true;
847 }
848 
TryFullUnrolling(LoopAnalysisInfo * analysis_info,bool generate_code)849 bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
850   // Fully unroll loops with a known and small trip count.
851   int64_t trip_count = analysis_info->GetTripCount();
852   if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
853       trip_count == LoopAnalysisInfo::kUnknownTripCount ||
854       !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
855     return false;
856   }
857 
858   if (generate_code) {
859     // Peeling of the N first iterations (where N equals to the trip count) will effectively
860     // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
861     // preheader and the original loop. The trip count of this loop will be 0 as the sequential
862     // iterations are executed first and there are exactly N of them. Thus we can statically
863     // evaluate the loop exit condition to 'false' and fully eliminate it.
864     //
865     // Here is an example of full unrolling of a loop with a trip count 2:
866     //
867     //                                           loop_cond_1
868     //                                           loop_body_1        <- First iteration.
869     //                                               |
870     //                             \                 v
871     //                            ==\            loop_cond_2
872     //                            ==/            loop_body_2        <- Second iteration.
873     //                             /                 |
874     //               <-                              v     <-
875     //     loop_cond   \                         loop_cond   \      <- This cond is always false.
876     //     loop_body  _/                         loop_body  _/
877     //
878     HLoopInformation* loop_info = analysis_info->GetLoopInfo();
879     PeelByCount(loop_info, trip_count, &induction_range_);
880     HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
881     int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
882     loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
883   }
884 
885   return true;
886 }
887 
TryPeelingAndUnrolling(LoopNode * node)888 bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
889   HLoopInformation* loop_info = node->loop_info;
890   int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
891   LoopAnalysisInfo analysis_info(loop_info);
892   LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
893 
894   if (analysis_info.HasInstructionsPreventingScalarOpts() ||
895       arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
896     return false;
897   }
898 
899   if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
900       !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
901       !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
902     return false;
903   }
904 
905   // Run 'IsLoopClonable' the last as it might be time-consuming.
906   if (!LoopClonerHelper::IsLoopClonable(loop_info)) {
907     return false;
908   }
909 
910   return TryFullUnrolling(&analysis_info) ||
911          TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
912          TryUnrollingForBranchPenaltyReduction(&analysis_info);
913 }
914 
915 //
916 // Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
917 // "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
918 // Intel Press, June, 2004 (http://www.aartbik.com/).
919 //
920 
ShouldVectorize(LoopNode * node,HBasicBlock * block,int64_t trip_count)921 bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
922   // Reset vector bookkeeping.
923   vector_length_ = 0;
924   vector_refs_->clear();
925   vector_static_peeling_factor_ = 0;
926   vector_dynamic_peeling_candidate_ = nullptr;
927   vector_runtime_test_a_ =
928   vector_runtime_test_b_ = nullptr;
929 
930   // Phis in the loop-body prevent vectorization.
931   if (!block->GetPhis().IsEmpty()) {
932     return false;
933   }
934 
935   // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
936   // occurrence, which allows passing down attributes down the use tree.
937   for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
938     if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
939       return false;  // failure to vectorize a left-hand-side
940     }
941   }
942 
943   // Prepare alignment analysis:
944   // (1) find desired alignment (SIMD vector size in bytes).
945   // (2) initialize static loop peeling votes (peeling factor that will
946   //     make one particular reference aligned), never to exceed (1).
947   // (3) variable to record how many references share same alignment.
948   // (4) variable to record suitable candidate for dynamic loop peeling.
949   size_t desired_alignment = GetVectorSizeInBytes();
950   ScopedArenaVector<uint32_t> peeling_votes(desired_alignment, 0u,
951       loop_allocator_->Adapter(kArenaAllocLoopOptimization));
952 
953   uint32_t max_num_same_alignment = 0;
954   const ArrayReference* peeling_candidate = nullptr;
955 
956   // Data dependence analysis. Find each pair of references with same type, where
957   // at least one is a write. Each such pair denotes a possible data dependence.
958   // This analysis exploits the property that differently typed arrays cannot be
959   // aliased, as well as the property that references either point to the same
960   // array or to two completely disjoint arrays, i.e., no partial aliasing.
961   // Other than a few simply heuristics, no detailed subscript analysis is done.
962   // The scan over references also prepares finding a suitable alignment strategy.
963   for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
964     uint32_t num_same_alignment = 0;
965     // Scan over all next references.
966     for (auto j = i; ++j != vector_refs_->end(); ) {
967       if (i->type == j->type && (i->lhs || j->lhs)) {
968         // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
969         HInstruction* a = i->base;
970         HInstruction* b = j->base;
971         HInstruction* x = i->offset;
972         HInstruction* y = j->offset;
973         if (a == b) {
974           // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
975           // Conservatively assume a loop-carried data dependence otherwise, and reject.
976           if (x != y) {
977             return false;
978           }
979           // Count the number of references that have the same alignment (since
980           // base and offset are the same) and where at least one is a write, so
981           // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
982           num_same_alignment++;
983         } else {
984           // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
985           // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
986           // generating an explicit a != b disambiguation runtime test on the two references.
987           if (x != y) {
988             // To avoid excessive overhead, we only accept one a != b test.
989             if (vector_runtime_test_a_ == nullptr) {
990               // First test found.
991               vector_runtime_test_a_ = a;
992               vector_runtime_test_b_ = b;
993             } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
994                        (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
995               return false;  // second test would be needed
996             }
997           }
998         }
999       }
1000     }
1001     // Update information for finding suitable alignment strategy:
1002     // (1) update votes for static loop peeling,
1003     // (2) update suitable candidate for dynamic loop peeling.
1004     Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1005     if (alignment.Base() >= desired_alignment) {
1006       // If the array/string object has a known, sufficient alignment, use the
1007       // initial offset to compute the static loop peeling vote (this always
1008       // works, since elements have natural alignment).
1009       uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1010       uint32_t vote = (offset == 0)
1011           ? 0
1012           : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1013       DCHECK_LT(vote, 16u);
1014       ++peeling_votes[vote];
1015     } else if (BaseAlignment() >= desired_alignment &&
1016                num_same_alignment > max_num_same_alignment) {
1017       // Otherwise, if the array/string object has a known, sufficient alignment
1018       // for just the base but with an unknown offset, record the candidate with
1019       // the most occurrences for dynamic loop peeling (again, the peeling always
1020       // works, since elements have natural alignment).
1021       max_num_same_alignment = num_same_alignment;
1022       peeling_candidate = &(*i);
1023     }
1024   }  // for i
1025 
1026   if (!IsInPredicatedVectorizationMode()) {
1027     // Find a suitable alignment strategy.
1028     SetAlignmentStrategy(peeling_votes, peeling_candidate);
1029   }
1030 
1031   // Does vectorization seem profitable?
1032   if (!IsVectorizationProfitable(trip_count)) {
1033     return false;
1034   }
1035 
1036   // Success!
1037   return true;
1038 }
1039 
Vectorize(LoopNode * node,HBasicBlock * block,HBasicBlock * exit,int64_t trip_count)1040 void HLoopOptimization::Vectorize(LoopNode* node,
1041                                   HBasicBlock* block,
1042                                   HBasicBlock* exit,
1043                                   int64_t trip_count) {
1044   HBasicBlock* header = node->loop_info->GetHeader();
1045   HBasicBlock* preheader = node->loop_info->GetPreHeader();
1046 
1047   // Pick a loop unrolling factor for the vector loop.
1048   uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1049       block, trip_count, MaxNumberPeeled(), vector_length_);
1050   uint32_t chunk = vector_length_ * unroll;
1051 
1052   DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1053 
1054   // A cleanup loop is needed, at least, for any unknown trip count or
1055   // for a known trip count with remainder iterations after vectorization.
1056   bool needs_cleanup = !IsInPredicatedVectorizationMode() &&
1057       (trip_count == 0 || ((trip_count - vector_static_peeling_factor_) % chunk) != 0);
1058 
1059   // Adjust vector bookkeeping.
1060   HPhi* main_phi = nullptr;
1061   bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi);  // refills sets
1062   DCHECK(is_simple_loop_header);
1063   vector_header_ = header;
1064   vector_body_ = block;
1065 
1066   // Loop induction type.
1067   DataType::Type induc_type = main_phi->GetType();
1068   DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1069       << induc_type;
1070 
1071   // Generate the trip count for static or dynamic loop peeling, if needed:
1072   // ptc = <peeling factor>;
1073   HInstruction* ptc = nullptr;
1074   if (vector_static_peeling_factor_ != 0) {
1075     DCHECK(!IsInPredicatedVectorizationMode());
1076     // Static loop peeling for SIMD alignment (using the most suitable
1077     // fixed peeling factor found during prior alignment analysis).
1078     DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1079     ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1080   } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1081     DCHECK(!IsInPredicatedVectorizationMode());
1082     // Dynamic loop peeling for SIMD alignment (using the most suitable
1083     // candidate found during prior alignment analysis):
1084     // rem = offset % ALIGN;    // adjusted as #elements
1085     // ptc = rem == 0 ? 0 : (ALIGN - rem);
1086     uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1087     uint32_t align = GetVectorSizeInBytes() >> shift;
1088     uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1089                                           vector_dynamic_peeling_candidate_->is_string_char_at);
1090     HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1091     HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1092         induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1093     HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1094         induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1095     HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1096         induc_type, graph_->GetConstant(induc_type, align), rem));
1097     HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1098         rem, graph_->GetConstant(induc_type, 0)));
1099     ptc = Insert(preheader, new (global_allocator_) HSelect(
1100         cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1101     needs_cleanup = true;  // don't know the exact amount
1102   }
1103 
1104   // Generate loop control:
1105   // stc = <trip-count>;
1106   // ptc = min(stc, ptc);
1107   // vtc = stc - (stc - ptc) % chunk;
1108   // i = 0;
1109   HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1110   HInstruction* vtc = stc;
1111   if (needs_cleanup) {
1112     DCHECK(!IsInPredicatedVectorizationMode());
1113     DCHECK(IsPowerOfTwo(chunk));
1114     HInstruction* diff = stc;
1115     if (ptc != nullptr) {
1116       if (trip_count == 0) {
1117         HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1118         ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1119       }
1120       diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1121     }
1122     HInstruction* rem = Insert(
1123         preheader, new (global_allocator_) HAnd(induc_type,
1124                                                 diff,
1125                                                 graph_->GetConstant(induc_type, chunk - 1)));
1126     vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1127   }
1128   vector_index_ = graph_->GetConstant(induc_type, 0);
1129 
1130   // Generate runtime disambiguation test:
1131   // vtc = a != b ? vtc : 0;
1132   if (vector_runtime_test_a_ != nullptr) {
1133     HInstruction* rt = Insert(
1134         preheader,
1135         new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1136     vtc = Insert(preheader,
1137                  new (global_allocator_)
1138                  HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
1139     needs_cleanup = true;
1140   }
1141 
1142   // Generate alignment peeling loop, if needed:
1143   // for ( ; i < ptc; i += 1)
1144   //    <loop-body>
1145   //
1146   // NOTE: The alignment forced by the peeling loop is preserved even if data is
1147   //       moved around during suspend checks, since all analysis was based on
1148   //       nothing more than the Android runtime alignment conventions.
1149   if (ptc != nullptr) {
1150     DCHECK(!IsInPredicatedVectorizationMode());
1151     vector_mode_ = kSequential;
1152     GenerateNewLoop(node,
1153                     block,
1154                     graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1155                     vector_index_,
1156                     ptc,
1157                     graph_->GetConstant(induc_type, 1),
1158                     LoopAnalysisInfo::kNoUnrollingFactor);
1159   }
1160 
1161   // Generate vector loop, possibly further unrolled:
1162   // for ( ; i < vtc; i += chunk)
1163   //    <vectorized-loop-body>
1164   vector_mode_ = kVector;
1165   GenerateNewLoop(node,
1166                   block,
1167                   graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1168                   vector_index_,
1169                   vtc,
1170                   graph_->GetConstant(induc_type, vector_length_),  // increment per unroll
1171                   unroll);
1172   HLoopInformation* vloop = vector_header_->GetLoopInformation();
1173 
1174   // Generate cleanup loop, if needed:
1175   // for ( ; i < stc; i += 1)
1176   //    <loop-body>
1177   if (needs_cleanup) {
1178     DCHECK(!IsInPredicatedVectorizationMode() || vector_runtime_test_a_ != nullptr);
1179     vector_mode_ = kSequential;
1180     GenerateNewLoop(node,
1181                     block,
1182                     graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1183                     vector_index_,
1184                     stc,
1185                     graph_->GetConstant(induc_type, 1),
1186                     LoopAnalysisInfo::kNoUnrollingFactor);
1187   }
1188 
1189   // Link reductions to their final uses.
1190   for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1191     if (i->first->IsPhi()) {
1192       HInstruction* phi = i->first;
1193       HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1194       // Deal with regular uses.
1195       for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1196         induction_range_.Replace(use.GetUser(), phi, repl);  // update induction use
1197       }
1198       phi->ReplaceWith(repl);
1199     }
1200   }
1201 
1202   // Remove the original loop by disconnecting the body block
1203   // and removing all instructions from the header.
1204   block->DisconnectAndDelete();
1205   while (!header->GetFirstInstruction()->IsGoto()) {
1206     header->RemoveInstruction(header->GetFirstInstruction());
1207   }
1208 
1209   // Update loop hierarchy: the old header now resides in the same outer loop
1210   // as the old preheader. Note that we don't bother putting sequential
1211   // loops back in the hierarchy at this point.
1212   header->SetLoopInformation(preheader->GetLoopInformation());  // outward
1213   node->loop_info = vloop;
1214 }
1215 
GenerateNewLoop(LoopNode * node,HBasicBlock * block,HBasicBlock * new_preheader,HInstruction * lo,HInstruction * hi,HInstruction * step,uint32_t unroll)1216 void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1217                                         HBasicBlock* block,
1218                                         HBasicBlock* new_preheader,
1219                                         HInstruction* lo,
1220                                         HInstruction* hi,
1221                                         HInstruction* step,
1222                                         uint32_t unroll) {
1223   DCHECK(unroll == 1 || vector_mode_ == kVector);
1224   DataType::Type induc_type = lo->GetType();
1225   // Prepare new loop.
1226   vector_preheader_ = new_preheader,
1227   vector_header_ = vector_preheader_->GetSingleSuccessor();
1228   vector_body_ = vector_header_->GetSuccessors()[1];
1229   HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1230                                            kNoRegNumber,
1231                                            0,
1232                                            HPhi::ToPhiType(induc_type));
1233   // Generate header and prepare body.
1234   // for (i = lo; i < hi; i += step)
1235   //    <loop-body>
1236   HInstruction* cond = nullptr;
1237   HInstruction* set_pred = nullptr;
1238   if (IsInPredicatedVectorizationMode()) {
1239     HVecPredWhile* pred_while =
1240         new (global_allocator_) HVecPredWhile(global_allocator_,
1241                                               phi,
1242                                               hi,
1243                                               HVecPredWhile::CondKind::kLO,
1244                                               DataType::Type::kInt32,
1245                                               vector_length_,
1246                                               0u);
1247 
1248     cond = new (global_allocator_) HVecPredCondition(global_allocator_,
1249                                                      pred_while,
1250                                                      HVecPredCondition::PCondKind::kNFirst,
1251                                                      DataType::Type::kInt32,
1252                                                      vector_length_,
1253                                                      0u);
1254 
1255     vector_header_->AddPhi(phi);
1256     vector_header_->AddInstruction(pred_while);
1257     vector_header_->AddInstruction(cond);
1258     set_pred = pred_while;
1259   } else {
1260     cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1261     vector_header_->AddPhi(phi);
1262     vector_header_->AddInstruction(cond);
1263   }
1264 
1265   vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
1266   vector_index_ = phi;
1267   vector_permanent_map_->clear();  // preserved over unrolling
1268   for (uint32_t u = 0; u < unroll; u++) {
1269     // Generate instruction map.
1270     vector_map_->clear();
1271     for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1272       bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1273       DCHECK(vectorized_def);
1274     }
1275     // Generate body from the instruction map, but in original program order.
1276     HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1277     for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1278       auto i = vector_map_->find(it.Current());
1279       if (i != vector_map_->end() && !i->second->IsInBlock()) {
1280         Insert(vector_body_, i->second);
1281         if (IsInPredicatedVectorizationMode() && i->second->IsVecOperation()) {
1282           HVecOperation* op = i->second->AsVecOperation();
1283           op->SetMergingGoverningPredicate(set_pred);
1284         }
1285         // Deal with instructions that need an environment, such as the scalar intrinsics.
1286         if (i->second->NeedsEnvironment()) {
1287           i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1288         }
1289       }
1290     }
1291     // Generate the induction.
1292     vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1293     Insert(vector_body_, vector_index_);
1294   }
1295   // Finalize phi inputs for the reductions (if any).
1296   for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1297     if (!i->first->IsPhi()) {
1298       DCHECK(i->second->IsPhi());
1299       GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1300     }
1301   }
1302   // Finalize phi inputs for the loop index.
1303   phi->AddInput(lo);
1304   phi->AddInput(vector_index_);
1305   vector_index_ = phi;
1306 }
1307 
VectorizeDef(LoopNode * node,HInstruction * instruction,bool generate_code)1308 bool HLoopOptimization::VectorizeDef(LoopNode* node,
1309                                      HInstruction* instruction,
1310                                      bool generate_code) {
1311   // Accept a left-hand-side array base[index] for
1312   // (1) supported vector type,
1313   // (2) loop-invariant base,
1314   // (3) unit stride index,
1315   // (4) vectorizable right-hand-side value.
1316   uint64_t restrictions = kNone;
1317   // Don't accept expressions that can throw.
1318   if (instruction->CanThrow()) {
1319     return false;
1320   }
1321   if (instruction->IsArraySet()) {
1322     DataType::Type type = instruction->AsArraySet()->GetComponentType();
1323     HInstruction* base = instruction->InputAt(0);
1324     HInstruction* index = instruction->InputAt(1);
1325     HInstruction* value = instruction->InputAt(2);
1326     HInstruction* offset = nullptr;
1327     // For narrow types, explicit type conversion may have been
1328     // optimized way, so set the no hi bits restriction here.
1329     if (DataType::Size(type) <= 2) {
1330       restrictions |= kNoHiBits;
1331     }
1332     if (TrySetVectorType(type, &restrictions) &&
1333         node->loop_info->IsDefinedOutOfTheLoop(base) &&
1334         induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
1335         VectorizeUse(node, value, generate_code, type, restrictions)) {
1336       if (generate_code) {
1337         GenerateVecSub(index, offset);
1338         GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
1339       } else {
1340         vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1341       }
1342       return true;
1343     }
1344     return false;
1345   }
1346   // Accept a left-hand-side reduction for
1347   // (1) supported vector type,
1348   // (2) vectorizable right-hand-side value.
1349   auto redit = reductions_->find(instruction);
1350   if (redit != reductions_->end()) {
1351     DataType::Type type = instruction->GetType();
1352     // Recognize SAD idiom or direct reduction.
1353     if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1354         VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
1355         (TrySetVectorType(type, &restrictions) &&
1356          VectorizeUse(node, instruction, generate_code, type, restrictions))) {
1357       if (generate_code) {
1358         HInstruction* new_red = vector_map_->Get(instruction);
1359         vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1360         vector_permanent_map_->Overwrite(redit->second, new_red);
1361       }
1362       return true;
1363     }
1364     return false;
1365   }
1366   // Branch back okay.
1367   if (instruction->IsGoto()) {
1368     return true;
1369   }
1370   // Otherwise accept only expressions with no effects outside the immediate loop-body.
1371   // Note that actual uses are inspected during right-hand-side tree traversal.
1372   return !IsUsedOutsideLoop(node->loop_info, instruction)
1373          && !instruction->DoesAnyWrite();
1374 }
1375 
VectorizeUse(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type type,uint64_t restrictions)1376 bool HLoopOptimization::VectorizeUse(LoopNode* node,
1377                                      HInstruction* instruction,
1378                                      bool generate_code,
1379                                      DataType::Type type,
1380                                      uint64_t restrictions) {
1381   // Accept anything for which code has already been generated.
1382   if (generate_code) {
1383     if (vector_map_->find(instruction) != vector_map_->end()) {
1384       return true;
1385     }
1386   }
1387   // Continue the right-hand-side tree traversal, passing in proper
1388   // types and vector restrictions along the way. During code generation,
1389   // all new nodes are drawn from the global allocator.
1390   if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1391     // Accept invariant use, using scalar expansion.
1392     if (generate_code) {
1393       GenerateVecInv(instruction, type);
1394     }
1395     return true;
1396   } else if (instruction->IsArrayGet()) {
1397     // Deal with vector restrictions.
1398     bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1399 
1400     if (is_string_char_at && (HasVectorRestrictions(restrictions, kNoStringCharAt) ||
1401                               IsInPredicatedVectorizationMode())) {
1402       // TODO: Support CharAt for predicated mode.
1403       return false;
1404     }
1405     // Accept a right-hand-side array base[index] for
1406     // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
1407     // (2) loop-invariant base,
1408     // (3) unit stride index,
1409     // (4) vectorizable right-hand-side value.
1410     HInstruction* base = instruction->InputAt(0);
1411     HInstruction* index = instruction->InputAt(1);
1412     HInstruction* offset = nullptr;
1413     if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
1414         node->loop_info->IsDefinedOutOfTheLoop(base) &&
1415         induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
1416       if (generate_code) {
1417         GenerateVecSub(index, offset);
1418         GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
1419       } else {
1420         vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
1421       }
1422       return true;
1423     }
1424   } else if (instruction->IsPhi()) {
1425     // Accept particular phi operations.
1426     if (reductions_->find(instruction) != reductions_->end()) {
1427       // Deal with vector restrictions.
1428       if (HasVectorRestrictions(restrictions, kNoReduction)) {
1429         return false;
1430       }
1431       // Accept a reduction.
1432       if (generate_code) {
1433         GenerateVecReductionPhi(instruction->AsPhi());
1434       }
1435       return true;
1436     }
1437     // TODO: accept right-hand-side induction?
1438     return false;
1439   } else if (instruction->IsTypeConversion()) {
1440     // Accept particular type conversions.
1441     HTypeConversion* conversion = instruction->AsTypeConversion();
1442     HInstruction* opa = conversion->InputAt(0);
1443     DataType::Type from = conversion->GetInputType();
1444     DataType::Type to = conversion->GetResultType();
1445     if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
1446       uint32_t size_vec = DataType::Size(type);
1447       uint32_t size_from = DataType::Size(from);
1448       uint32_t size_to = DataType::Size(to);
1449       // Accept an integral conversion
1450       // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1451       // (1b) widening from at least vector type, and
1452       // (2) vectorizable operand.
1453       if ((size_to < size_from &&
1454            size_to == size_vec &&
1455            VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1456           (size_to >= size_from &&
1457            size_from >= size_vec &&
1458            VectorizeUse(node, opa, generate_code, type, restrictions))) {
1459         if (generate_code) {
1460           if (vector_mode_ == kVector) {
1461             vector_map_->Put(instruction, vector_map_->Get(opa));  // operand pass-through
1462           } else {
1463             GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1464           }
1465         }
1466         return true;
1467       }
1468     } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
1469       DCHECK_EQ(to, type);
1470       // Accept int to float conversion for
1471       // (1) supported int,
1472       // (2) vectorizable operand.
1473       if (TrySetVectorType(from, &restrictions) &&
1474           VectorizeUse(node, opa, generate_code, from, restrictions)) {
1475         if (generate_code) {
1476           GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1477         }
1478         return true;
1479       }
1480     }
1481     return false;
1482   } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1483     // Accept unary operator for vectorizable operand.
1484     HInstruction* opa = instruction->InputAt(0);
1485     if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1486       if (generate_code) {
1487         GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1488       }
1489       return true;
1490     }
1491   } else if (instruction->IsAdd() || instruction->IsSub() ||
1492              instruction->IsMul() || instruction->IsDiv() ||
1493              instruction->IsAnd() || instruction->IsOr()  || instruction->IsXor()) {
1494     // Deal with vector restrictions.
1495     if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1496         (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1497       return false;
1498     }
1499     // Accept binary operator for vectorizable operands.
1500     HInstruction* opa = instruction->InputAt(0);
1501     HInstruction* opb = instruction->InputAt(1);
1502     if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1503         VectorizeUse(node, opb, generate_code, type, restrictions)) {
1504       if (generate_code) {
1505         GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1506       }
1507       return true;
1508     }
1509   } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
1510     // Recognize halving add idiom.
1511     if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1512       return true;
1513     }
1514     // Deal with vector restrictions.
1515     HInstruction* opa = instruction->InputAt(0);
1516     HInstruction* opb = instruction->InputAt(1);
1517     HInstruction* r = opa;
1518     bool is_unsigned = false;
1519     if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1520         (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1521       return false;  // unsupported instruction
1522     } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1523       // Shifts right need extra care to account for higher order bits.
1524       // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1525       if (instruction->IsShr() &&
1526           (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1527         return false;  // reject, unless all operands are sign-extension narrower
1528       } else if (instruction->IsUShr() &&
1529                  (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1530         return false;  // reject, unless all operands are zero-extension narrower
1531       }
1532     }
1533     // Accept shift operator for vectorizable/invariant operands.
1534     // TODO: accept symbolic, albeit loop invariant shift factors.
1535     DCHECK(r != nullptr);
1536     if (generate_code && vector_mode_ != kVector) {  // de-idiom
1537       r = opa;
1538     }
1539     int64_t distance = 0;
1540     if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1541         IsInt64AndGet(opb, /*out*/ &distance)) {
1542       // Restrict shift distance to packed data type width.
1543       int64_t max_distance = DataType::Size(type) * 8;
1544       if (0 <= distance && distance < max_distance) {
1545         if (generate_code) {
1546           GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
1547         }
1548         return true;
1549       }
1550     }
1551   } else if (instruction->IsAbs()) {
1552     // Deal with vector restrictions.
1553     HInstruction* opa = instruction->InputAt(0);
1554     HInstruction* r = opa;
1555     bool is_unsigned = false;
1556     if (HasVectorRestrictions(restrictions, kNoAbs)) {
1557       return false;
1558     } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1559                (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1560       return false;  // reject, unless operand is sign-extension narrower
1561     }
1562     // Accept ABS(x) for vectorizable operand.
1563     DCHECK(r != nullptr);
1564     if (generate_code && vector_mode_ != kVector) {  // de-idiom
1565       r = opa;
1566     }
1567     if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1568       if (generate_code) {
1569         GenerateVecOp(instruction,
1570                       vector_map_->Get(r),
1571                       nullptr,
1572                       HVecOperation::ToProperType(type, is_unsigned));
1573       }
1574       return true;
1575     }
1576   }
1577   return false;
1578 }
1579 
GetVectorSizeInBytes()1580 uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1581   return simd_register_size_;
1582 }
1583 
TrySetVectorType(DataType::Type type,uint64_t * restrictions)1584 bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
1585   const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1586   switch (compiler_options_->GetInstructionSet()) {
1587     case InstructionSet::kArm:
1588     case InstructionSet::kThumb2:
1589       // Allow vectorization for all ARM devices, because Android assumes that
1590       // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
1591       switch (type) {
1592         case DataType::Type::kBool:
1593         case DataType::Type::kUint8:
1594         case DataType::Type::kInt8:
1595           *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
1596           return TrySetVectorLength(type, 8);
1597         case DataType::Type::kUint16:
1598         case DataType::Type::kInt16:
1599           *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
1600           return TrySetVectorLength(type, 4);
1601         case DataType::Type::kInt32:
1602           *restrictions |= kNoDiv | kNoWideSAD;
1603           return TrySetVectorLength(type, 2);
1604         default:
1605           break;
1606       }
1607       return false;
1608     case InstructionSet::kArm64:
1609       if (IsInPredicatedVectorizationMode()) {
1610         // SVE vectorization.
1611         CHECK(features->AsArm64InstructionSetFeatures()->HasSVE());
1612         size_t vector_length = simd_register_size_ / DataType::Size(type);
1613         DCHECK_EQ(simd_register_size_ % DataType::Size(type), 0u);
1614         switch (type) {
1615           case DataType::Type::kBool:
1616           case DataType::Type::kUint8:
1617           case DataType::Type::kInt8:
1618             *restrictions |= kNoDiv |
1619                              kNoSignedHAdd |
1620                              kNoUnsignedHAdd |
1621                              kNoUnroundedHAdd |
1622                              kNoSAD;
1623             return TrySetVectorLength(type, vector_length);
1624           case DataType::Type::kUint16:
1625           case DataType::Type::kInt16:
1626             *restrictions |= kNoDiv |
1627                              kNoSignedHAdd |
1628                              kNoUnsignedHAdd |
1629                              kNoUnroundedHAdd |
1630                              kNoSAD |
1631                              kNoDotProd;
1632             return TrySetVectorLength(type, vector_length);
1633           case DataType::Type::kInt32:
1634             *restrictions |= kNoDiv | kNoSAD;
1635             return TrySetVectorLength(type, vector_length);
1636           case DataType::Type::kInt64:
1637             *restrictions |= kNoDiv | kNoSAD;
1638             return TrySetVectorLength(type, vector_length);
1639           case DataType::Type::kFloat32:
1640             *restrictions |= kNoReduction;
1641             return TrySetVectorLength(type, vector_length);
1642           case DataType::Type::kFloat64:
1643             *restrictions |= kNoReduction;
1644             return TrySetVectorLength(type, vector_length);
1645           default:
1646             break;
1647         }
1648         return false;
1649       } else {
1650         // Allow vectorization for all ARM devices, because Android assumes that
1651         // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
1652         switch (type) {
1653           case DataType::Type::kBool:
1654           case DataType::Type::kUint8:
1655           case DataType::Type::kInt8:
1656             *restrictions |= kNoDiv;
1657             return TrySetVectorLength(type, 16);
1658           case DataType::Type::kUint16:
1659           case DataType::Type::kInt16:
1660             *restrictions |= kNoDiv;
1661             return TrySetVectorLength(type, 8);
1662           case DataType::Type::kInt32:
1663             *restrictions |= kNoDiv;
1664             return TrySetVectorLength(type, 4);
1665           case DataType::Type::kInt64:
1666             *restrictions |= kNoDiv | kNoMul;
1667             return TrySetVectorLength(type, 2);
1668           case DataType::Type::kFloat32:
1669             *restrictions |= kNoReduction;
1670             return TrySetVectorLength(type, 4);
1671           case DataType::Type::kFloat64:
1672             *restrictions |= kNoReduction;
1673             return TrySetVectorLength(type, 2);
1674           default:
1675             break;
1676         }
1677         return false;
1678       }
1679     case InstructionSet::kX86:
1680     case InstructionSet::kX86_64:
1681       // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
1682       if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1683         switch (type) {
1684           case DataType::Type::kBool:
1685           case DataType::Type::kUint8:
1686           case DataType::Type::kInt8:
1687             *restrictions |= kNoMul |
1688                              kNoDiv |
1689                              kNoShift |
1690                              kNoAbs |
1691                              kNoSignedHAdd |
1692                              kNoUnroundedHAdd |
1693                              kNoSAD |
1694                              kNoDotProd;
1695             return TrySetVectorLength(type, 16);
1696           case DataType::Type::kUint16:
1697             *restrictions |= kNoDiv |
1698                              kNoAbs |
1699                              kNoSignedHAdd |
1700                              kNoUnroundedHAdd |
1701                              kNoSAD |
1702                              kNoDotProd;
1703             return TrySetVectorLength(type, 8);
1704           case DataType::Type::kInt16:
1705             *restrictions |= kNoDiv |
1706                              kNoAbs |
1707                              kNoSignedHAdd |
1708                              kNoUnroundedHAdd |
1709                              kNoSAD;
1710             return TrySetVectorLength(type, 8);
1711           case DataType::Type::kInt32:
1712             *restrictions |= kNoDiv | kNoSAD;
1713             return TrySetVectorLength(type, 4);
1714           case DataType::Type::kInt64:
1715             *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
1716             return TrySetVectorLength(type, 2);
1717           case DataType::Type::kFloat32:
1718             *restrictions |= kNoReduction;
1719             return TrySetVectorLength(type, 4);
1720           case DataType::Type::kFloat64:
1721             *restrictions |= kNoReduction;
1722             return TrySetVectorLength(type, 2);
1723           default:
1724             break;
1725         }  // switch type
1726       }
1727       return false;
1728     default:
1729       return false;
1730   }  // switch instruction set
1731 }
1732 
TrySetVectorLengthImpl(uint32_t length)1733 bool HLoopOptimization::TrySetVectorLengthImpl(uint32_t length) {
1734   DCHECK(IsPowerOfTwo(length) && length >= 2u);
1735   // First time set?
1736   if (vector_length_ == 0) {
1737     vector_length_ = length;
1738   }
1739   // Different types are acceptable within a loop-body, as long as all the corresponding vector
1740   // lengths match exactly to obtain a uniform traversal through the vector iteration space
1741   // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1742   return vector_length_ == length;
1743 }
1744 
GenerateVecInv(HInstruction * org,DataType::Type type)1745 void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
1746   if (vector_map_->find(org) == vector_map_->end()) {
1747     // In scalar code, just use a self pass-through for scalar invariants
1748     // (viz. expression remains itself).
1749     if (vector_mode_ == kSequential) {
1750       vector_map_->Put(org, org);
1751       return;
1752     }
1753     // In vector code, explicit scalar expansion is needed.
1754     HInstruction* vector = nullptr;
1755     auto it = vector_permanent_map_->find(org);
1756     if (it != vector_permanent_map_->end()) {
1757       vector = it->second;  // reuse during unrolling
1758     } else {
1759       // Generates ReplicateScalar( (optional_type_conv) org ).
1760       HInstruction* input = org;
1761       DataType::Type input_type = input->GetType();
1762       if (type != input_type && (type == DataType::Type::kInt64 ||
1763                                  input_type == DataType::Type::kInt64)) {
1764         input = Insert(vector_preheader_,
1765                        new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1766       }
1767       vector = new (global_allocator_)
1768           HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
1769       vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1770       if (IsInPredicatedVectorizationMode()) {
1771         HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1772                                                                           graph_->GetIntConstant(1),
1773                                                                           type,
1774                                                                           vector_length_,
1775                                                                           0u);
1776         vector_preheader_->InsertInstructionBefore(set_pred, vector);
1777         vector->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1778       }
1779     }
1780     vector_map_->Put(org, vector);
1781   }
1782 }
1783 
GenerateVecSub(HInstruction * org,HInstruction * offset)1784 void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1785   if (vector_map_->find(org) == vector_map_->end()) {
1786     HInstruction* subscript = vector_index_;
1787     int64_t value = 0;
1788     if (!IsInt64AndGet(offset, &value) || value != 0) {
1789       subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
1790       if (org->IsPhi()) {
1791         Insert(vector_body_, subscript);  // lacks layout placeholder
1792       }
1793     }
1794     vector_map_->Put(org, subscript);
1795   }
1796 }
1797 
GenerateVecMem(HInstruction * org,HInstruction * opa,HInstruction * opb,HInstruction * offset,DataType::Type type)1798 void HLoopOptimization::GenerateVecMem(HInstruction* org,
1799                                        HInstruction* opa,
1800                                        HInstruction* opb,
1801                                        HInstruction* offset,
1802                                        DataType::Type type) {
1803   uint32_t dex_pc = org->GetDexPc();
1804   HInstruction* vector = nullptr;
1805   if (vector_mode_ == kVector) {
1806     // Vector store or load.
1807     bool is_string_char_at = false;
1808     HInstruction* base = org->InputAt(0);
1809     if (opb != nullptr) {
1810       vector = new (global_allocator_) HVecStore(
1811           global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
1812     } else  {
1813       is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1814       vector = new (global_allocator_) HVecLoad(global_allocator_,
1815                                                 base,
1816                                                 opa,
1817                                                 type,
1818                                                 org->GetSideEffects(),
1819                                                 vector_length_,
1820                                                 is_string_char_at,
1821                                                 dex_pc);
1822     }
1823     // Known (forced/adjusted/original) alignment?
1824     if (vector_dynamic_peeling_candidate_ != nullptr) {
1825       if (vector_dynamic_peeling_candidate_->offset == offset &&  // TODO: diffs too?
1826           DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1827           vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1828         vector->AsVecMemoryOperation()->SetAlignment(  // forced
1829             Alignment(GetVectorSizeInBytes(), 0));
1830       }
1831     } else {
1832       vector->AsVecMemoryOperation()->SetAlignment(  // adjusted/original
1833           ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
1834     }
1835   } else {
1836     // Scalar store or load.
1837     DCHECK(vector_mode_ == kSequential);
1838     if (opb != nullptr) {
1839       DataType::Type component_type = org->AsArraySet()->GetComponentType();
1840       vector = new (global_allocator_) HArraySet(
1841           org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
1842     } else  {
1843       bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1844       vector = new (global_allocator_) HArrayGet(
1845           org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
1846     }
1847   }
1848   vector_map_->Put(org, vector);
1849 }
1850 
GenerateVecReductionPhi(HPhi * phi)1851 void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1852   DCHECK(reductions_->find(phi) != reductions_->end());
1853   DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1854   HInstruction* vector = nullptr;
1855   if (vector_mode_ == kSequential) {
1856     HPhi* new_phi = new (global_allocator_) HPhi(
1857         global_allocator_, kNoRegNumber, 0, phi->GetType());
1858     vector_header_->AddPhi(new_phi);
1859     vector = new_phi;
1860   } else {
1861     // Link vector reduction back to prior unrolled update, or a first phi.
1862     auto it = vector_permanent_map_->find(phi);
1863     if (it != vector_permanent_map_->end()) {
1864       vector = it->second;
1865     } else {
1866       HPhi* new_phi = new (global_allocator_) HPhi(
1867           global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1868       vector_header_->AddPhi(new_phi);
1869       vector = new_phi;
1870     }
1871   }
1872   vector_map_->Put(phi, vector);
1873 }
1874 
GenerateVecReductionPhiInputs(HPhi * phi,HInstruction * reduction)1875 void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1876   HInstruction* new_phi = vector_map_->Get(phi);
1877   HInstruction* new_init = reductions_->Get(phi);
1878   HInstruction* new_red = vector_map_->Get(reduction);
1879   // Link unrolled vector loop back to new phi.
1880   for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1881     DCHECK(new_phi->IsVecOperation());
1882   }
1883   // Prepare the new initialization.
1884   if (vector_mode_ == kVector) {
1885     // Generate a [initial, 0, .., 0] vector for add or
1886     // a [initial, initial, .., initial] vector for min/max.
1887     HVecOperation* red_vector = new_red->AsVecOperation();
1888     HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
1889     uint32_t vector_length = red_vector->GetVectorLength();
1890     DataType::Type type = red_vector->GetPackedType();
1891     if (kind == HVecReduce::ReductionKind::kSum) {
1892       new_init = Insert(vector_preheader_,
1893                         new (global_allocator_) HVecSetScalars(global_allocator_,
1894                                                                &new_init,
1895                                                                type,
1896                                                                vector_length,
1897                                                                1,
1898                                                                kNoDexPc));
1899     } else {
1900       new_init = Insert(vector_preheader_,
1901                         new (global_allocator_) HVecReplicateScalar(global_allocator_,
1902                                                                     new_init,
1903                                                                     type,
1904                                                                     vector_length,
1905                                                                     kNoDexPc));
1906     }
1907     if (IsInPredicatedVectorizationMode()) {
1908       HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1909                                                                         graph_->GetIntConstant(1),
1910                                                                         type,
1911                                                                         vector_length,
1912                                                                         0u);
1913       vector_preheader_->InsertInstructionBefore(set_pred, new_init);
1914       new_init->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1915     }
1916   } else {
1917     new_init = ReduceAndExtractIfNeeded(new_init);
1918   }
1919   // Set the phi inputs.
1920   DCHECK(new_phi->IsPhi());
1921   new_phi->AsPhi()->AddInput(new_init);
1922   new_phi->AsPhi()->AddInput(new_red);
1923   // New feed value for next phi (safe mutation in iteration).
1924   reductions_->find(phi)->second = new_phi;
1925 }
1926 
ReduceAndExtractIfNeeded(HInstruction * instruction)1927 HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1928   if (instruction->IsPhi()) {
1929     HInstruction* input = instruction->InputAt(1);
1930     if (HVecOperation::ReturnsSIMDValue(input)) {
1931       DCHECK(!input->IsPhi());
1932       HVecOperation* input_vector = input->AsVecOperation();
1933       uint32_t vector_length = input_vector->GetVectorLength();
1934       DataType::Type type = input_vector->GetPackedType();
1935       HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
1936       HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1937       // Generate a vector reduction and scalar extract
1938       //    x = REDUCE( [x_1, .., x_n] )
1939       //    y = x_1
1940       // along the exit of the defining loop.
1941       HInstruction* reduce = new (global_allocator_) HVecReduce(
1942           global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
1943       exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1944       instruction = new (global_allocator_) HVecExtractScalar(
1945           global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
1946       exit->InsertInstructionAfter(instruction, reduce);
1947 
1948       if (IsInPredicatedVectorizationMode()) {
1949         HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1950                                                                           graph_->GetIntConstant(1),
1951                                                                           type,
1952                                                                           vector_length,
1953                                                                           0u);
1954         exit->InsertInstructionBefore(set_pred, reduce);
1955         reduce->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1956         instruction->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1957       }
1958     }
1959   }
1960   return instruction;
1961 }
1962 
1963 #define GENERATE_VEC(x, y) \
1964   if (vector_mode_ == kVector) { \
1965     vector = (x); \
1966   } else { \
1967     DCHECK(vector_mode_ == kSequential); \
1968     vector = (y); \
1969   } \
1970   break;
1971 
GenerateVecOp(HInstruction * org,HInstruction * opa,HInstruction * opb,DataType::Type type)1972 void HLoopOptimization::GenerateVecOp(HInstruction* org,
1973                                       HInstruction* opa,
1974                                       HInstruction* opb,
1975                                       DataType::Type type) {
1976   uint32_t dex_pc = org->GetDexPc();
1977   HInstruction* vector = nullptr;
1978   DataType::Type org_type = org->GetType();
1979   switch (org->GetKind()) {
1980     case HInstruction::kNeg:
1981       DCHECK(opb == nullptr);
1982       GENERATE_VEC(
1983         new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1984         new (global_allocator_) HNeg(org_type, opa, dex_pc));
1985     case HInstruction::kNot:
1986       DCHECK(opb == nullptr);
1987       GENERATE_VEC(
1988         new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1989         new (global_allocator_) HNot(org_type, opa, dex_pc));
1990     case HInstruction::kBooleanNot:
1991       DCHECK(opb == nullptr);
1992       GENERATE_VEC(
1993         new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1994         new (global_allocator_) HBooleanNot(opa, dex_pc));
1995     case HInstruction::kTypeConversion:
1996       DCHECK(opb == nullptr);
1997       GENERATE_VEC(
1998         new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1999         new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
2000     case HInstruction::kAdd:
2001       GENERATE_VEC(
2002         new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2003         new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
2004     case HInstruction::kSub:
2005       GENERATE_VEC(
2006         new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2007         new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
2008     case HInstruction::kMul:
2009       GENERATE_VEC(
2010         new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2011         new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
2012     case HInstruction::kDiv:
2013       GENERATE_VEC(
2014         new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2015         new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
2016     case HInstruction::kAnd:
2017       GENERATE_VEC(
2018         new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2019         new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
2020     case HInstruction::kOr:
2021       GENERATE_VEC(
2022         new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2023         new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
2024     case HInstruction::kXor:
2025       GENERATE_VEC(
2026         new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2027         new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
2028     case HInstruction::kShl:
2029       GENERATE_VEC(
2030         new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2031         new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
2032     case HInstruction::kShr:
2033       GENERATE_VEC(
2034         new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2035         new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
2036     case HInstruction::kUShr:
2037       GENERATE_VEC(
2038         new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2039         new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
2040     case HInstruction::kAbs:
2041       DCHECK(opb == nullptr);
2042       GENERATE_VEC(
2043         new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2044         new (global_allocator_) HAbs(org_type, opa, dex_pc));
2045     default:
2046       break;
2047   }  // switch
2048   CHECK(vector != nullptr) << "Unsupported SIMD operator";
2049   vector_map_->Put(org, vector);
2050 }
2051 
2052 #undef GENERATE_VEC
2053 
2054 //
2055 // Vectorization idioms.
2056 //
2057 
2058 // Method recognizes the following idioms:
2059 //   rounding  halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2060 //   truncated halving add (a + b)     >> 1 for unsigned/signed operands a, b
2061 // Provided that the operands are promoted to a wider form to do the arithmetic and
2062 // then cast back to narrower form, the idioms can be mapped into efficient SIMD
2063 // implementation that operates directly in narrower form (plus one extra bit).
2064 // TODO: current version recognizes implicit byte/short/char widening only;
2065 //       explicit widening from int to long could be added later.
VectorizeHalvingAddIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type type,uint64_t restrictions)2066 bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2067                                                  HInstruction* instruction,
2068                                                  bool generate_code,
2069                                                  DataType::Type type,
2070                                                  uint64_t restrictions) {
2071   // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
2072   // (note whether the sign bit in wider precision is shifted in has no effect
2073   // on the narrow precision computed by the idiom).
2074   if ((instruction->IsShr() ||
2075        instruction->IsUShr()) &&
2076       IsInt64Value(instruction->InputAt(1), 1)) {
2077     // Test for (a + b + c) >> 1 for optional constant c.
2078     HInstruction* a = nullptr;
2079     HInstruction* b = nullptr;
2080     int64_t       c = 0;
2081     if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
2082       // Accept c == 1 (rounded) or c == 0 (not rounded).
2083       bool is_rounded = false;
2084       if (c == 1) {
2085         is_rounded = true;
2086       } else if (c != 0) {
2087         return false;
2088       }
2089       // Accept consistent zero or sign extension on operands a and b.
2090       HInstruction* r = nullptr;
2091       HInstruction* s = nullptr;
2092       bool is_unsigned = false;
2093       if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
2094         return false;
2095       }
2096       // Deal with vector restrictions.
2097       if ((is_unsigned && HasVectorRestrictions(restrictions, kNoUnsignedHAdd)) ||
2098           (!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2099           (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2100         return false;
2101       }
2102       // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2103       // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
2104       DCHECK(r != nullptr && s != nullptr);
2105       if (generate_code && vector_mode_ != kVector) {  // de-idiom
2106         r = instruction->InputAt(0);
2107         s = instruction->InputAt(1);
2108       }
2109       if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2110           VectorizeUse(node, s, generate_code, type, restrictions)) {
2111         if (generate_code) {
2112           if (vector_mode_ == kVector) {
2113             vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2114                 global_allocator_,
2115                 vector_map_->Get(r),
2116                 vector_map_->Get(s),
2117                 HVecOperation::ToProperType(type, is_unsigned),
2118                 vector_length_,
2119                 is_rounded,
2120                 kNoDexPc));
2121             MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2122           } else {
2123             GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2124           }
2125         }
2126         return true;
2127       }
2128     }
2129   }
2130   return false;
2131 }
2132 
2133 // Method recognizes the following idiom:
2134 //   q += ABS(a - b) for signed operands a, b
2135 // Provided that the operands have the same type or are promoted to a wider form.
2136 // Since this may involve a vector length change, the idiom is handled by going directly
2137 // to a sad-accumulate node (rather than relying combining finer grained nodes later).
2138 // TODO: unsigned SAD too?
VectorizeSADIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type reduction_type,uint64_t restrictions)2139 bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2140                                           HInstruction* instruction,
2141                                           bool generate_code,
2142                                           DataType::Type reduction_type,
2143                                           uint64_t restrictions) {
2144   // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2145   // are done in the same precision (either int or long).
2146   if (!instruction->IsAdd() ||
2147       (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
2148     return false;
2149   }
2150   HInstruction* acc = instruction->InputAt(0);
2151   HInstruction* abs = instruction->InputAt(1);
2152   HInstruction* a = nullptr;
2153   HInstruction* b = nullptr;
2154   if (abs->IsAbs() &&
2155       abs->GetType() == reduction_type &&
2156       IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2157     DCHECK(a != nullptr && b != nullptr);
2158   } else {
2159     return false;
2160   }
2161   // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2162   // The same-type or narrower operands are called r (a or lower) and s (b or lower).
2163   // We inspect the operands carefully to pick the most suited type.
2164   HInstruction* r = a;
2165   HInstruction* s = b;
2166   bool is_unsigned = false;
2167   DataType::Type sub_type = GetNarrowerType(a, b);
2168   if (reduction_type != sub_type &&
2169       (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2170     return false;
2171   }
2172   // Try same/narrower type and deal with vector restrictions.
2173   if (!TrySetVectorType(sub_type, &restrictions) ||
2174       HasVectorRestrictions(restrictions, kNoSAD) ||
2175       (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
2176     return false;
2177   }
2178   // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2179   // idiomatic operation. Sequential code uses the original scalar expressions.
2180   DCHECK(r != nullptr && s != nullptr);
2181   if (generate_code && vector_mode_ != kVector) {  // de-idiom
2182     r = s = abs->InputAt(0);
2183   }
2184   if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
2185       VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2186       VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2187     if (generate_code) {
2188       if (vector_mode_ == kVector) {
2189         vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2190             global_allocator_,
2191             vector_map_->Get(acc),
2192             vector_map_->Get(r),
2193             vector_map_->Get(s),
2194             HVecOperation::ToProperType(reduction_type, is_unsigned),
2195             GetOtherVL(reduction_type, sub_type, vector_length_),
2196             kNoDexPc));
2197         MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2198       } else {
2199         // "GenerateVecOp()" must not be called more than once for each original loop body
2200         // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2201         // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2202         // has not yet been processed.
2203         if (vector_map_->find(abs) == vector_map_->end()) {
2204           GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2205         }
2206         GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
2207       }
2208     }
2209     return true;
2210   }
2211   return false;
2212 }
2213 
2214 // Method recognises the following dot product idiom:
2215 //   q += a * b for operands a, b whose type is narrower than the reduction one.
2216 // Provided that the operands have the same type or are promoted to a wider form.
2217 // Since this may involve a vector length change, the idiom is handled by going directly
2218 // to a dot product node (rather than relying combining finer grained nodes later).
VectorizeDotProdIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type reduction_type,uint64_t restrictions)2219 bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2220                                               HInstruction* instruction,
2221                                               bool generate_code,
2222                                               DataType::Type reduction_type,
2223                                               uint64_t restrictions) {
2224   if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
2225     return false;
2226   }
2227 
2228   HInstruction* const acc = instruction->InputAt(0);
2229   HInstruction* const mul = instruction->InputAt(1);
2230   if (!mul->IsMul() || mul->GetType() != reduction_type) {
2231     return false;
2232   }
2233 
2234   HInstruction* const mul_left = mul->InputAt(0);
2235   HInstruction* const mul_right = mul->InputAt(1);
2236   HInstruction* r = mul_left;
2237   HInstruction* s = mul_right;
2238   DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
2239   bool is_unsigned = false;
2240 
2241   if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
2242     return false;
2243   }
2244   op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2245 
2246   if (!TrySetVectorType(op_type, &restrictions) ||
2247       HasVectorRestrictions(restrictions, kNoDotProd)) {
2248     return false;
2249   }
2250 
2251   DCHECK(r != nullptr && s != nullptr);
2252   // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2253   // idiomatic operation. Sequential code uses the original scalar expressions.
2254   if (generate_code && vector_mode_ != kVector) {  // de-idiom
2255     r = mul_left;
2256     s = mul_right;
2257   }
2258   if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
2259       VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2260       VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2261     if (generate_code) {
2262       if (vector_mode_ == kVector) {
2263         vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2264             global_allocator_,
2265             vector_map_->Get(acc),
2266             vector_map_->Get(r),
2267             vector_map_->Get(s),
2268             reduction_type,
2269             is_unsigned,
2270             GetOtherVL(reduction_type, op_type, vector_length_),
2271             kNoDexPc));
2272         MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2273       } else {
2274         // "GenerateVecOp()" must not be called more than once for each original loop body
2275         // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2276         // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2277         // has not yet been processed.
2278         if (vector_map_->find(mul) == vector_map_->end()) {
2279           GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2280         }
2281         GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
2282       }
2283     }
2284     return true;
2285   }
2286   return false;
2287 }
2288 
2289 //
2290 // Vectorization heuristics.
2291 //
2292 
ComputeAlignment(HInstruction * offset,DataType::Type type,bool is_string_char_at,uint32_t peeling)2293 Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2294                                               DataType::Type type,
2295                                               bool is_string_char_at,
2296                                               uint32_t peeling) {
2297   // Combine the alignment and hidden offset that is guaranteed by
2298   // the Android runtime with a known starting index adjusted as bytes.
2299   int64_t value = 0;
2300   if (IsInt64AndGet(offset, /*out*/ &value)) {
2301     uint32_t start_offset =
2302         HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2303     return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2304   }
2305   // Otherwise, the Android runtime guarantees at least natural alignment.
2306   return Alignment(DataType::Size(type), 0);
2307 }
2308 
SetAlignmentStrategy(const ScopedArenaVector<uint32_t> & peeling_votes,const ArrayReference * peeling_candidate)2309 void HLoopOptimization::SetAlignmentStrategy(const ScopedArenaVector<uint32_t>& peeling_votes,
2310                                              const ArrayReference* peeling_candidate) {
2311   // Current heuristic: pick the best static loop peeling factor, if any,
2312   // or otherwise use dynamic loop peeling on suggested peeling candidate.
2313   uint32_t max_vote = 0;
2314   for (size_t i = 0; i < peeling_votes.size(); i++) {
2315     if (peeling_votes[i] > max_vote) {
2316       max_vote = peeling_votes[i];
2317       vector_static_peeling_factor_ = i;
2318     }
2319   }
2320   if (max_vote == 0) {
2321     vector_dynamic_peeling_candidate_ = peeling_candidate;
2322   }
2323 }
2324 
MaxNumberPeeled()2325 uint32_t HLoopOptimization::MaxNumberPeeled() {
2326   if (vector_dynamic_peeling_candidate_ != nullptr) {
2327     return vector_length_ - 1u;  // worst-case
2328   }
2329   return vector_static_peeling_factor_;  // known exactly
2330 }
2331 
IsVectorizationProfitable(int64_t trip_count)2332 bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
2333   // Current heuristic: non-empty body with sufficient number of iterations (if known).
2334   // TODO: refine by looking at e.g. operation count, alignment, etc.
2335   // TODO: trip count is really unsigned entity, provided the guarding test
2336   //       is satisfied; deal with this more carefully later
2337   uint32_t max_peel = MaxNumberPeeled();
2338   if (vector_length_ == 0) {
2339     return false;  // nothing found
2340   } else if (trip_count < 0) {
2341     return false;  // guard against non-taken/large
2342   } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
2343     return false;  // insufficient iterations
2344   }
2345   return true;
2346 }
2347 
2348 //
2349 // Helpers.
2350 //
2351 
TrySetPhiInduction(HPhi * phi,bool restrict_uses)2352 bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
2353   // Start with empty phi induction.
2354   iset_->clear();
2355 
2356   // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2357   // smart enough to follow strongly connected components (and it's probably not worth
2358   // it to make it so). See b/33775412.
2359   if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2360     return false;
2361   }
2362 
2363   // Lookup phi induction cycle.
2364   ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2365   if (set != nullptr) {
2366     for (HInstruction* i : *set) {
2367       // Check that, other than instructions that are no longer in the graph (removed earlier)
2368       // each instruction is removable and, when restrict uses are requested, other than for phi,
2369       // all uses are contained within the cycle.
2370       if (!i->IsInBlock()) {
2371         continue;
2372       } else if (!i->IsRemovable()) {
2373         return false;
2374       } else if (i != phi && restrict_uses) {
2375         // Deal with regular uses.
2376         for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2377           if (set->find(use.GetUser()) == set->end()) {
2378             return false;
2379           }
2380         }
2381       }
2382       iset_->insert(i);  // copy
2383     }
2384     return true;
2385   }
2386   return false;
2387 }
2388 
TrySetPhiReduction(HPhi * phi)2389 bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
2390   DCHECK(iset_->empty());
2391   // Only unclassified phi cycles are candidates for reductions.
2392   if (induction_range_.IsClassified(phi)) {
2393     return false;
2394   }
2395   // Accept operations like x = x + .., provided that the phi and the reduction are
2396   // used exactly once inside the loop, and by each other.
2397   HInputsRef inputs = phi->GetInputs();
2398   if (inputs.size() == 2) {
2399     HInstruction* reduction = inputs[1];
2400     if (HasReductionFormat(reduction, phi)) {
2401       HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2402       uint32_t use_count = 0;
2403       bool single_use_inside_loop =
2404           // Reduction update only used by phi.
2405           reduction->GetUses().HasExactlyOneElement() &&
2406           !reduction->HasEnvironmentUses() &&
2407           // Reduction update is only use of phi inside the loop.
2408           IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2409           iset_->size() == 1;
2410       iset_->clear();  // leave the way you found it
2411       if (single_use_inside_loop) {
2412         // Link reduction back, and start recording feed value.
2413         reductions_->Put(reduction, phi);
2414         reductions_->Put(phi, phi->InputAt(0));
2415         return true;
2416       }
2417     }
2418   }
2419   return false;
2420 }
2421 
TrySetSimpleLoopHeader(HBasicBlock * block,HPhi ** main_phi)2422 bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2423   // Start with empty phi induction and reductions.
2424   iset_->clear();
2425   reductions_->clear();
2426 
2427   // Scan the phis to find the following (the induction structure has already
2428   // been optimized, so we don't need to worry about trivial cases):
2429   // (1) optional reductions in loop,
2430   // (2) the main induction, used in loop control.
2431   HPhi* phi = nullptr;
2432   for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2433     if (TrySetPhiReduction(it.Current()->AsPhi())) {
2434       continue;
2435     } else if (phi == nullptr) {
2436       // Found the first candidate for main induction.
2437       phi = it.Current()->AsPhi();
2438     } else {
2439       return false;
2440     }
2441   }
2442 
2443   // Then test for a typical loopheader:
2444   //   s:  SuspendCheck
2445   //   c:  Condition(phi, bound)
2446   //   i:  If(c)
2447   if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
2448     HInstruction* s = block->GetFirstInstruction();
2449     if (s != nullptr && s->IsSuspendCheck()) {
2450       HInstruction* c = s->GetNext();
2451       if (c != nullptr &&
2452           c->IsCondition() &&
2453           c->GetUses().HasExactlyOneElement() &&  // only used for termination
2454           !c->HasEnvironmentUses()) {  // unlikely, but not impossible
2455         HInstruction* i = c->GetNext();
2456         if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2457           iset_->insert(c);
2458           iset_->insert(s);
2459           *main_phi = phi;
2460           return true;
2461         }
2462       }
2463     }
2464   }
2465   return false;
2466 }
2467 
IsEmptyBody(HBasicBlock * block)2468 bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
2469   if (!block->GetPhis().IsEmpty()) {
2470     return false;
2471   }
2472   for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2473     HInstruction* instruction = it.Current();
2474     if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2475       return false;
2476     }
2477   }
2478   return true;
2479 }
2480 
IsUsedOutsideLoop(HLoopInformation * loop_info,HInstruction * instruction)2481 bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2482                                           HInstruction* instruction) {
2483   // Deal with regular uses.
2484   for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2485     if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2486       return true;
2487     }
2488   }
2489   return false;
2490 }
2491 
IsOnlyUsedAfterLoop(HLoopInformation * loop_info,HInstruction * instruction,bool collect_loop_uses,uint32_t * use_count)2492 bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
2493                                             HInstruction* instruction,
2494                                             bool collect_loop_uses,
2495                                             /*out*/ uint32_t* use_count) {
2496   // Deal with regular uses.
2497   for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2498     HInstruction* user = use.GetUser();
2499     if (iset_->find(user) == iset_->end()) {  // not excluded?
2500       HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2501       if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
2502         // If collect_loop_uses is set, simply keep adding those uses to the set.
2503         // Otherwise, reject uses inside the loop that were not already in the set.
2504         if (collect_loop_uses) {
2505           iset_->insert(user);
2506           continue;
2507         }
2508         return false;
2509       }
2510       ++*use_count;
2511     }
2512   }
2513   return true;
2514 }
2515 
TryReplaceWithLastValue(HLoopInformation * loop_info,HInstruction * instruction,HBasicBlock * block)2516 bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2517                                                 HInstruction* instruction,
2518                                                 HBasicBlock* block) {
2519   // Try to replace outside uses with the last value.
2520   if (induction_range_.CanGenerateLastValue(instruction)) {
2521     HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
2522     // Deal with regular uses.
2523     const HUseList<HInstruction*>& uses = instruction->GetUses();
2524     for (auto it = uses.begin(), end = uses.end(); it != end;) {
2525       HInstruction* user = it->GetUser();
2526       size_t index = it->GetIndex();
2527       ++it;  // increment before replacing
2528       if (iset_->find(user) == iset_->end()) {  // not excluded?
2529         if (kIsDebugBuild) {
2530           // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2531           HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2532           CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2533         }
2534         user->ReplaceInput(replacement, index);
2535         induction_range_.Replace(user, instruction, replacement);  // update induction
2536       }
2537     }
2538     // Deal with environment uses.
2539     const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2540     for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2541       HEnvironment* user = it->GetUser();
2542       size_t index = it->GetIndex();
2543       ++it;  // increment before replacing
2544       if (iset_->find(user->GetHolder()) == iset_->end()) {  // not excluded?
2545         // Only update environment uses after the loop.
2546         HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
2547         if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2548           user->RemoveAsUserOfInput(index);
2549           user->SetRawEnvAt(index, replacement);
2550           replacement->AddEnvUseAt(user, index);
2551         }
2552       }
2553     }
2554     return true;
2555   }
2556   return false;
2557 }
2558 
TryAssignLastValue(HLoopInformation * loop_info,HInstruction * instruction,HBasicBlock * block,bool collect_loop_uses)2559 bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2560                                            HInstruction* instruction,
2561                                            HBasicBlock* block,
2562                                            bool collect_loop_uses) {
2563   // Assigning the last value is always successful if there are no uses.
2564   // Otherwise, it succeeds in a no early-exit loop by generating the
2565   // proper last value assignment.
2566   uint32_t use_count = 0;
2567   return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2568       (use_count == 0 ||
2569        (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
2570 }
2571 
RemoveDeadInstructions(const HInstructionList & list)2572 void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2573   for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2574     HInstruction* instruction = i.Current();
2575     if (instruction->IsDeadAndRemovable()) {
2576       simplified_ = true;
2577       instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2578     }
2579   }
2580 }
2581 
CanRemoveCycle()2582 bool HLoopOptimization::CanRemoveCycle() {
2583   for (HInstruction* i : *iset_) {
2584     // We can never remove instructions that have environment
2585     // uses when we compile 'debuggable'.
2586     if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2587       return false;
2588     }
2589     // A deoptimization should never have an environment input removed.
2590     for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2591       if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2592         return false;
2593       }
2594     }
2595   }
2596   return true;
2597 }
2598 
2599 }  // namespace art
2600