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 HIDDEN {
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 at the end of the block, with safe checks.
Insert(HBasicBlock * block,HInstruction * instruction)370 inline 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 // Returns whether the loop is of a diamond structure:
457 //
458 // header <----------------+
459 // | |
460 // diamond_hif |
461 // / \ |
462 // diamond_true diamond_false |
463 // \ / |
464 // back_edge |
465 // | |
466 // +---------------------+
HasLoopDiamondStructure(HLoopInformation * loop_info)467 static bool HasLoopDiamondStructure(HLoopInformation* loop_info) {
468 HBasicBlock* header = loop_info->GetHeader();
469 if (loop_info->NumberOfBackEdges() != 1 || header->GetSuccessors().size() != 2) {
470 return false;
471 }
472 HBasicBlock* header_succ_0 = header->GetSuccessors()[0];
473 HBasicBlock* header_succ_1 = header->GetSuccessors()[1];
474 HBasicBlock* diamond_top = loop_info->Contains(*header_succ_0) ?
475 header_succ_0 :
476 header_succ_1;
477 if (!diamond_top->GetLastInstruction()->IsIf()) {
478 return false;
479 }
480
481 HIf* diamond_hif = diamond_top->GetLastInstruction()->AsIf();
482 HBasicBlock* diamond_true = diamond_hif->IfTrueSuccessor();
483 HBasicBlock* diamond_false = diamond_hif->IfFalseSuccessor();
484
485 if (diamond_true->GetSuccessors().size() != 1 || diamond_false->GetSuccessors().size() != 1) {
486 return false;
487 }
488
489 HBasicBlock* back_edge = diamond_true->GetSingleSuccessor();
490 if (back_edge != diamond_false->GetSingleSuccessor() ||
491 back_edge != loop_info->GetBackEdges()[0]) {
492 return false;
493 }
494
495 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 5u);
496 return true;
497 }
498
IsPredicatedLoopControlFlowSupported(HLoopInformation * loop_info)499 static bool IsPredicatedLoopControlFlowSupported(HLoopInformation* loop_info) {
500 size_t num_of_blocks = loop_info->GetBlocks().NumSetBits();
501 return num_of_blocks == 2 || HasLoopDiamondStructure(loop_info);
502 }
503
504 //
505 // Public methods.
506 //
507
HLoopOptimization(HGraph * graph,const CodeGenerator & codegen,HInductionVarAnalysis * induction_analysis,OptimizingCompilerStats * stats,const char * name)508 HLoopOptimization::HLoopOptimization(HGraph* graph,
509 const CodeGenerator& codegen,
510 HInductionVarAnalysis* induction_analysis,
511 OptimizingCompilerStats* stats,
512 const char* name)
513 : HOptimization(graph, name, stats),
514 compiler_options_(&codegen.GetCompilerOptions()),
515 simd_register_size_(codegen.GetSIMDRegisterWidth()),
516 induction_range_(induction_analysis),
517 loop_allocator_(nullptr),
518 global_allocator_(graph_->GetAllocator()),
519 top_loop_(nullptr),
520 last_loop_(nullptr),
521 iset_(nullptr),
522 reductions_(nullptr),
523 simplified_(false),
524 predicated_vectorization_mode_(codegen.SupportsPredicatedSIMD()),
525 vector_length_(0),
526 vector_refs_(nullptr),
527 vector_static_peeling_factor_(0),
528 vector_dynamic_peeling_candidate_(nullptr),
529 vector_runtime_test_a_(nullptr),
530 vector_runtime_test_b_(nullptr),
531 vector_map_(nullptr),
532 vector_permanent_map_(nullptr),
533 vector_external_set_(nullptr),
534 predicate_info_map_(nullptr),
535 synthesis_mode_(LoopSynthesisMode::kSequential),
536 vector_preheader_(nullptr),
537 vector_header_(nullptr),
538 vector_body_(nullptr),
539 vector_index_(nullptr),
540 arch_loop_helper_(ArchNoOptsLoopHelper::Create(codegen, global_allocator_)) {}
541
Run()542 bool HLoopOptimization::Run() {
543 // Skip if there is no loop or the graph has irreducible loops.
544 // TODO: make this less of a sledgehammer.
545 if (!graph_->HasLoops() || graph_->HasIrreducibleLoops()) {
546 return false;
547 }
548
549 // Phase-local allocator.
550 ScopedArenaAllocator allocator(graph_->GetArenaStack());
551 loop_allocator_ = &allocator;
552
553 // Perform loop optimizations.
554 const bool did_loop_opt = LocalRun();
555 if (top_loop_ == nullptr) {
556 graph_->SetHasLoops(false); // no more loops
557 }
558
559 // Detach allocator.
560 loop_allocator_ = nullptr;
561
562 return did_loop_opt;
563 }
564
565 //
566 // Loop setup and traversal.
567 //
568
LocalRun()569 bool HLoopOptimization::LocalRun() {
570 // Build the linear order using the phase-local allocator. This step enables building
571 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
572 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
573 LinearizeGraph(graph_, &linear_order);
574
575 // Build the loop hierarchy.
576 for (HBasicBlock* block : linear_order) {
577 if (block->IsLoopHeader()) {
578 AddLoop(block->GetLoopInformation());
579 }
580 }
581 DCHECK(top_loop_ != nullptr);
582
583 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
584 // temporary data structures using the phase-local allocator. All new HIR
585 // should use the global allocator.
586 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
587 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
588 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
589 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
590 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
591 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
592 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
593 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
594 ScopedArenaSet<HInstruction*> ext_set(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
595 ScopedArenaSafeMap<HBasicBlock*, BlockPredicateInfo*> pred(
596 std::less<HBasicBlock*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
597 // Attach.
598 iset_ = &iset;
599 reductions_ = &reds;
600 vector_refs_ = &refs;
601 vector_map_ = ↦
602 vector_permanent_map_ = &perm;
603 vector_external_set_ = &ext_set;
604 predicate_info_map_ = &pred;
605 // Traverse.
606 const bool did_loop_opt = TraverseLoopsInnerToOuter(top_loop_);
607 // Detach.
608 iset_ = nullptr;
609 reductions_ = nullptr;
610 vector_refs_ = nullptr;
611 vector_map_ = nullptr;
612 vector_permanent_map_ = nullptr;
613 vector_external_set_ = nullptr;
614 predicate_info_map_ = nullptr;
615
616 return did_loop_opt;
617 }
618
AddLoop(HLoopInformation * loop_info)619 void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
620 DCHECK(loop_info != nullptr);
621 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
622 if (last_loop_ == nullptr) {
623 // First loop.
624 DCHECK(top_loop_ == nullptr);
625 last_loop_ = top_loop_ = node;
626 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
627 // Inner loop.
628 node->outer = last_loop_;
629 DCHECK(last_loop_->inner == nullptr);
630 last_loop_ = last_loop_->inner = node;
631 } else {
632 // Subsequent loop.
633 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
634 last_loop_ = last_loop_->outer;
635 }
636 node->outer = last_loop_->outer;
637 node->previous = last_loop_;
638 DCHECK(last_loop_->next == nullptr);
639 last_loop_ = last_loop_->next = node;
640 }
641 }
642
RemoveLoop(LoopNode * node)643 void HLoopOptimization::RemoveLoop(LoopNode* node) {
644 DCHECK(node != nullptr);
645 DCHECK(node->inner == nullptr);
646 if (node->previous != nullptr) {
647 // Within sequence.
648 node->previous->next = node->next;
649 if (node->next != nullptr) {
650 node->next->previous = node->previous;
651 }
652 } else {
653 // First of sequence.
654 if (node->outer != nullptr) {
655 node->outer->inner = node->next;
656 } else {
657 top_loop_ = node->next;
658 }
659 if (node->next != nullptr) {
660 node->next->outer = node->outer;
661 node->next->previous = nullptr;
662 }
663 }
664 }
665
TraverseLoopsInnerToOuter(LoopNode * node)666 bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
667 bool changed = false;
668 for ( ; node != nullptr; node = node->next) {
669 // Visit inner loops first. Recompute induction information for this
670 // loop if the induction of any inner loop has changed.
671 if (TraverseLoopsInnerToOuter(node->inner)) {
672 induction_range_.ReVisit(node->loop_info);
673 changed = true;
674 }
675
676 CalculateAndSetTryCatchKind(node);
677 if (node->try_catch_kind == LoopNode::TryCatchKind::kHasTryCatch) {
678 // The current optimizations assume that the loops do not contain try/catches.
679 // TODO(solanes, 227283906): Assess if we can modify them to work with try/catches.
680 continue;
681 }
682
683 DCHECK(node->try_catch_kind == LoopNode::TryCatchKind::kNoTryCatch)
684 << "kind: " << static_cast<int>(node->try_catch_kind)
685 << ". LoopOptimization requires the loops to not have try catches.";
686
687 // Repeat simplifications in the loop-body until no more changes occur.
688 // Note that since each simplification consists of eliminating code (without
689 // introducing new code), this process is always finite.
690 do {
691 simplified_ = false;
692 SimplifyInduction(node);
693 SimplifyBlocks(node);
694 changed = simplified_ || changed;
695 } while (simplified_);
696 // Optimize inner loop.
697 if (node->inner == nullptr) {
698 changed = OptimizeInnerLoop(node) || changed;
699 }
700 }
701 return changed;
702 }
703
CalculateAndSetTryCatchKind(LoopNode * node)704 void HLoopOptimization::CalculateAndSetTryCatchKind(LoopNode* node) {
705 DCHECK(node != nullptr);
706 DCHECK(node->try_catch_kind == LoopNode::TryCatchKind::kUnknown)
707 << "kind: " << static_cast<int>(node->try_catch_kind)
708 << ". SetTryCatchKind should be called only once per LoopNode.";
709
710 // If a inner loop has a try catch, then the outer loop has one too (as it contains `inner`).
711 // Knowing this, we could skip iterating through all of the outer loop's parents with a simple
712 // check.
713 for (LoopNode* inner = node->inner; inner != nullptr; inner = inner->next) {
714 DCHECK(inner->try_catch_kind != LoopNode::TryCatchKind::kUnknown)
715 << "kind: " << static_cast<int>(inner->try_catch_kind)
716 << ". Should have updated the inner loop before the outer loop.";
717
718 if (inner->try_catch_kind == LoopNode::TryCatchKind::kHasTryCatch) {
719 node->try_catch_kind = LoopNode::TryCatchKind::kHasTryCatch;
720 return;
721 }
722 }
723
724 for (HBlocksInLoopIterator it_loop(*node->loop_info); !it_loop.Done(); it_loop.Advance()) {
725 HBasicBlock* block = it_loop.Current();
726 if (block->GetTryCatchInformation() != nullptr) {
727 node->try_catch_kind = LoopNode::TryCatchKind::kHasTryCatch;
728 return;
729 }
730 }
731
732 node->try_catch_kind = LoopNode::TryCatchKind::kNoTryCatch;
733 }
734
735 //
736 // This optimization applies to loops with plain simple operations
737 // (I.e. no calls to java code or runtime) with a known small trip_count * instr_count
738 // value.
739 //
TryToRemoveSuspendCheckFromLoopHeader(LoopAnalysisInfo * analysis_info,bool generate_code)740 bool HLoopOptimization::TryToRemoveSuspendCheckFromLoopHeader(LoopAnalysisInfo* analysis_info,
741 bool generate_code) {
742 if (!graph_->SuspendChecksAreAllowedToNoOp()) {
743 return false;
744 }
745
746 int64_t trip_count = analysis_info->GetTripCount();
747
748 if (trip_count == LoopAnalysisInfo::kUnknownTripCount) {
749 return false;
750 }
751
752 int64_t instruction_count = analysis_info->GetNumberOfInstructions();
753 int64_t total_instruction_count = trip_count * instruction_count;
754
755 // The inclusion of the HasInstructionsPreventingScalarOpts() prevents this
756 // optimization from being applied to loops that have calls.
757 bool can_optimize =
758 total_instruction_count <= HLoopOptimization::kMaxTotalInstRemoveSuspendCheck &&
759 !analysis_info->HasInstructionsPreventingScalarOpts();
760
761 if (!can_optimize) {
762 return false;
763 }
764
765 // If we should do the optimization, disable codegen for the SuspendCheck.
766 if (generate_code) {
767 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
768 HBasicBlock* header = loop_info->GetHeader();
769 HSuspendCheck* instruction = header->GetLoopInformation()->GetSuspendCheck();
770 // As other optimizations depend on SuspendCheck
771 // (e.g: CHAGuardVisitor::HoistGuard), disable its codegen instead of
772 // removing the SuspendCheck instruction.
773 instruction->SetIsNoOp(true);
774 }
775
776 return true;
777 }
778
779 //
780 // Optimization.
781 //
782
SimplifyInduction(LoopNode * node)783 void HLoopOptimization::SimplifyInduction(LoopNode* node) {
784 HBasicBlock* header = node->loop_info->GetHeader();
785 HBasicBlock* preheader = node->loop_info->GetPreHeader();
786 // Scan the phis in the header to find opportunities to simplify an induction
787 // cycle that is only used outside the loop. Replace these uses, if any, with
788 // the last value and remove the induction cycle.
789 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
790 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
791 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
792 HPhi* phi = it.Current()->AsPhi();
793 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
794 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
795 // Note that it's ok to have replaced uses after the loop with the last value, without
796 // being able to remove the cycle. Environment uses (which are the reason we may not be
797 // able to remove the cycle) within the loop will still hold the right value. We must
798 // have tried first, however, to replace outside uses.
799 if (CanRemoveCycle()) {
800 simplified_ = true;
801 for (HInstruction* i : *iset_) {
802 RemoveFromCycle(i);
803 }
804 DCHECK(CheckInductionSetFullyRemoved(iset_));
805 }
806 }
807 }
808 }
809
SimplifyBlocks(LoopNode * node)810 void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
811 // Iterate over all basic blocks in the loop-body.
812 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
813 HBasicBlock* block = it.Current();
814 // Remove dead instructions from the loop-body.
815 RemoveDeadInstructions(block->GetPhis());
816 RemoveDeadInstructions(block->GetInstructions());
817 // Remove trivial control flow blocks from the loop-body.
818 if (block->GetPredecessors().size() == 1 &&
819 block->GetSuccessors().size() == 1 &&
820 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
821 simplified_ = true;
822 block->MergeWith(block->GetSingleSuccessor());
823 } else if (block->GetSuccessors().size() == 2) {
824 // Trivial if block can be bypassed to either branch.
825 HBasicBlock* succ0 = block->GetSuccessors()[0];
826 HBasicBlock* succ1 = block->GetSuccessors()[1];
827 HBasicBlock* meet0 = nullptr;
828 HBasicBlock* meet1 = nullptr;
829 if (succ0 != succ1 &&
830 IsGotoBlock(succ0, &meet0) &&
831 IsGotoBlock(succ1, &meet1) &&
832 meet0 == meet1 && // meets again
833 meet0 != block && // no self-loop
834 meet0->GetPhis().IsEmpty()) { // not used for merging
835 simplified_ = true;
836 succ0->DisconnectAndDelete();
837 if (block->Dominates(meet0)) {
838 block->RemoveDominatedBlock(meet0);
839 succ1->AddDominatedBlock(meet0);
840 meet0->SetDominator(succ1);
841 }
842 }
843 }
844 }
845 }
846
847 // Checks whether the loop has exit structure suitable for InnerLoopFinite optimization:
848 // - has single loop exit.
849 // - the exit block has only single predecessor - a block inside the loop.
850 //
851 // In that case returns single exit basic block (outside the loop); otherwise nullptr.
GetInnerLoopFiniteSingleExit(HLoopInformation * loop_info)852 static HBasicBlock* GetInnerLoopFiniteSingleExit(HLoopInformation* loop_info) {
853 HBasicBlock* exit = nullptr;
854 for (HBlocksInLoopIterator block_it(*loop_info);
855 !block_it.Done();
856 block_it.Advance()) {
857 HBasicBlock* block = block_it.Current();
858
859 // Check whether one of the successor is loop exit.
860 for (HBasicBlock* successor : block->GetSuccessors()) {
861 if (!loop_info->Contains(*successor)) {
862 if (exit != nullptr) {
863 // The loop has more than one exit.
864 return nullptr;
865 }
866 exit = successor;
867
868 // Ensure exit can only be reached by exiting loop.
869 if (successor->GetPredecessors().size() != 1) {
870 return nullptr;
871 }
872 }
873 }
874 }
875 return exit;
876 }
877
878 // Determines whether predicated loop vectorization should be tried for ALL loops.
879 #ifdef ART_FORCE_TRY_PREDICATED_SIMD
880 static constexpr bool kForceTryPredicatedSIMD = true;
881 #else
882 static constexpr bool kForceTryPredicatedSIMD = false;
883 #endif
884
TryOptimizeInnerLoopFinite(LoopNode * node)885 bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
886 HBasicBlock* header = node->loop_info->GetHeader();
887 HBasicBlock* preheader = node->loop_info->GetPreHeader();
888 // Ensure loop header logic is finite.
889 int64_t trip_count = 0;
890 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
891 return false;
892 }
893 // Check loop exits.
894 HBasicBlock* exit = GetInnerLoopFiniteSingleExit(node->loop_info);
895 if (exit == nullptr) {
896 return false;
897 }
898
899 HBasicBlock* body = (header->GetSuccessors()[0] == exit)
900 ? header->GetSuccessors()[1]
901 : header->GetSuccessors()[0];
902 // Detect either an empty loop (no side effects other than plain iteration) or
903 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
904 // with the last value and remove the loop, possibly after unrolling its body.
905 HPhi* main_phi = nullptr;
906 size_t num_of_blocks = header->GetLoopInformation()->GetBlocks().NumSetBits();
907
908 if (num_of_blocks == 2 && TrySetSimpleLoopHeader(header, &main_phi)) {
909 bool is_empty = IsEmptyBody(body);
910 if (reductions_->empty() && // TODO: possible with some effort
911 (is_empty || trip_count == 1) &&
912 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
913 if (!is_empty) {
914 // Unroll the loop-body, which sees initial value of the index.
915 main_phi->ReplaceWith(main_phi->InputAt(0));
916 preheader->MergeInstructionsWith(body);
917 }
918 body->DisconnectAndDelete();
919 exit->RemovePredecessor(header);
920 header->RemoveSuccessor(exit);
921 header->RemoveDominatedBlock(exit);
922 header->DisconnectAndDelete();
923 preheader->AddSuccessor(exit);
924 preheader->AddInstruction(new (global_allocator_) HGoto());
925 preheader->AddDominatedBlock(exit);
926 exit->SetDominator(preheader);
927 RemoveLoop(node); // update hierarchy
928 return true;
929 }
930 }
931 // Vectorize loop, if possible and valid.
932 if (!kEnableVectorization ||
933 // Disable vectorization for debuggable graphs: this is a workaround for the bug
934 // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
935 // TODO: b/138601207, investigate other possible cases with wrong environment values and
936 // possibly switch back vectorization on for debuggable graphs.
937 graph_->IsDebuggable()) {
938 return false;
939 }
940
941 if (kForceTryPredicatedSIMD && IsInPredicatedVectorizationMode()) {
942 return TryVectorizePredicated(node, body, exit, main_phi, trip_count);
943 } else {
944 return TryVectorizedTraditional(node, body, exit, main_phi, trip_count);
945 }
946 }
947
TryVectorizePredicated(LoopNode * node,HBasicBlock * body,HBasicBlock * exit,HPhi * main_phi,int64_t trip_count)948 bool HLoopOptimization::TryVectorizePredicated(LoopNode* node,
949 HBasicBlock* body,
950 HBasicBlock* exit,
951 HPhi* main_phi,
952 int64_t trip_count) {
953 if (!IsPredicatedLoopControlFlowSupported(node->loop_info) ||
954 !ShouldVectorizeCommon(node, main_phi, trip_count)) {
955 return false;
956 }
957
958 // Currently we can only generate cleanup loops for loops with 2 basic block.
959 //
960 // TODO: Support array disambiguation tests for CF loops.
961 if (NeedsArrayRefsDisambiguationTest() &&
962 node->loop_info->GetBlocks().NumSetBits() != 2) {
963 return false;
964 }
965
966 VectorizePredicated(node, body, exit);
967 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
968 graph_->SetHasPredicatedSIMD(true); // flag SIMD usage
969 return true;
970 }
971
TryVectorizedTraditional(LoopNode * node,HBasicBlock * body,HBasicBlock * exit,HPhi * main_phi,int64_t trip_count)972 bool HLoopOptimization::TryVectorizedTraditional(LoopNode* node,
973 HBasicBlock* body,
974 HBasicBlock* exit,
975 HPhi* main_phi,
976 int64_t trip_count) {
977 HBasicBlock* header = node->loop_info->GetHeader();
978 size_t num_of_blocks = header->GetLoopInformation()->GetBlocks().NumSetBits();
979
980 if (num_of_blocks != 2 || !ShouldVectorizeCommon(node, main_phi, trip_count)) {
981 return false;
982 }
983 VectorizeTraditional(node, body, exit, trip_count);
984 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
985 graph_->SetHasTraditionalSIMD(true); // flag SIMD usage
986 return true;
987 }
988
OptimizeInnerLoop(LoopNode * node)989 bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
990 return TryOptimizeInnerLoopFinite(node) || TryLoopScalarOpts(node);
991 }
992
993 //
994 // Scalar loop peeling and unrolling: generic part methods.
995 //
996
TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo * analysis_info,bool generate_code)997 bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
998 bool generate_code) {
999 if (analysis_info->GetNumberOfExits() > 1) {
1000 return false;
1001 }
1002
1003 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
1004 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
1005 return false;
1006 }
1007
1008 if (generate_code) {
1009 // TODO: support other unrolling factors.
1010 DCHECK_EQ(unrolling_factor, 2u);
1011
1012 // Perform unrolling.
1013 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
1014 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
1015 helper.DoUnrolling();
1016
1017 // Remove the redundant loop check after unrolling.
1018 HIf* copy_hif =
1019 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
1020 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
1021 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
1022 }
1023 return true;
1024 }
1025
TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo * analysis_info,bool generate_code)1026 bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
1027 bool generate_code) {
1028 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
1029 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
1030 return false;
1031 }
1032
1033 if (analysis_info->GetNumberOfInvariantExits() == 0) {
1034 return false;
1035 }
1036
1037 if (generate_code) {
1038 // Perform peeling.
1039 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
1040 helper.DoPeeling();
1041
1042 // Statically evaluate loop check after peeling for loop invariant condition.
1043 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
1044 for (auto entry : *hir_map) {
1045 HInstruction* copy = entry.second;
1046 if (copy->IsIf()) {
1047 TryToEvaluateIfCondition(copy->AsIf(), graph_);
1048 }
1049 }
1050 }
1051
1052 return true;
1053 }
1054
TryFullUnrolling(LoopAnalysisInfo * analysis_info,bool generate_code)1055 bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
1056 // Fully unroll loops with a known and small trip count.
1057 int64_t trip_count = analysis_info->GetTripCount();
1058 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
1059 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
1060 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
1061 return false;
1062 }
1063
1064 if (generate_code) {
1065 // Peeling of the N first iterations (where N equals to the trip count) will effectively
1066 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
1067 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
1068 // iterations are executed first and there are exactly N of them. Thus we can statically
1069 // evaluate the loop exit condition to 'false' and fully eliminate it.
1070 //
1071 // Here is an example of full unrolling of a loop with a trip count 2:
1072 //
1073 // loop_cond_1
1074 // loop_body_1 <- First iteration.
1075 // |
1076 // \ v
1077 // ==\ loop_cond_2
1078 // ==/ loop_body_2 <- Second iteration.
1079 // / |
1080 // <- v <-
1081 // loop_cond \ loop_cond \ <- This cond is always false.
1082 // loop_body _/ loop_body _/
1083 //
1084 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
1085 PeelByCount(loop_info, trip_count, &induction_range_);
1086 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
1087 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
1088 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
1089 }
1090
1091 return true;
1092 }
1093
TryLoopScalarOpts(LoopNode * node)1094 bool HLoopOptimization::TryLoopScalarOpts(LoopNode* node) {
1095 HLoopInformation* loop_info = node->loop_info;
1096 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
1097 LoopAnalysisInfo analysis_info(loop_info);
1098 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
1099
1100 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
1101 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
1102 return false;
1103 }
1104
1105 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
1106 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
1107 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false) &&
1108 !TryToRemoveSuspendCheckFromLoopHeader(&analysis_info, /*generate_code*/ false)) {
1109 return false;
1110 }
1111
1112 // Try the suspend check removal even for non-clonable loops. Also this
1113 // optimization doesn't interfere with other scalar loop optimizations so it can
1114 // be done prior to them.
1115 bool removed_suspend_check = TryToRemoveSuspendCheckFromLoopHeader(&analysis_info);
1116
1117 // Run 'IsLoopClonable' the last as it might be time-consuming.
1118 if (!LoopClonerHelper::IsLoopClonable(loop_info)) {
1119 return false;
1120 }
1121
1122 return TryFullUnrolling(&analysis_info) ||
1123 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
1124 TryUnrollingForBranchPenaltyReduction(&analysis_info) || removed_suspend_check;
1125 }
1126
1127 //
1128 // Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
1129 // "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
1130 // Intel Press, June, 2004 (http://www.aartbik.com/).
1131 //
1132
1133
CanVectorizeDataFlow(LoopNode * node,HBasicBlock * header,bool collect_alignment_info)1134 bool HLoopOptimization::CanVectorizeDataFlow(LoopNode* node,
1135 HBasicBlock* header,
1136 bool collect_alignment_info) {
1137 // Reset vector bookkeeping.
1138 vector_length_ = 0;
1139 vector_refs_->clear();
1140 vector_static_peeling_factor_ = 0;
1141 vector_dynamic_peeling_candidate_ = nullptr;
1142 vector_runtime_test_a_ =
1143 vector_runtime_test_b_ = nullptr;
1144
1145 // Traverse the data flow of the loop, in the original program order.
1146 for (HBlocksInLoopReversePostOrderIterator block_it(*header->GetLoopInformation());
1147 !block_it.Done();
1148 block_it.Advance()) {
1149 HBasicBlock* block = block_it.Current();
1150
1151 if (block == header) {
1152 // The header is of a certain structure (TrySetSimpleLoopHeader) and doesn't need to be
1153 // processed here.
1154 continue;
1155 }
1156
1157 // Phis in the loop-body prevent vectorization.
1158 // TODO: Enable vectorization of CF loops with Phis.
1159 if (!block->GetPhis().IsEmpty()) {
1160 return false;
1161 }
1162
1163 // Scan the loop-body instructions, starting a right-hand-side tree traversal at each
1164 // left-hand-side occurrence, which allows passing down attributes down the use tree.
1165 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1166 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
1167 return false; // failure to vectorize a left-hand-side
1168 }
1169 }
1170 }
1171
1172 // Prepare alignment analysis:
1173 // (1) find desired alignment (SIMD vector size in bytes).
1174 // (2) initialize static loop peeling votes (peeling factor that will
1175 // make one particular reference aligned), never to exceed (1).
1176 // (3) variable to record how many references share same alignment.
1177 // (4) variable to record suitable candidate for dynamic loop peeling.
1178 size_t desired_alignment = GetVectorSizeInBytes();
1179 ScopedArenaVector<uint32_t> peeling_votes(desired_alignment, 0u,
1180 loop_allocator_->Adapter(kArenaAllocLoopOptimization));
1181
1182 uint32_t max_num_same_alignment = 0;
1183 const ArrayReference* peeling_candidate = nullptr;
1184
1185 // Data dependence analysis. Find each pair of references with same type, where
1186 // at least one is a write. Each such pair denotes a possible data dependence.
1187 // This analysis exploits the property that differently typed arrays cannot be
1188 // aliased, as well as the property that references either point to the same
1189 // array or to two completely disjoint arrays, i.e., no partial aliasing.
1190 // Other than a few simply heuristics, no detailed subscript analysis is done.
1191 // The scan over references also prepares finding a suitable alignment strategy.
1192 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
1193 uint32_t num_same_alignment = 0;
1194 // Scan over all next references.
1195 for (auto j = i; ++j != vector_refs_->end(); ) {
1196 if (i->type == j->type && (i->lhs || j->lhs)) {
1197 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
1198 HInstruction* a = i->base;
1199 HInstruction* b = j->base;
1200 HInstruction* x = i->offset;
1201 HInstruction* y = j->offset;
1202 if (a == b) {
1203 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
1204 // Conservatively assume a loop-carried data dependence otherwise, and reject.
1205 if (x != y) {
1206 return false;
1207 }
1208 // Count the number of references that have the same alignment (since
1209 // base and offset are the same) and where at least one is a write, so
1210 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
1211 num_same_alignment++;
1212 } else {
1213 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
1214 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
1215 // generating an explicit a != b disambiguation runtime test on the two references.
1216 if (x != y) {
1217 // To avoid excessive overhead, we only accept one a != b test.
1218 if (vector_runtime_test_a_ == nullptr) {
1219 // First test found.
1220 vector_runtime_test_a_ = a;
1221 vector_runtime_test_b_ = b;
1222 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
1223 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1224 return false; // second test would be needed
1225 }
1226 }
1227 }
1228 }
1229 }
1230 // Update information for finding suitable alignment strategy:
1231 // (1) update votes for static loop peeling,
1232 // (2) update suitable candidate for dynamic loop peeling.
1233 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1234 if (alignment.Base() >= desired_alignment) {
1235 // If the array/string object has a known, sufficient alignment, use the
1236 // initial offset to compute the static loop peeling vote (this always
1237 // works, since elements have natural alignment).
1238 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1239 uint32_t vote = (offset == 0)
1240 ? 0
1241 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1242 DCHECK_LT(vote, 16u);
1243 ++peeling_votes[vote];
1244 } else if (BaseAlignment() >= desired_alignment &&
1245 num_same_alignment > max_num_same_alignment) {
1246 // Otherwise, if the array/string object has a known, sufficient alignment
1247 // for just the base but with an unknown offset, record the candidate with
1248 // the most occurrences for dynamic loop peeling (again, the peeling always
1249 // works, since elements have natural alignment).
1250 max_num_same_alignment = num_same_alignment;
1251 peeling_candidate = &(*i);
1252 }
1253 } // for i
1254
1255 if (collect_alignment_info) {
1256 // Update the info on alignment strategy.
1257 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1258 }
1259
1260 // Success!
1261 return true;
1262 }
1263
ShouldVectorizeCommon(LoopNode * node,HPhi * main_phi,int64_t trip_count)1264 bool HLoopOptimization::ShouldVectorizeCommon(LoopNode* node,
1265 HPhi* main_phi,
1266 int64_t trip_count) {
1267 HBasicBlock* header = node->loop_info->GetHeader();
1268 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1269
1270 bool enable_alignment_strategies = !IsInPredicatedVectorizationMode();
1271 if (!TrySetSimpleLoopHeader(header, &main_phi) ||
1272 !CanVectorizeDataFlow(node, header, enable_alignment_strategies) ||
1273 !IsVectorizationProfitable(trip_count) ||
1274 !TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
1275 return false;
1276 }
1277
1278 return true;
1279 }
1280
VectorizePredicated(LoopNode * node,HBasicBlock * block,HBasicBlock * exit)1281 void HLoopOptimization::VectorizePredicated(LoopNode* node,
1282 HBasicBlock* block,
1283 HBasicBlock* exit) {
1284 DCHECK(IsInPredicatedVectorizationMode());
1285
1286 vector_external_set_->clear();
1287
1288 HBasicBlock* header = node->loop_info->GetHeader();
1289 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1290
1291 // Adjust vector bookkeeping.
1292 HPhi* main_phi = nullptr;
1293 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
1294 DCHECK(is_simple_loop_header);
1295 vector_header_ = header;
1296 vector_body_ = block;
1297
1298 // Loop induction type.
1299 DataType::Type induc_type = main_phi->GetType();
1300 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1301 << induc_type;
1302
1303 // Generate loop control:
1304 // stc = <trip-count>;
1305 // vtc = <vector trip-count>
1306 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1307 HInstruction* vtc = stc;
1308 vector_index_ = graph_->GetConstant(induc_type, 0);
1309 bool needs_disambiguation_test = false;
1310 // Generate runtime disambiguation test:
1311 // vtc = a != b ? vtc : 0;
1312 if (NeedsArrayRefsDisambiguationTest()) {
1313 HInstruction* rt = Insert(
1314 preheader,
1315 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1316 vtc = Insert(preheader,
1317 new (global_allocator_)
1318 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
1319 needs_disambiguation_test = true;
1320 }
1321
1322 // Generate vector loop:
1323 // for ( ; i < vtc; i += vector_length)
1324 // <vectorized-loop-body>
1325 HBasicBlock* preheader_for_vector_loop =
1326 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1327 synthesis_mode_ = LoopSynthesisMode::kVector;
1328 GenerateNewLoopPredicated(node,
1329 preheader_for_vector_loop,
1330 vector_index_,
1331 vtc,
1332 graph_->GetConstant(induc_type, vector_length_));
1333
1334 // Generate scalar loop, if needed:
1335 // for ( ; i < stc; i += 1)
1336 // <loop-body>
1337 if (needs_disambiguation_test) {
1338 synthesis_mode_ = LoopSynthesisMode::kSequential;
1339 HBasicBlock* preheader_for_cleanup_loop =
1340 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1341 // Use "Traditional" version for the sequential loop.
1342 GenerateNewLoopScalarOrTraditional(node,
1343 preheader_for_cleanup_loop,
1344 vector_index_,
1345 stc,
1346 graph_->GetConstant(induc_type, 1),
1347 LoopAnalysisInfo::kNoUnrollingFactor);
1348 }
1349
1350 FinalizeVectorization(node);
1351
1352 // Assign governing predicates for the predicated instructions inserted during vectorization
1353 // outside the loop.
1354 for (auto it : *vector_external_set_) {
1355 DCHECK(it->IsVecOperation());
1356 HVecOperation* vec_op = it->AsVecOperation();
1357
1358 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1359 graph_->GetIntConstant(1),
1360 vec_op->GetPackedType(),
1361 vec_op->GetVectorLength(),
1362 0u);
1363 vec_op->GetBlock()->InsertInstructionBefore(set_pred, vec_op);
1364 vec_op->SetMergingGoverningPredicate(set_pred);
1365 }
1366 }
1367
VectorizeTraditional(LoopNode * node,HBasicBlock * block,HBasicBlock * exit,int64_t trip_count)1368 void HLoopOptimization::VectorizeTraditional(LoopNode* node,
1369 HBasicBlock* block,
1370 HBasicBlock* exit,
1371 int64_t trip_count) {
1372 DCHECK(!IsInPredicatedVectorizationMode());
1373
1374 vector_external_set_->clear();
1375
1376 HBasicBlock* header = node->loop_info->GetHeader();
1377 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1378
1379 // Pick a loop unrolling factor for the vector loop.
1380 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1381 block, trip_count, MaxNumberPeeled(), vector_length_);
1382 uint32_t chunk = vector_length_ * unroll;
1383
1384 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1385
1386 // A cleanup loop is needed, at least, for any unknown trip count or
1387 // for a known trip count with remainder iterations after vectorization.
1388 bool needs_cleanup =
1389 (trip_count == 0 || ((trip_count - vector_static_peeling_factor_) % chunk) != 0);
1390
1391 // Adjust vector bookkeeping.
1392 HPhi* main_phi = nullptr;
1393 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
1394 DCHECK(is_simple_loop_header);
1395 vector_header_ = header;
1396 vector_body_ = block;
1397
1398 // Loop induction type.
1399 DataType::Type induc_type = main_phi->GetType();
1400 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1401 << induc_type;
1402
1403 // Generate the trip count for static or dynamic loop peeling, if needed:
1404 // ptc = <peeling factor>;
1405 HInstruction* ptc = nullptr;
1406 if (vector_static_peeling_factor_ != 0) {
1407 // Static loop peeling for SIMD alignment (using the most suitable
1408 // fixed peeling factor found during prior alignment analysis).
1409 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1410 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1411 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1412 // Dynamic loop peeling for SIMD alignment (using the most suitable
1413 // candidate found during prior alignment analysis):
1414 // rem = offset % ALIGN; // adjusted as #elements
1415 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1416 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1417 uint32_t align = GetVectorSizeInBytes() >> shift;
1418 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1419 vector_dynamic_peeling_candidate_->is_string_char_at);
1420 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1421 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1422 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1423 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1424 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1425 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1426 induc_type, graph_->GetConstant(induc_type, align), rem));
1427 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1428 rem, graph_->GetConstant(induc_type, 0)));
1429 ptc = Insert(preheader, new (global_allocator_) HSelect(
1430 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1431 needs_cleanup = true; // don't know the exact amount
1432 }
1433
1434 // Generate loop control:
1435 // stc = <trip-count>;
1436 // ptc = min(stc, ptc);
1437 // vtc = stc - (stc - ptc) % chunk;
1438 // i = 0;
1439 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1440 HInstruction* vtc = stc;
1441 if (needs_cleanup) {
1442 DCHECK(IsPowerOfTwo(chunk));
1443 HInstruction* diff = stc;
1444 if (ptc != nullptr) {
1445 if (trip_count == 0) {
1446 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1447 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1448 }
1449 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1450 }
1451 HInstruction* rem = Insert(
1452 preheader, new (global_allocator_) HAnd(induc_type,
1453 diff,
1454 graph_->GetConstant(induc_type, chunk - 1)));
1455 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1456 }
1457 vector_index_ = graph_->GetConstant(induc_type, 0);
1458
1459 // Generate runtime disambiguation test:
1460 // vtc = a != b ? vtc : 0;
1461 if (NeedsArrayRefsDisambiguationTest()) {
1462 HInstruction* rt = Insert(
1463 preheader,
1464 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1465 vtc = Insert(preheader,
1466 new (global_allocator_)
1467 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
1468 needs_cleanup = true;
1469 }
1470
1471 // Generate alignment peeling loop, if needed:
1472 // for ( ; i < ptc; i += 1)
1473 // <loop-body>
1474 //
1475 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1476 // moved around during suspend checks, since all analysis was based on
1477 // nothing more than the Android runtime alignment conventions.
1478 if (ptc != nullptr) {
1479 synthesis_mode_ = LoopSynthesisMode::kSequential;
1480 HBasicBlock* preheader_for_peeling_loop =
1481 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1482 GenerateNewLoopScalarOrTraditional(node,
1483 preheader_for_peeling_loop,
1484 vector_index_,
1485 ptc,
1486 graph_->GetConstant(induc_type, 1),
1487 LoopAnalysisInfo::kNoUnrollingFactor);
1488 }
1489
1490 // Generate vector loop, possibly further unrolled:
1491 // for ( ; i < vtc; i += chunk)
1492 // <vectorized-loop-body>
1493 synthesis_mode_ = LoopSynthesisMode::kVector;
1494 HBasicBlock* preheader_for_vector_loop =
1495 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1496 GenerateNewLoopScalarOrTraditional(node,
1497 preheader_for_vector_loop,
1498 vector_index_,
1499 vtc,
1500 graph_->GetConstant(induc_type, vector_length_), // per unroll
1501 unroll);
1502
1503 // Generate cleanup loop, if needed:
1504 // for ( ; i < stc; i += 1)
1505 // <loop-body>
1506 if (needs_cleanup) {
1507 synthesis_mode_ = LoopSynthesisMode::kSequential;
1508 HBasicBlock* preheader_for_cleanup_loop =
1509 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit);
1510 GenerateNewLoopScalarOrTraditional(node,
1511 preheader_for_cleanup_loop,
1512 vector_index_,
1513 stc,
1514 graph_->GetConstant(induc_type, 1),
1515 LoopAnalysisInfo::kNoUnrollingFactor);
1516 }
1517
1518 FinalizeVectorization(node);
1519 }
1520
FinalizeVectorization(LoopNode * node)1521 void HLoopOptimization::FinalizeVectorization(LoopNode* node) {
1522 HBasicBlock* header = node->loop_info->GetHeader();
1523 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1524 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1525 // Link reductions to their final uses.
1526 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1527 if (i->first->IsPhi()) {
1528 HInstruction* phi = i->first;
1529 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1530 // Deal with regular uses.
1531 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1532 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1533 }
1534 phi->ReplaceWith(repl);
1535 }
1536 }
1537
1538 // Remove the original loop.
1539 for (HBlocksInLoopPostOrderIterator it_loop(*node->loop_info);
1540 !it_loop.Done();
1541 it_loop.Advance()) {
1542 HBasicBlock* cur_block = it_loop.Current();
1543 if (cur_block == node->loop_info->GetHeader()) {
1544 continue;
1545 }
1546 cur_block->DisconnectAndDelete();
1547 }
1548
1549 while (!header->GetFirstInstruction()->IsGoto()) {
1550 header->RemoveInstruction(header->GetFirstInstruction());
1551 }
1552
1553 // Update loop hierarchy: the old header now resides in the same outer loop
1554 // as the old preheader. Note that we don't bother putting sequential
1555 // loops back in the hierarchy at this point.
1556 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1557 node->loop_info = vloop;
1558 }
1559
InitializeForNewLoop(HBasicBlock * new_preheader,HInstruction * lo)1560 HPhi* HLoopOptimization::InitializeForNewLoop(HBasicBlock* new_preheader, HInstruction* lo) {
1561 DataType::Type induc_type = lo->GetType();
1562 // Prepare new loop.
1563 vector_preheader_ = new_preheader,
1564 vector_header_ = vector_preheader_->GetSingleSuccessor();
1565 vector_body_ = vector_header_->GetSuccessors()[1];
1566 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1567 kNoRegNumber,
1568 0,
1569 HPhi::ToPhiType(induc_type));
1570 vector_header_->AddPhi(phi);
1571 vector_index_ = phi;
1572 vector_permanent_map_->clear();
1573 predicate_info_map_->clear();
1574
1575 return phi;
1576 }
1577
GenerateNewLoopScalarOrTraditional(LoopNode * node,HBasicBlock * new_preheader,HInstruction * lo,HInstruction * hi,HInstruction * step,uint32_t unroll)1578 void HLoopOptimization::GenerateNewLoopScalarOrTraditional(LoopNode* node,
1579 HBasicBlock* new_preheader,
1580 HInstruction* lo,
1581 HInstruction* hi,
1582 HInstruction* step,
1583 uint32_t unroll) {
1584 DCHECK(unroll == 1 || synthesis_mode_ == LoopSynthesisMode::kVector);
1585 DataType::Type induc_type = lo->GetType();
1586 HPhi* phi = InitializeForNewLoop(new_preheader, lo);
1587
1588 // Generate loop exit check.
1589 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1590 vector_header_->AddInstruction(cond);
1591 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
1592
1593 for (uint32_t u = 0; u < unroll; u++) {
1594 GenerateNewLoopBodyOnce(node, induc_type, step);
1595 }
1596
1597 FinalizePhisForNewLoop(phi, lo);
1598 }
1599
GenerateNewLoopPredicated(LoopNode * node,HBasicBlock * new_preheader,HInstruction * lo,HInstruction * hi,HInstruction * step)1600 void HLoopOptimization::GenerateNewLoopPredicated(LoopNode* node,
1601 HBasicBlock* new_preheader,
1602 HInstruction* lo,
1603 HInstruction* hi,
1604 HInstruction* step) {
1605 DCHECK(IsInPredicatedVectorizationMode());
1606 DCHECK(synthesis_mode_ == LoopSynthesisMode::kVector);
1607 DataType::Type induc_type = lo->GetType();
1608 HPhi* phi = InitializeForNewLoop(new_preheader, lo);
1609
1610 // Generate loop exit check.
1611 HVecPredWhile* pred_while =
1612 new (global_allocator_) HVecPredWhile(global_allocator_,
1613 phi,
1614 hi,
1615 HVecPredWhile::CondKind::kLO,
1616 DataType::Type::kInt32,
1617 vector_length_,
1618 0u);
1619
1620 HInstruction* cond =
1621 new (global_allocator_) HVecPredToBoolean(global_allocator_,
1622 pred_while,
1623 HVecPredToBoolean::PCondKind::kNFirst,
1624 DataType::Type::kInt32,
1625 vector_length_,
1626 0u);
1627
1628 vector_header_->AddInstruction(pred_while);
1629 vector_header_->AddInstruction(cond);
1630 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
1631
1632 PreparePredicateInfoMap(node);
1633 GenerateNewLoopBodyOnce(node, induc_type, step);
1634 InitPredicateInfoMap(node, pred_while);
1635
1636 // Assign governing predicates for instructions in the loop; the traversal order doesn't matter.
1637 for (HBlocksInLoopIterator block_it(*node->loop_info);
1638 !block_it.Done();
1639 block_it.Advance()) {
1640 HBasicBlock* cur_block = block_it.Current();
1641
1642 for (HInstructionIterator it(cur_block->GetInstructions()); !it.Done(); it.Advance()) {
1643 auto i = vector_map_->find(it.Current());
1644 if (i != vector_map_->end()) {
1645 HInstruction* instr = i->second;
1646
1647 if (!instr->IsVecOperation()) {
1648 continue;
1649 }
1650 // There are cases when a vector instruction, which corresponds to some instruction in the
1651 // original scalar loop, is located not in the newly created vector loop but
1652 // in the vector loop preheader (and hence recorded in vector_external_set_).
1653 //
1654 // Governing predicates will be set for such instructions separately.
1655 bool in_vector_loop = vector_header_->GetLoopInformation()->Contains(*instr->GetBlock());
1656 DCHECK_IMPLIES(!in_vector_loop,
1657 vector_external_set_->find(instr) != vector_external_set_->end());
1658
1659 if (in_vector_loop &&
1660 !instr->AsVecOperation()->IsPredicated()) {
1661 HVecOperation* op = instr->AsVecOperation();
1662 HVecPredSetOperation* pred = predicate_info_map_->Get(cur_block)->GetControlPredicate();
1663 op->SetMergingGoverningPredicate(pred);
1664 }
1665 }
1666 }
1667 }
1668
1669 FinalizePhisForNewLoop(phi, lo);
1670 }
1671
GenerateNewLoopBodyOnce(LoopNode * node,DataType::Type induc_type,HInstruction * step)1672 void HLoopOptimization::GenerateNewLoopBodyOnce(LoopNode* node,
1673 DataType::Type induc_type,
1674 HInstruction* step) {
1675 // Generate instruction map.
1676 vector_map_->clear();
1677 HLoopInformation* loop_info = node->loop_info;
1678
1679 // Traverse the data flow of the loop, in the original program order.
1680 for (HBlocksInLoopReversePostOrderIterator block_it(*loop_info);
1681 !block_it.Done();
1682 block_it.Advance()) {
1683 HBasicBlock* cur_block = block_it.Current();
1684
1685 if (cur_block == loop_info->GetHeader()) {
1686 continue;
1687 }
1688
1689 for (HInstructionIterator it(cur_block->GetInstructions()); !it.Done(); it.Advance()) {
1690 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1691 DCHECK(vectorized_def);
1692 }
1693 }
1694
1695 // Generate body from the instruction map, in the original program order.
1696 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1697 for (HBlocksInLoopReversePostOrderIterator block_it(*loop_info);
1698 !block_it.Done();
1699 block_it.Advance()) {
1700 HBasicBlock* cur_block = block_it.Current();
1701
1702 if (cur_block == loop_info->GetHeader()) {
1703 continue;
1704 }
1705
1706 for (HInstructionIterator it(cur_block->GetInstructions()); !it.Done(); it.Advance()) {
1707 auto i = vector_map_->find(it.Current());
1708 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1709 Insert(vector_body_, i->second);
1710 // Deal with instructions that need an environment, such as the scalar intrinsics.
1711 if (i->second->NeedsEnvironment()) {
1712 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1713 }
1714 }
1715 }
1716 }
1717 // Generate the induction.
1718 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1719 Insert(vector_body_, vector_index_);
1720 }
1721
FinalizePhisForNewLoop(HPhi * phi,HInstruction * lo)1722 void HLoopOptimization::FinalizePhisForNewLoop(HPhi* phi, HInstruction* lo) {
1723 // Finalize phi inputs for the reductions (if any).
1724 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1725 if (!i->first->IsPhi()) {
1726 DCHECK(i->second->IsPhi());
1727 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1728 }
1729 }
1730 // Finalize phi inputs for the loop index.
1731 phi->AddInput(lo);
1732 phi->AddInput(vector_index_);
1733 vector_index_ = phi;
1734 }
1735
VectorizeDef(LoopNode * node,HInstruction * instruction,bool generate_code)1736 bool HLoopOptimization::VectorizeDef(LoopNode* node,
1737 HInstruction* instruction,
1738 bool generate_code) {
1739 // Accept a left-hand-side array base[index] for
1740 // (1) supported vector type,
1741 // (2) loop-invariant base,
1742 // (3) unit stride index,
1743 // (4) vectorizable right-hand-side value.
1744 uint64_t restrictions = kNone;
1745 // Don't accept expressions that can throw.
1746 if (instruction->CanThrow()) {
1747 return false;
1748 }
1749 if (instruction->IsArraySet()) {
1750 DataType::Type type = instruction->AsArraySet()->GetComponentType();
1751 HInstruction* base = instruction->InputAt(0);
1752 HInstruction* index = instruction->InputAt(1);
1753 HInstruction* value = instruction->InputAt(2);
1754 HInstruction* offset = nullptr;
1755 // For narrow types, explicit type conversion may have been
1756 // optimized way, so set the no hi bits restriction here.
1757 if (DataType::Size(type) <= 2) {
1758 restrictions |= kNoHiBits;
1759 }
1760 if (TrySetVectorType(type, &restrictions) &&
1761 node->loop_info->IsDefinedOutOfTheLoop(base) &&
1762 induction_range_.IsUnitStride(instruction->GetBlock(), index, graph_, &offset) &&
1763 VectorizeUse(node, value, generate_code, type, restrictions)) {
1764 if (generate_code) {
1765 GenerateVecSub(index, offset);
1766 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
1767 } else {
1768 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1769 }
1770 return true;
1771 }
1772 return false;
1773 }
1774 // Accept a left-hand-side reduction for
1775 // (1) supported vector type,
1776 // (2) vectorizable right-hand-side value.
1777 auto redit = reductions_->find(instruction);
1778 if (redit != reductions_->end()) {
1779 DataType::Type type = instruction->GetType();
1780 // Recognize SAD idiom or direct reduction.
1781 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1782 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
1783 (TrySetVectorType(type, &restrictions) &&
1784 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
1785 DCHECK(!instruction->IsPhi());
1786 if (generate_code) {
1787 HInstruction* new_red_vec_op = vector_map_->Get(instruction);
1788 HInstruction* original_phi = redit->second;
1789 DCHECK(original_phi->IsPhi());
1790 vector_permanent_map_->Put(new_red_vec_op, vector_map_->Get(original_phi));
1791 vector_permanent_map_->Overwrite(original_phi, new_red_vec_op);
1792 }
1793 return true;
1794 }
1795 return false;
1796 }
1797 // Branch back okay.
1798 if (instruction->IsGoto()) {
1799 return true;
1800 }
1801
1802 if (instruction->IsIf()) {
1803 return VectorizeIfCondition(node, instruction, generate_code, restrictions);
1804 }
1805 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1806 // Note that actual uses are inspected during right-hand-side tree traversal.
1807 return !IsUsedOutsideLoop(node->loop_info, instruction)
1808 && !instruction->DoesAnyWrite();
1809 }
1810
VectorizeUse(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type type,uint64_t restrictions)1811 bool HLoopOptimization::VectorizeUse(LoopNode* node,
1812 HInstruction* instruction,
1813 bool generate_code,
1814 DataType::Type type,
1815 uint64_t restrictions) {
1816 // Accept anything for which code has already been generated.
1817 if (generate_code) {
1818 if (vector_map_->find(instruction) != vector_map_->end()) {
1819 return true;
1820 }
1821 }
1822 // Continue the right-hand-side tree traversal, passing in proper
1823 // types and vector restrictions along the way. During code generation,
1824 // all new nodes are drawn from the global allocator.
1825 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1826 // Accept invariant use, using scalar expansion.
1827 if (generate_code) {
1828 GenerateVecInv(instruction, type);
1829 }
1830 return true;
1831 } else if (instruction->IsArrayGet()) {
1832 // Deal with vector restrictions.
1833 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1834
1835 if (is_string_char_at && (HasVectorRestrictions(restrictions, kNoStringCharAt))) {
1836 return false;
1837 }
1838 // Accept a right-hand-side array base[index] for
1839 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
1840 // (2) loop-invariant base,
1841 // (3) unit stride index,
1842 // (4) vectorizable right-hand-side value.
1843 HInstruction* base = instruction->InputAt(0);
1844 HInstruction* index = instruction->InputAt(1);
1845 HInstruction* offset = nullptr;
1846 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
1847 node->loop_info->IsDefinedOutOfTheLoop(base) &&
1848 induction_range_.IsUnitStride(instruction->GetBlock(), index, graph_, &offset)) {
1849 if (generate_code) {
1850 GenerateVecSub(index, offset);
1851 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
1852 } else {
1853 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
1854 }
1855 return true;
1856 }
1857 } else if (instruction->IsPhi()) {
1858 // Accept particular phi operations.
1859 if (reductions_->find(instruction) != reductions_->end()) {
1860 // Deal with vector restrictions.
1861 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1862 return false;
1863 }
1864 // Accept a reduction.
1865 if (generate_code) {
1866 GenerateVecReductionPhi(instruction->AsPhi());
1867 }
1868 return true;
1869 }
1870 // TODO: accept right-hand-side induction?
1871 return false;
1872 } else if (instruction->IsTypeConversion()) {
1873 // Accept particular type conversions.
1874 HTypeConversion* conversion = instruction->AsTypeConversion();
1875 HInstruction* opa = conversion->InputAt(0);
1876 DataType::Type from = conversion->GetInputType();
1877 DataType::Type to = conversion->GetResultType();
1878 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
1879 uint32_t size_vec = DataType::Size(type);
1880 uint32_t size_from = DataType::Size(from);
1881 uint32_t size_to = DataType::Size(to);
1882 // Accept an integral conversion
1883 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1884 // (1b) widening from at least vector type, and
1885 // (2) vectorizable operand.
1886 if ((size_to < size_from &&
1887 size_to == size_vec &&
1888 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1889 (size_to >= size_from &&
1890 size_from >= size_vec &&
1891 VectorizeUse(node, opa, generate_code, type, restrictions))) {
1892 if (generate_code) {
1893 if (synthesis_mode_ == LoopSynthesisMode::kVector) {
1894 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1895 } else {
1896 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1897 }
1898 }
1899 return true;
1900 }
1901 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
1902 DCHECK_EQ(to, type);
1903 // Accept int to float conversion for
1904 // (1) supported int,
1905 // (2) vectorizable operand.
1906 if (TrySetVectorType(from, &restrictions) &&
1907 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1908 if (generate_code) {
1909 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1910 }
1911 return true;
1912 }
1913 }
1914 return false;
1915 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1916 // Accept unary operator for vectorizable operand.
1917 HInstruction* opa = instruction->InputAt(0);
1918 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1919 if (generate_code) {
1920 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1921 }
1922 return true;
1923 }
1924 } else if (instruction->IsAdd() || instruction->IsSub() ||
1925 instruction->IsMul() || instruction->IsDiv() ||
1926 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1927 // Deal with vector restrictions.
1928 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1929 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1930 return false;
1931 }
1932 // Accept binary operator for vectorizable operands.
1933 HInstruction* opa = instruction->InputAt(0);
1934 HInstruction* opb = instruction->InputAt(1);
1935 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1936 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1937 if (generate_code) {
1938 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1939 }
1940 return true;
1941 }
1942 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
1943 // Recognize halving add idiom.
1944 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1945 return true;
1946 }
1947 // Deal with vector restrictions.
1948 HInstruction* opa = instruction->InputAt(0);
1949 HInstruction* opb = instruction->InputAt(1);
1950 HInstruction* r = opa;
1951 bool is_unsigned = false;
1952 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1953 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1954 return false; // unsupported instruction
1955 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1956 // Shifts right need extra care to account for higher order bits.
1957 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1958 if (instruction->IsShr() &&
1959 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1960 return false; // reject, unless all operands are sign-extension narrower
1961 } else if (instruction->IsUShr() &&
1962 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1963 return false; // reject, unless all operands are zero-extension narrower
1964 }
1965 }
1966 // Accept shift operator for vectorizable/invariant operands.
1967 // TODO: accept symbolic, albeit loop invariant shift factors.
1968 DCHECK(r != nullptr);
1969 if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) { // de-idiom
1970 r = opa;
1971 }
1972 int64_t distance = 0;
1973 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1974 IsInt64AndGet(opb, /*out*/ &distance)) {
1975 // Restrict shift distance to packed data type width.
1976 int64_t max_distance = DataType::Size(type) * 8;
1977 if (0 <= distance && distance < max_distance) {
1978 if (generate_code) {
1979 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
1980 }
1981 return true;
1982 }
1983 }
1984 } else if (instruction->IsAbs()) {
1985 // Deal with vector restrictions.
1986 HInstruction* opa = instruction->InputAt(0);
1987 HInstruction* r = opa;
1988 bool is_unsigned = false;
1989 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1990 return false;
1991 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1992 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1993 return false; // reject, unless operand is sign-extension narrower
1994 }
1995 // Accept ABS(x) for vectorizable operand.
1996 DCHECK(r != nullptr);
1997 if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) { // de-idiom
1998 r = opa;
1999 }
2000 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
2001 if (generate_code) {
2002 GenerateVecOp(instruction,
2003 vector_map_->Get(r),
2004 nullptr,
2005 HVecOperation::ToProperType(type, is_unsigned));
2006 }
2007 return true;
2008 }
2009 }
2010 return false;
2011 }
2012
GetVectorSizeInBytes()2013 uint32_t HLoopOptimization::GetVectorSizeInBytes() {
2014 return simd_register_size_;
2015 }
2016
TrySetVectorType(DataType::Type type,uint64_t * restrictions)2017 bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
2018 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
2019 switch (compiler_options_->GetInstructionSet()) {
2020 case InstructionSet::kArm:
2021 case InstructionSet::kThumb2:
2022 // Allow vectorization for all ARM devices, because Android assumes that
2023 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
2024 *restrictions |= kNoIfCond;
2025 switch (type) {
2026 case DataType::Type::kBool:
2027 case DataType::Type::kUint8:
2028 case DataType::Type::kInt8:
2029 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
2030 return TrySetVectorLength(type, 8);
2031 case DataType::Type::kUint16:
2032 case DataType::Type::kInt16:
2033 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
2034 return TrySetVectorLength(type, 4);
2035 case DataType::Type::kInt32:
2036 *restrictions |= kNoDiv | kNoWideSAD;
2037 return TrySetVectorLength(type, 2);
2038 default:
2039 break;
2040 }
2041 return false;
2042 case InstructionSet::kArm64:
2043 if (IsInPredicatedVectorizationMode()) {
2044 // SVE vectorization.
2045 CHECK(features->AsArm64InstructionSetFeatures()->HasSVE());
2046 size_t vector_length = simd_register_size_ / DataType::Size(type);
2047 DCHECK_EQ(simd_register_size_ % DataType::Size(type), 0u);
2048 switch (type) {
2049 case DataType::Type::kBool:
2050 *restrictions |= kNoDiv |
2051 kNoSignedHAdd |
2052 kNoUnsignedHAdd |
2053 kNoUnroundedHAdd |
2054 kNoSAD |
2055 kNoIfCond;
2056 return TrySetVectorLength(type, vector_length);
2057 case DataType::Type::kUint8:
2058 case DataType::Type::kInt8:
2059 *restrictions |= kNoDiv |
2060 kNoSignedHAdd |
2061 kNoUnsignedHAdd |
2062 kNoUnroundedHAdd |
2063 kNoSAD;
2064 return TrySetVectorLength(type, vector_length);
2065 case DataType::Type::kUint16:
2066 case DataType::Type::kInt16:
2067 *restrictions |= kNoDiv |
2068 kNoStringCharAt | // TODO: support in predicated mode.
2069 kNoSignedHAdd |
2070 kNoUnsignedHAdd |
2071 kNoUnroundedHAdd |
2072 kNoSAD |
2073 kNoDotProd;
2074 return TrySetVectorLength(type, vector_length);
2075 case DataType::Type::kInt32:
2076 *restrictions |= kNoDiv | kNoSAD;
2077 return TrySetVectorLength(type, vector_length);
2078 case DataType::Type::kInt64:
2079 *restrictions |= kNoDiv | kNoSAD | kNoIfCond;
2080 return TrySetVectorLength(type, vector_length);
2081 case DataType::Type::kFloat32:
2082 *restrictions |= kNoReduction | kNoIfCond;
2083 return TrySetVectorLength(type, vector_length);
2084 case DataType::Type::kFloat64:
2085 *restrictions |= kNoReduction | kNoIfCond;
2086 return TrySetVectorLength(type, vector_length);
2087 default:
2088 break;
2089 }
2090 return false;
2091 } else {
2092 // Allow vectorization for all ARM devices, because Android assumes that
2093 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
2094 *restrictions |= kNoIfCond;
2095 switch (type) {
2096 case DataType::Type::kBool:
2097 case DataType::Type::kUint8:
2098 case DataType::Type::kInt8:
2099 *restrictions |= kNoDiv;
2100 return TrySetVectorLength(type, 16);
2101 case DataType::Type::kUint16:
2102 case DataType::Type::kInt16:
2103 *restrictions |= kNoDiv;
2104 return TrySetVectorLength(type, 8);
2105 case DataType::Type::kInt32:
2106 *restrictions |= kNoDiv;
2107 return TrySetVectorLength(type, 4);
2108 case DataType::Type::kInt64:
2109 *restrictions |= kNoDiv | kNoMul;
2110 return TrySetVectorLength(type, 2);
2111 case DataType::Type::kFloat32:
2112 *restrictions |= kNoReduction;
2113 return TrySetVectorLength(type, 4);
2114 case DataType::Type::kFloat64:
2115 *restrictions |= kNoReduction;
2116 return TrySetVectorLength(type, 2);
2117 default:
2118 break;
2119 }
2120 return false;
2121 }
2122 case InstructionSet::kX86:
2123 case InstructionSet::kX86_64:
2124 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
2125 *restrictions |= kNoIfCond;
2126 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
2127 switch (type) {
2128 case DataType::Type::kBool:
2129 case DataType::Type::kUint8:
2130 case DataType::Type::kInt8:
2131 *restrictions |= kNoMul |
2132 kNoDiv |
2133 kNoShift |
2134 kNoAbs |
2135 kNoSignedHAdd |
2136 kNoUnroundedHAdd |
2137 kNoSAD |
2138 kNoDotProd;
2139 return TrySetVectorLength(type, 16);
2140 case DataType::Type::kUint16:
2141 *restrictions |= kNoDiv |
2142 kNoAbs |
2143 kNoSignedHAdd |
2144 kNoUnroundedHAdd |
2145 kNoSAD |
2146 kNoDotProd;
2147 return TrySetVectorLength(type, 8);
2148 case DataType::Type::kInt16:
2149 *restrictions |= kNoDiv |
2150 kNoAbs |
2151 kNoSignedHAdd |
2152 kNoUnroundedHAdd |
2153 kNoSAD;
2154 return TrySetVectorLength(type, 8);
2155 case DataType::Type::kInt32:
2156 *restrictions |= kNoDiv | kNoSAD;
2157 return TrySetVectorLength(type, 4);
2158 case DataType::Type::kInt64:
2159 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
2160 return TrySetVectorLength(type, 2);
2161 case DataType::Type::kFloat32:
2162 *restrictions |= kNoReduction;
2163 return TrySetVectorLength(type, 4);
2164 case DataType::Type::kFloat64:
2165 *restrictions |= kNoReduction;
2166 return TrySetVectorLength(type, 2);
2167 default:
2168 break;
2169 } // switch type
2170 }
2171 return false;
2172 default:
2173 return false;
2174 } // switch instruction set
2175 }
2176
TrySetVectorLengthImpl(uint32_t length)2177 bool HLoopOptimization::TrySetVectorLengthImpl(uint32_t length) {
2178 DCHECK(IsPowerOfTwo(length) && length >= 2u);
2179 // First time set?
2180 if (vector_length_ == 0) {
2181 vector_length_ = length;
2182 }
2183 // Different types are acceptable within a loop-body, as long as all the corresponding vector
2184 // lengths match exactly to obtain a uniform traversal through the vector iteration space
2185 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
2186 return vector_length_ == length;
2187 }
2188
GenerateVecInv(HInstruction * org,DataType::Type type)2189 void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
2190 if (vector_map_->find(org) == vector_map_->end()) {
2191 // In scalar code, just use a self pass-through for scalar invariants
2192 // (viz. expression remains itself).
2193 if (synthesis_mode_ == LoopSynthesisMode::kSequential) {
2194 vector_map_->Put(org, org);
2195 return;
2196 }
2197 // In vector code, explicit scalar expansion is needed.
2198 HInstruction* vector = nullptr;
2199 auto it = vector_permanent_map_->find(org);
2200 if (it != vector_permanent_map_->end()) {
2201 vector = it->second; // reuse during unrolling
2202 } else {
2203 // Generates ReplicateScalar( (optional_type_conv) org ).
2204 HInstruction* input = org;
2205 DataType::Type input_type = input->GetType();
2206 if (type != input_type && (type == DataType::Type::kInt64 ||
2207 input_type == DataType::Type::kInt64)) {
2208 input = Insert(vector_preheader_,
2209 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
2210 }
2211 vector = new (global_allocator_)
2212 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
2213 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
2214 MaybeInsertInVectorExternalSet(vector);
2215 }
2216 vector_map_->Put(org, vector);
2217 }
2218 }
2219
GenerateVecSub(HInstruction * org,HInstruction * offset)2220 void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
2221 if (vector_map_->find(org) == vector_map_->end()) {
2222 HInstruction* subscript = vector_index_;
2223 int64_t value = 0;
2224 if (!IsInt64AndGet(offset, &value) || value != 0) {
2225 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
2226 if (org->IsPhi()) {
2227 Insert(vector_body_, subscript); // lacks layout placeholder
2228 }
2229 }
2230 vector_map_->Put(org, subscript);
2231 }
2232 }
2233
GenerateVecMem(HInstruction * org,HInstruction * opa,HInstruction * opb,HInstruction * offset,DataType::Type type)2234 void HLoopOptimization::GenerateVecMem(HInstruction* org,
2235 HInstruction* opa,
2236 HInstruction* opb,
2237 HInstruction* offset,
2238 DataType::Type type) {
2239 uint32_t dex_pc = org->GetDexPc();
2240 HInstruction* vector = nullptr;
2241 if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2242 // Vector store or load.
2243 bool is_string_char_at = false;
2244 HInstruction* base = org->InputAt(0);
2245 if (opb != nullptr) {
2246 vector = new (global_allocator_) HVecStore(
2247 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
2248 } else {
2249 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
2250 vector = new (global_allocator_) HVecLoad(global_allocator_,
2251 base,
2252 opa,
2253 type,
2254 org->GetSideEffects(),
2255 vector_length_,
2256 is_string_char_at,
2257 dex_pc);
2258 }
2259 // Known (forced/adjusted/original) alignment?
2260 if (vector_dynamic_peeling_candidate_ != nullptr) {
2261 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
2262 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
2263 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
2264 vector->AsVecMemoryOperation()->SetAlignment( // forced
2265 Alignment(GetVectorSizeInBytes(), 0));
2266 }
2267 } else {
2268 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
2269 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
2270 }
2271 } else {
2272 // Scalar store or load.
2273 DCHECK(synthesis_mode_ == LoopSynthesisMode::kSequential);
2274 if (opb != nullptr) {
2275 DataType::Type component_type = org->AsArraySet()->GetComponentType();
2276 vector = new (global_allocator_) HArraySet(
2277 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
2278 } else {
2279 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
2280 vector = new (global_allocator_) HArrayGet(
2281 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
2282 }
2283 }
2284 vector_map_->Put(org, vector);
2285 }
2286
GenerateVecReductionPhi(HPhi * orig_phi)2287 void HLoopOptimization::GenerateVecReductionPhi(HPhi* orig_phi) {
2288 DCHECK(reductions_->find(orig_phi) != reductions_->end());
2289 DCHECK(reductions_->Get(orig_phi->InputAt(1)) == orig_phi);
2290 HInstruction* vector = nullptr;
2291 if (synthesis_mode_ == LoopSynthesisMode::kSequential) {
2292 HPhi* new_phi = new (global_allocator_) HPhi(
2293 global_allocator_, kNoRegNumber, 0, orig_phi->GetType());
2294 vector_header_->AddPhi(new_phi);
2295 vector = new_phi;
2296 } else {
2297 // Link vector reduction back to prior unrolled update, or a first phi.
2298 auto it = vector_permanent_map_->find(orig_phi);
2299 if (it != vector_permanent_map_->end()) {
2300 vector = it->second;
2301 } else {
2302 HPhi* new_phi = new (global_allocator_) HPhi(
2303 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
2304 vector_header_->AddPhi(new_phi);
2305 vector = new_phi;
2306 }
2307 }
2308 vector_map_->Put(orig_phi, vector);
2309 }
2310
GenerateVecReductionPhiInputs(HPhi * phi,HInstruction * reduction)2311 void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
2312 HInstruction* new_phi = vector_map_->Get(phi);
2313 HInstruction* new_init = reductions_->Get(phi);
2314 HInstruction* new_red = vector_map_->Get(reduction);
2315 // Link unrolled vector loop back to new phi.
2316 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
2317 DCHECK(new_phi->IsVecOperation());
2318 }
2319 // Prepare the new initialization.
2320 if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2321 // Generate a [initial, 0, .., 0] vector for add or
2322 // a [initial, initial, .., initial] vector for min/max.
2323 HVecOperation* red_vector = new_red->AsVecOperation();
2324 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
2325 uint32_t vector_length = red_vector->GetVectorLength();
2326 DataType::Type type = red_vector->GetPackedType();
2327 if (kind == HVecReduce::ReductionKind::kSum) {
2328 new_init = Insert(vector_preheader_,
2329 new (global_allocator_) HVecSetScalars(global_allocator_,
2330 &new_init,
2331 type,
2332 vector_length,
2333 1,
2334 kNoDexPc));
2335 } else {
2336 new_init = Insert(vector_preheader_,
2337 new (global_allocator_) HVecReplicateScalar(global_allocator_,
2338 new_init,
2339 type,
2340 vector_length,
2341 kNoDexPc));
2342 }
2343 MaybeInsertInVectorExternalSet(new_init);
2344 } else {
2345 new_init = ReduceAndExtractIfNeeded(new_init);
2346 }
2347 // Set the phi inputs.
2348 DCHECK(new_phi->IsPhi());
2349 new_phi->AsPhi()->AddInput(new_init);
2350 new_phi->AsPhi()->AddInput(new_red);
2351 // New feed value for next phi (safe mutation in iteration).
2352 reductions_->find(phi)->second = new_phi;
2353 }
2354
ReduceAndExtractIfNeeded(HInstruction * instruction)2355 HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
2356 if (instruction->IsPhi()) {
2357 HInstruction* input = instruction->InputAt(1);
2358 if (HVecOperation::ReturnsSIMDValue(input)) {
2359 DCHECK(!input->IsPhi());
2360 HVecOperation* input_vector = input->AsVecOperation();
2361 uint32_t vector_length = input_vector->GetVectorLength();
2362 DataType::Type type = input_vector->GetPackedType();
2363 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
2364 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
2365 // Generate a vector reduction and scalar extract
2366 // x = REDUCE( [x_1, .., x_n] )
2367 // y = x_1
2368 // along the exit of the defining loop.
2369 HVecReduce* reduce = new (global_allocator_) HVecReduce(
2370 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
2371 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
2372 MaybeInsertInVectorExternalSet(reduce);
2373 instruction = new (global_allocator_) HVecExtractScalar(
2374 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
2375 exit->InsertInstructionAfter(instruction, reduce);
2376
2377 MaybeInsertInVectorExternalSet(instruction);
2378 }
2379 }
2380 return instruction;
2381 }
2382
2383 #define GENERATE_VEC(x, y) \
2384 if (synthesis_mode_ == LoopSynthesisMode::kVector) { \
2385 vector = (x); \
2386 } else { \
2387 DCHECK(synthesis_mode_ == LoopSynthesisMode::kSequential); \
2388 vector = (y); \
2389 } \
2390 break;
2391
GenerateVecOp(HInstruction * org,HInstruction * opa,HInstruction * opb,DataType::Type type)2392 HInstruction* HLoopOptimization::GenerateVecOp(HInstruction* org,
2393 HInstruction* opa,
2394 HInstruction* opb,
2395 DataType::Type type) {
2396 uint32_t dex_pc = org->GetDexPc();
2397 HInstruction* vector = nullptr;
2398 DataType::Type org_type = org->GetType();
2399 switch (org->GetKind()) {
2400 case HInstruction::kNeg:
2401 DCHECK(opb == nullptr);
2402 GENERATE_VEC(
2403 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
2404 new (global_allocator_) HNeg(org_type, opa, dex_pc));
2405 case HInstruction::kNot:
2406 DCHECK(opb == nullptr);
2407 GENERATE_VEC(
2408 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2409 new (global_allocator_) HNot(org_type, opa, dex_pc));
2410 case HInstruction::kBooleanNot:
2411 DCHECK(opb == nullptr);
2412 GENERATE_VEC(
2413 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2414 new (global_allocator_) HBooleanNot(opa, dex_pc));
2415 case HInstruction::kTypeConversion:
2416 DCHECK(opb == nullptr);
2417 GENERATE_VEC(
2418 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
2419 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
2420 case HInstruction::kAdd:
2421 GENERATE_VEC(
2422 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2423 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
2424 case HInstruction::kSub:
2425 GENERATE_VEC(
2426 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2427 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
2428 case HInstruction::kMul:
2429 GENERATE_VEC(
2430 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2431 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
2432 case HInstruction::kDiv:
2433 GENERATE_VEC(
2434 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2435 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
2436 case HInstruction::kAnd:
2437 GENERATE_VEC(
2438 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2439 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
2440 case HInstruction::kOr:
2441 GENERATE_VEC(
2442 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2443 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
2444 case HInstruction::kXor:
2445 GENERATE_VEC(
2446 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2447 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
2448 case HInstruction::kShl:
2449 GENERATE_VEC(
2450 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2451 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
2452 case HInstruction::kShr:
2453 GENERATE_VEC(
2454 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2455 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
2456 case HInstruction::kUShr:
2457 GENERATE_VEC(
2458 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2459 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
2460 case HInstruction::kAbs:
2461 DCHECK(opb == nullptr);
2462 GENERATE_VEC(
2463 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2464 new (global_allocator_) HAbs(org_type, opa, dex_pc));
2465 case HInstruction::kEqual: {
2466 // Special case.
2467 DCHECK_EQ(synthesis_mode_, LoopSynthesisMode::kVector);
2468 vector = new (global_allocator_)
2469 HVecCondition(global_allocator_, opa, opb, type, vector_length_, dex_pc);
2470 }
2471 break;
2472 default:
2473 break;
2474 } // switch
2475 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2476 vector_map_->Put(org, vector);
2477 return vector;
2478 }
2479
2480 #undef GENERATE_VEC
2481
2482 //
2483 // Vectorization idioms.
2484 //
2485
2486 // Method recognizes the following idioms:
2487 // rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2488 // truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
2489 // Provided that the operands are promoted to a wider form to do the arithmetic and
2490 // then cast back to narrower form, the idioms can be mapped into efficient SIMD
2491 // implementation that operates directly in narrower form (plus one extra bit).
2492 // TODO: current version recognizes implicit byte/short/char widening only;
2493 // explicit widening from int to long could be added later.
VectorizeHalvingAddIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type type,uint64_t restrictions)2494 bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2495 HInstruction* instruction,
2496 bool generate_code,
2497 DataType::Type type,
2498 uint64_t restrictions) {
2499 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
2500 // (note whether the sign bit in wider precision is shifted in has no effect
2501 // on the narrow precision computed by the idiom).
2502 if ((instruction->IsShr() ||
2503 instruction->IsUShr()) &&
2504 IsInt64Value(instruction->InputAt(1), 1)) {
2505 // Test for (a + b + c) >> 1 for optional constant c.
2506 HInstruction* a = nullptr;
2507 HInstruction* b = nullptr;
2508 int64_t c = 0;
2509 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
2510 // Accept c == 1 (rounded) or c == 0 (not rounded).
2511 bool is_rounded = false;
2512 if (c == 1) {
2513 is_rounded = true;
2514 } else if (c != 0) {
2515 return false;
2516 }
2517 // Accept consistent zero or sign extension on operands a and b.
2518 HInstruction* r = nullptr;
2519 HInstruction* s = nullptr;
2520 bool is_unsigned = false;
2521 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
2522 return false;
2523 }
2524 // Deal with vector restrictions.
2525 if ((is_unsigned && HasVectorRestrictions(restrictions, kNoUnsignedHAdd)) ||
2526 (!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2527 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2528 return false;
2529 }
2530 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2531 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
2532 DCHECK(r != nullptr && s != nullptr);
2533 if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) { // de-idiom
2534 r = instruction->InputAt(0);
2535 s = instruction->InputAt(1);
2536 }
2537 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2538 VectorizeUse(node, s, generate_code, type, restrictions)) {
2539 if (generate_code) {
2540 if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2541 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2542 global_allocator_,
2543 vector_map_->Get(r),
2544 vector_map_->Get(s),
2545 HVecOperation::ToProperType(type, is_unsigned),
2546 vector_length_,
2547 is_rounded,
2548 kNoDexPc));
2549 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2550 } else {
2551 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2552 }
2553 }
2554 return true;
2555 }
2556 }
2557 }
2558 return false;
2559 }
2560
2561 // Method recognizes the following idiom:
2562 // q += ABS(a - b) for signed operands a, b
2563 // Provided that the operands have the same type or are promoted to a wider form.
2564 // Since this may involve a vector length change, the idiom is handled by going directly
2565 // to a sad-accumulate node (rather than relying combining finer grained nodes later).
2566 // TODO: unsigned SAD too?
VectorizeSADIdiom(LoopNode * node,HInstruction * instruction,bool generate_code,DataType::Type reduction_type,uint64_t restrictions)2567 bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2568 HInstruction* instruction,
2569 bool generate_code,
2570 DataType::Type reduction_type,
2571 uint64_t restrictions) {
2572 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2573 // are done in the same precision (either int or long).
2574 if (!instruction->IsAdd() ||
2575 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
2576 return false;
2577 }
2578 HInstruction* acc = instruction->InputAt(0);
2579 HInstruction* abs = instruction->InputAt(1);
2580 HInstruction* a = nullptr;
2581 HInstruction* b = nullptr;
2582 if (abs->IsAbs() &&
2583 abs->GetType() == reduction_type &&
2584 IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2585 DCHECK(a != nullptr && b != nullptr);
2586 } else {
2587 return false;
2588 }
2589 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2590 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
2591 // We inspect the operands carefully to pick the most suited type.
2592 HInstruction* r = a;
2593 HInstruction* s = b;
2594 bool is_unsigned = false;
2595 DataType::Type sub_type = GetNarrowerType(a, b);
2596 if (reduction_type != sub_type &&
2597 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2598 return false;
2599 }
2600 // Try same/narrower type and deal with vector restrictions.
2601 if (!TrySetVectorType(sub_type, &restrictions) ||
2602 HasVectorRestrictions(restrictions, kNoSAD) ||
2603 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
2604 return false;
2605 }
2606 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2607 // idiomatic operation. Sequential code uses the original scalar expressions.
2608 DCHECK(r != nullptr && s != nullptr);
2609 if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) { // de-idiom
2610 r = s = abs->InputAt(0);
2611 }
2612 if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
2613 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2614 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2615 if (generate_code) {
2616 if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2617 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2618 global_allocator_,
2619 vector_map_->Get(acc),
2620 vector_map_->Get(r),
2621 vector_map_->Get(s),
2622 HVecOperation::ToProperType(reduction_type, is_unsigned),
2623 GetOtherVL(reduction_type, sub_type, vector_length_),
2624 kNoDexPc));
2625 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2626 } else {
2627 // "GenerateVecOp()" must not be called more than once for each original loop body
2628 // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2629 // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2630 // has not yet been processed.
2631 if (vector_map_->find(abs) == vector_map_->end()) {
2632 GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2633 }
2634 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
2635 }
2636 }
2637 return true;
2638 }
2639 return false;
2640 }
2641
2642 // Method recognises the following dot product idiom:
2643 // q += a * b for operands a, b whose type is narrower than the reduction one.
2644 // Provided that the operands have the same type or are promoted to a wider form.
2645 // Since this may involve a vector length change, the idiom is handled by going directly
2646 // 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)2647 bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2648 HInstruction* instruction,
2649 bool generate_code,
2650 DataType::Type reduction_type,
2651 uint64_t restrictions) {
2652 if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
2653 return false;
2654 }
2655
2656 HInstruction* const acc = instruction->InputAt(0);
2657 HInstruction* const mul = instruction->InputAt(1);
2658 if (!mul->IsMul() || mul->GetType() != reduction_type) {
2659 return false;
2660 }
2661
2662 HInstruction* const mul_left = mul->InputAt(0);
2663 HInstruction* const mul_right = mul->InputAt(1);
2664 HInstruction* r = mul_left;
2665 HInstruction* s = mul_right;
2666 DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
2667 bool is_unsigned = false;
2668
2669 if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
2670 return false;
2671 }
2672 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2673
2674 if (!TrySetVectorType(op_type, &restrictions) ||
2675 HasVectorRestrictions(restrictions, kNoDotProd)) {
2676 return false;
2677 }
2678
2679 DCHECK(r != nullptr && s != nullptr);
2680 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2681 // idiomatic operation. Sequential code uses the original scalar expressions.
2682 if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) { // de-idiom
2683 r = mul_left;
2684 s = mul_right;
2685 }
2686 if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
2687 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2688 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2689 if (generate_code) {
2690 if (synthesis_mode_ == LoopSynthesisMode::kVector) {
2691 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2692 global_allocator_,
2693 vector_map_->Get(acc),
2694 vector_map_->Get(r),
2695 vector_map_->Get(s),
2696 reduction_type,
2697 is_unsigned,
2698 GetOtherVL(reduction_type, op_type, vector_length_),
2699 kNoDexPc));
2700 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2701 } else {
2702 // "GenerateVecOp()" must not be called more than once for each original loop body
2703 // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2704 // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2705 // has not yet been processed.
2706 if (vector_map_->find(mul) == vector_map_->end()) {
2707 GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2708 }
2709 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
2710 }
2711 }
2712 return true;
2713 }
2714 return false;
2715 }
2716
VectorizeIfCondition(LoopNode * node,HInstruction * hif,bool generate_code,uint64_t restrictions)2717 bool HLoopOptimization::VectorizeIfCondition(LoopNode* node,
2718 HInstruction* hif,
2719 bool generate_code,
2720 uint64_t restrictions) {
2721 DCHECK(hif->IsIf());
2722 HInstruction* if_input = hif->InputAt(0);
2723
2724 if (!if_input->HasOnlyOneNonEnvironmentUse()) {
2725 // Avoid the complications of the condition used as materialized boolean.
2726 return false;
2727 }
2728
2729 if (!if_input->IsEqual()) {
2730 // TODO: Support other condition types.
2731 return false;
2732 }
2733
2734 HCondition* cond = if_input->AsCondition();
2735 HInstruction* opa = cond->InputAt(0);
2736 HInstruction* opb = cond->InputAt(1);
2737 DataType::Type type = GetNarrowerType(opa, opb);
2738
2739 if (!DataType::IsIntegralType(type)) {
2740 return false;
2741 }
2742
2743 bool is_unsigned = false;
2744 HInstruction* opa_promoted = opa;
2745 HInstruction* opb_promoted = opb;
2746 bool is_int_case = DataType::Type::kInt32 == opa->GetType() &&
2747 DataType::Type::kInt32 == opb->GetType();
2748
2749 // Condition arguments should be either both int32 or consistently extended signed/unsigned
2750 // narrower operands.
2751 if (!is_int_case &&
2752 !IsNarrowerOperands(opa, opb, type, &opa_promoted, &opb_promoted, &is_unsigned)) {
2753 return false;
2754 }
2755 type = HVecOperation::ToProperType(type, is_unsigned);
2756
2757 // For narrow types, explicit type conversion may have been
2758 // optimized way, so set the no hi bits restriction here.
2759 if (DataType::Size(type) <= 2) {
2760 restrictions |= kNoHiBits;
2761 }
2762
2763 if (!TrySetVectorType(type, &restrictions) ||
2764 HasVectorRestrictions(restrictions, kNoIfCond)) {
2765 return false;
2766 }
2767
2768 if (generate_code && synthesis_mode_ != LoopSynthesisMode::kVector) { // de-idiom
2769 opa_promoted = opa;
2770 opb_promoted = opb;
2771 }
2772
2773 if (VectorizeUse(node, opa_promoted, generate_code, type, restrictions) &&
2774 VectorizeUse(node, opb_promoted, generate_code, type, restrictions)) {
2775 if (generate_code) {
2776 HInstruction* vec_cond = GenerateVecOp(cond,
2777 vector_map_->Get(opa_promoted),
2778 vector_map_->Get(opb_promoted),
2779 type);
2780 DCHECK_EQ(synthesis_mode_, LoopSynthesisMode::kVector);
2781 HInstruction* vec_pred_not = new (global_allocator_)
2782 HVecPredNot(global_allocator_, vec_cond, type, vector_length_, hif->GetDexPc());
2783
2784 vector_map_->Put(hif, vec_pred_not);
2785 BlockPredicateInfo* pred_info = predicate_info_map_->Get(hif->GetBlock());
2786 pred_info->SetControlFlowInfo(vec_cond->AsVecPredSetOperation(),
2787 vec_pred_not->AsVecPredSetOperation());
2788 }
2789 return true;
2790 }
2791
2792 return false;
2793 }
2794
2795 //
2796 // Vectorization heuristics.
2797 //
2798
ComputeAlignment(HInstruction * offset,DataType::Type type,bool is_string_char_at,uint32_t peeling)2799 Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2800 DataType::Type type,
2801 bool is_string_char_at,
2802 uint32_t peeling) {
2803 // Combine the alignment and hidden offset that is guaranteed by
2804 // the Android runtime with a known starting index adjusted as bytes.
2805 int64_t value = 0;
2806 if (IsInt64AndGet(offset, /*out*/ &value)) {
2807 uint32_t start_offset =
2808 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2809 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2810 }
2811 // Otherwise, the Android runtime guarantees at least natural alignment.
2812 return Alignment(DataType::Size(type), 0);
2813 }
2814
SetAlignmentStrategy(const ScopedArenaVector<uint32_t> & peeling_votes,const ArrayReference * peeling_candidate)2815 void HLoopOptimization::SetAlignmentStrategy(const ScopedArenaVector<uint32_t>& peeling_votes,
2816 const ArrayReference* peeling_candidate) {
2817 // Current heuristic: pick the best static loop peeling factor, if any,
2818 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2819 uint32_t max_vote = 0;
2820 for (size_t i = 0; i < peeling_votes.size(); i++) {
2821 if (peeling_votes[i] > max_vote) {
2822 max_vote = peeling_votes[i];
2823 vector_static_peeling_factor_ = i;
2824 }
2825 }
2826 if (max_vote == 0) {
2827 vector_dynamic_peeling_candidate_ = peeling_candidate;
2828 }
2829 }
2830
MaxNumberPeeled()2831 uint32_t HLoopOptimization::MaxNumberPeeled() {
2832 if (vector_dynamic_peeling_candidate_ != nullptr) {
2833 return vector_length_ - 1u; // worst-case
2834 }
2835 return vector_static_peeling_factor_; // known exactly
2836 }
2837
IsVectorizationProfitable(int64_t trip_count)2838 bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
2839 // Current heuristic: non-empty body with sufficient number of iterations (if known).
2840 // TODO: refine by looking at e.g. operation count, alignment, etc.
2841 // TODO: trip count is really unsigned entity, provided the guarding test
2842 // is satisfied; deal with this more carefully later
2843 uint32_t max_peel = MaxNumberPeeled();
2844 // Peeling is not supported in predicated mode.
2845 DCHECK_IMPLIES(IsInPredicatedVectorizationMode(), max_peel == 0u);
2846 if (vector_length_ == 0) {
2847 return false; // nothing found
2848 } else if (trip_count < 0) {
2849 return false; // guard against non-taken/large
2850 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
2851 return false; // insufficient iterations
2852 }
2853 return true;
2854 }
2855
2856 //
2857 // Helpers.
2858 //
2859
TrySetPhiInduction(HPhi * phi,bool restrict_uses)2860 bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
2861 // Start with empty phi induction.
2862 iset_->clear();
2863
2864 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2865 // smart enough to follow strongly connected components (and it's probably not worth
2866 // it to make it so). See b/33775412.
2867 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2868 return false;
2869 }
2870
2871 // Lookup phi induction cycle.
2872 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2873 if (set != nullptr) {
2874 for (HInstruction* i : *set) {
2875 // Check that, other than instructions that are no longer in the graph (removed earlier)
2876 // each instruction is removable and, when restrict uses are requested, other than for phi,
2877 // all uses are contained within the cycle.
2878 if (!i->IsInBlock()) {
2879 continue;
2880 } else if (!i->IsRemovable()) {
2881 return false;
2882 } else if (i != phi && restrict_uses) {
2883 // Deal with regular uses.
2884 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2885 if (set->find(use.GetUser()) == set->end()) {
2886 return false;
2887 }
2888 }
2889 }
2890 iset_->insert(i); // copy
2891 }
2892 return true;
2893 }
2894 return false;
2895 }
2896
TrySetPhiReduction(HPhi * phi)2897 bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
2898 DCHECK(phi->IsLoopHeaderPhi());
2899 // Only unclassified phi cycles are candidates for reductions.
2900 if (induction_range_.IsClassified(phi)) {
2901 return false;
2902 }
2903 // Accept operations like x = x + .., provided that the phi and the reduction are
2904 // used exactly once inside the loop, and by each other.
2905 HInputsRef inputs = phi->GetInputs();
2906 if (inputs.size() == 2) {
2907 HInstruction* reduction = inputs[1];
2908 if (HasReductionFormat(reduction, phi)) {
2909 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2910 DCHECK(loop_info->Contains(*reduction->GetBlock()));
2911 const bool single_use_inside_loop =
2912 // Reduction update only used by phi.
2913 reduction->GetUses().HasExactlyOneElement() &&
2914 !reduction->HasEnvironmentUses() &&
2915 // Reduction update is only use of phi inside the loop.
2916 std::none_of(phi->GetUses().begin(),
2917 phi->GetUses().end(),
2918 [loop_info, reduction](const HUseListNode<HInstruction*>& use) {
2919 HInstruction* user = use.GetUser();
2920 return user != reduction && loop_info->Contains(*user->GetBlock());
2921 });
2922 if (single_use_inside_loop) {
2923 // Link reduction back, and start recording feed value.
2924 reductions_->Put(reduction, phi);
2925 reductions_->Put(phi, phi->InputAt(0));
2926 return true;
2927 }
2928 }
2929 }
2930 return false;
2931 }
2932
TrySetSimpleLoopHeader(HBasicBlock * block,HPhi ** main_phi)2933 bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2934 // Start with empty phi induction and reductions.
2935 iset_->clear();
2936 reductions_->clear();
2937
2938 // Scan the phis to find the following (the induction structure has already
2939 // been optimized, so we don't need to worry about trivial cases):
2940 // (1) optional reductions in loop,
2941 // (2) the main induction, used in loop control.
2942 HPhi* phi = nullptr;
2943 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2944 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2945 continue;
2946 } else if (phi == nullptr) {
2947 // Found the first candidate for main induction.
2948 phi = it.Current()->AsPhi();
2949 } else {
2950 return false;
2951 }
2952 }
2953
2954 // Then test for a typical loopheader:
2955 // s: SuspendCheck
2956 // c: Condition(phi, bound)
2957 // i: If(c)
2958 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
2959 HInstruction* s = block->GetFirstInstruction();
2960 if (s != nullptr && s->IsSuspendCheck()) {
2961 HInstruction* c = s->GetNext();
2962 if (c != nullptr &&
2963 c->IsCondition() &&
2964 c->GetUses().HasExactlyOneElement() && // only used for termination
2965 !c->HasEnvironmentUses()) { // unlikely, but not impossible
2966 HInstruction* i = c->GetNext();
2967 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2968 iset_->insert(c);
2969 iset_->insert(s);
2970 *main_phi = phi;
2971 return true;
2972 }
2973 }
2974 }
2975 }
2976 return false;
2977 }
2978
IsEmptyBody(HBasicBlock * block)2979 bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
2980 if (!block->GetPhis().IsEmpty()) {
2981 return false;
2982 }
2983 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2984 HInstruction* instruction = it.Current();
2985 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2986 return false;
2987 }
2988 }
2989 return true;
2990 }
2991
IsUsedOutsideLoop(HLoopInformation * loop_info,HInstruction * instruction)2992 bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2993 HInstruction* instruction) {
2994 // Deal with regular uses.
2995 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2996 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2997 return true;
2998 }
2999 }
3000 return false;
3001 }
3002
IsOnlyUsedAfterLoop(HLoopInformation * loop_info,HInstruction * instruction,bool collect_loop_uses,uint32_t * use_count)3003 bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
3004 HInstruction* instruction,
3005 bool collect_loop_uses,
3006 /*out*/ uint32_t* use_count) {
3007 // Deal with regular uses.
3008 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
3009 HInstruction* user = use.GetUser();
3010 if (iset_->find(user) == iset_->end()) { // not excluded?
3011 if (loop_info->Contains(*user->GetBlock())) {
3012 // If collect_loop_uses is set, simply keep adding those uses to the set.
3013 // Otherwise, reject uses inside the loop that were not already in the set.
3014 if (collect_loop_uses) {
3015 iset_->insert(user);
3016 continue;
3017 }
3018 return false;
3019 }
3020 ++*use_count;
3021 }
3022 }
3023 return true;
3024 }
3025
TryReplaceWithLastValue(HLoopInformation * loop_info,HInstruction * instruction,HBasicBlock * block)3026 bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
3027 HInstruction* instruction,
3028 HBasicBlock* block) {
3029 // Try to replace outside uses with the last value.
3030 if (induction_range_.CanGenerateLastValue(instruction)) {
3031 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
3032 // Deal with regular uses.
3033 const HUseList<HInstruction*>& uses = instruction->GetUses();
3034 for (auto it = uses.begin(), end = uses.end(); it != end;) {
3035 HInstruction* user = it->GetUser();
3036 size_t index = it->GetIndex();
3037 ++it; // increment before replacing
3038 if (iset_->find(user) == iset_->end()) { // not excluded?
3039 if (kIsDebugBuild) {
3040 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
3041 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
3042 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
3043 }
3044 user->ReplaceInput(replacement, index);
3045 induction_range_.Replace(user, instruction, replacement); // update induction
3046 }
3047 }
3048 // Deal with environment uses.
3049 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
3050 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
3051 HEnvironment* user = it->GetUser();
3052 size_t index = it->GetIndex();
3053 ++it; // increment before replacing
3054 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
3055 // Only update environment uses after the loop.
3056 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
3057 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
3058 user->RemoveAsUserOfInput(index);
3059 user->SetRawEnvAt(index, replacement);
3060 replacement->AddEnvUseAt(user, index);
3061 }
3062 }
3063 }
3064 return true;
3065 }
3066 return false;
3067 }
3068
TryAssignLastValue(HLoopInformation * loop_info,HInstruction * instruction,HBasicBlock * block,bool collect_loop_uses)3069 bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
3070 HInstruction* instruction,
3071 HBasicBlock* block,
3072 bool collect_loop_uses) {
3073 // Assigning the last value is always successful if there are no uses.
3074 // Otherwise, it succeeds in a no early-exit loop by generating the
3075 // proper last value assignment.
3076 uint32_t use_count = 0;
3077 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
3078 (use_count == 0 ||
3079 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
3080 }
3081
RemoveDeadInstructions(const HInstructionList & list)3082 void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
3083 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
3084 HInstruction* instruction = i.Current();
3085 if (instruction->IsDeadAndRemovable()) {
3086 simplified_ = true;
3087 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
3088 }
3089 }
3090 }
3091
CanRemoveCycle()3092 bool HLoopOptimization::CanRemoveCycle() {
3093 for (HInstruction* i : *iset_) {
3094 // We can never remove instructions that have environment
3095 // uses when we compile 'debuggable'.
3096 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
3097 return false;
3098 }
3099 // A deoptimization should never have an environment input removed.
3100 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
3101 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
3102 return false;
3103 }
3104 }
3105 }
3106 return true;
3107 }
3108
PreparePredicateInfoMap(LoopNode * node)3109 void HLoopOptimization::PreparePredicateInfoMap(LoopNode* node) {
3110 HLoopInformation* loop_info = node->loop_info;
3111
3112 DCHECK(IsPredicatedLoopControlFlowSupported(loop_info));
3113
3114 for (HBlocksInLoopIterator block_it(*loop_info);
3115 !block_it.Done();
3116 block_it.Advance()) {
3117 HBasicBlock* cur_block = block_it.Current();
3118 BlockPredicateInfo* pred_info = new (loop_allocator_) BlockPredicateInfo();
3119
3120 predicate_info_map_->Put(cur_block, pred_info);
3121 }
3122 }
3123
InitPredicateInfoMap(LoopNode * node,HVecPredSetOperation * loop_main_pred)3124 void HLoopOptimization::InitPredicateInfoMap(LoopNode* node,
3125 HVecPredSetOperation* loop_main_pred) {
3126 HLoopInformation* loop_info = node->loop_info;
3127 HBasicBlock* header = loop_info->GetHeader();
3128 BlockPredicateInfo* header_info = predicate_info_map_->Get(header);
3129 // Loop header is a special case; it doesn't have a false predicate because we
3130 // would just exit the loop then.
3131 header_info->SetControlFlowInfo(loop_main_pred, loop_main_pred);
3132
3133 size_t blocks_in_loop = header->GetLoopInformation()->GetBlocks().NumSetBits();
3134 if (blocks_in_loop == 2) {
3135 for (HBasicBlock* successor : header->GetSuccessors()) {
3136 if (loop_info->Contains(*successor)) {
3137 // This is loop second block - body.
3138 BlockPredicateInfo* body_info = predicate_info_map_->Get(successor);
3139 body_info->SetControlPredicate(loop_main_pred);
3140 return;
3141 }
3142 }
3143 LOG(FATAL) << "Unreachable";
3144 UNREACHABLE();
3145 }
3146
3147 // TODO: support predicated vectorization of CF loop of more complex structure.
3148 DCHECK(HasLoopDiamondStructure(loop_info));
3149 HBasicBlock* header_succ_0 = header->GetSuccessors()[0];
3150 HBasicBlock* header_succ_1 = header->GetSuccessors()[1];
3151 HBasicBlock* diamond_top = loop_info->Contains(*header_succ_0) ?
3152 header_succ_0 :
3153 header_succ_1;
3154
3155 HIf* diamond_hif = diamond_top->GetLastInstruction()->AsIf();
3156 HBasicBlock* diamond_true = diamond_hif->IfTrueSuccessor();
3157 HBasicBlock* diamond_false = diamond_hif->IfFalseSuccessor();
3158 HBasicBlock* back_edge = diamond_true->GetSingleSuccessor();
3159
3160 BlockPredicateInfo* diamond_top_info = predicate_info_map_->Get(diamond_top);
3161 BlockPredicateInfo* diamond_true_info = predicate_info_map_->Get(diamond_true);
3162 BlockPredicateInfo* diamond_false_info = predicate_info_map_->Get(diamond_false);
3163 BlockPredicateInfo* back_edge_info = predicate_info_map_->Get(back_edge);
3164
3165 diamond_top_info->SetControlPredicate(header_info->GetTruePredicate());
3166
3167 diamond_true_info->SetControlPredicate(diamond_top_info->GetTruePredicate());
3168 diamond_false_info->SetControlPredicate(diamond_top_info->GetFalsePredicate());
3169
3170 back_edge_info->SetControlPredicate(header_info->GetTruePredicate());
3171 }
3172
MaybeInsertInVectorExternalSet(HInstruction * instruction)3173 void HLoopOptimization::MaybeInsertInVectorExternalSet(HInstruction* instruction) {
3174 if (IsInPredicatedVectorizationMode()) {
3175 vector_external_set_->insert(instruction);
3176 }
3177 }
3178
operator <<(std::ostream & os,const HLoopOptimization::LoopSynthesisMode & mode)3179 std::ostream& operator<<(std::ostream& os, const HLoopOptimization::LoopSynthesisMode& mode) {
3180 switch (mode) {
3181 case HLoopOptimization::LoopSynthesisMode::kSequential:
3182 return os << "kSequential";
3183 case HLoopOptimization::LoopSynthesisMode::kVector:
3184 return os << "kVector";
3185 }
3186 return os;
3187 }
3188
3189 } // namespace art
3190