LLVM 23.0.0git
LoopIdiomVectorize.cpp
Go to the documentation of this file.
1//===-------- LoopIdiomVectorize.cpp - Loop idiom vectorization -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements a pass that recognizes certain loop idioms and
10// transforms them into more optimized versions of the same loop. In cases
11// where this happens, it can be a significant performance win.
12//
13// We currently support two loops:
14//
15// 1. A loop that finds the first mismatched byte in an array and returns the
16// index, i.e. something like:
17//
18// while (++i != n) {
19// if (a[i] != b[i])
20// break;
21// }
22//
23// In this example we can actually vectorize the loop despite the early exit,
24// although the loop vectorizer does not support it. It requires some extra
25// checks to deal with the possibility of faulting loads when crossing page
26// boundaries. However, even with these checks it is still profitable to do the
27// transformation.
28//
29// TODO List:
30//
31// * Add support for the inverse case where we scan for a matching element.
32// * Permit 64-bit induction variable types.
33// * Recognize loops that increment the IV *after* comparing bytes.
34// * Allow 32-bit sign-extends of the IV used by the GEP.
35//
36// 2. A loop that finds the first matching character in an array among a set of
37// possible matches, e.g.:
38//
39// for (; first != last; ++first)
40// for (s_it = s_first; s_it != s_last; ++s_it)
41// if (*first == *s_it)
42// return first;
43// return last;
44//
45// This corresponds to std::find_first_of (for arrays of bytes) from the C++
46// standard library. This function can be implemented efficiently for targets
47// that support @llvm.experimental.vector.match. For example, on AArch64 targets
48// that implement SVE2, this lower to a MATCH instruction, which enables us to
49// perform up to 16x16=256 comparisons in one go. This can lead to very
50// significant speedups.
51//
52// TODO:
53//
54// * Add support for `find_first_not_of' loops (i.e. with not-equal comparison).
55// * Make VF a configurable parameter (right now we assume 128-bit vectors).
56// * Potentially adjust the cost model to let the transformation kick-in even if
57// @llvm.experimental.vector.match doesn't have direct support in hardware.
58//
59//===----------------------------------------------------------------------===//
60//
61// NOTE: This Pass matches really specific loop patterns because it's only
62// supposed to be a temporary solution until our LoopVectorizer is powerful
63// enough to vectorize them automatically.
64//
65//===----------------------------------------------------------------------===//
66
72#include "llvm/IR/Dominators.h"
73#include "llvm/IR/IRBuilder.h"
74#include "llvm/IR/Intrinsics.h"
75#include "llvm/IR/MDBuilder.h"
79
80using namespace llvm;
81using namespace PatternMatch;
82
83#define DEBUG_TYPE "loop-idiom-vectorize"
84
85static cl::opt<bool> DisableAll("disable-loop-idiom-vectorize-all", cl::Hidden,
86 cl::init(false),
87 cl::desc("Disable Loop Idiom Vectorize Pass."));
88
90 LITVecStyle("loop-idiom-vectorize-style", cl::Hidden,
91 cl::desc("The vectorization style for loop idiom transform."),
93 "Use masked vector intrinsics"),
95 "predicated", "Use VP intrinsics")),
97
98static cl::opt<bool>
99 DisableByteCmp("disable-loop-idiom-vectorize-bytecmp", cl::Hidden,
100 cl::init(false),
101 cl::desc("Proceed with Loop Idiom Vectorize Pass, but do "
102 "not convert byte-compare loop(s)."));
103
105 ByteCmpVF("loop-idiom-vectorize-bytecmp-vf", cl::Hidden,
106 cl::desc("The vectorization factor for byte-compare patterns."),
107 cl::init(16));
108
109static cl::opt<bool>
110 DisableFindFirstByte("disable-loop-idiom-vectorize-find-first-byte",
111 cl::Hidden, cl::init(false),
112 cl::desc("Do not convert find-first-byte loop(s)."));
113
114static cl::opt<bool>
115 VerifyLoops("loop-idiom-vectorize-verify", cl::Hidden, cl::init(false),
116 cl::desc("Verify loops generated Loop Idiom Vectorize Pass."));
117
118namespace {
119class LoopIdiomVectorize {
120 LoopIdiomVectorizeStyle VectorizeStyle;
121 unsigned ByteCompareVF;
122 Loop *CurLoop = nullptr;
123 DominatorTree *DT;
124 LoopInfo *LI;
126 const DataLayout *DL;
127
128 /// Interface to emit optimization remarks.
130
131 // Blocks that will be used for inserting vectorized code.
132 BasicBlock *EndBlock = nullptr;
133 BasicBlock *VectorLoopPreheaderBlock = nullptr;
134 BasicBlock *VectorLoopStartBlock = nullptr;
135 BasicBlock *VectorLoopMismatchBlock = nullptr;
136 BasicBlock *VectorLoopIncBlock = nullptr;
137
138public:
139 LoopIdiomVectorize(LoopIdiomVectorizeStyle S, unsigned VF, DominatorTree *DT,
140 LoopInfo *LI, const TargetTransformInfo *TTI,
142 : VectorizeStyle(S), ByteCompareVF(VF), DT(DT), LI(LI), TTI(TTI), DL(DL),
143 ORE(ORE) {}
144
145 bool run(Loop *L);
146
147private:
148 /// \name Countable Loop Idiom Handling
149 /// @{
150
151 bool runOnCountableLoop();
152 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
153 SmallVectorImpl<BasicBlock *> &ExitBlocks);
154
155 bool recognizeByteCompare();
156
157 Value *expandFindMismatch(IRBuilder<> &Builder, DomTreeUpdater &DTU,
158 GetElementPtrInst *GEPA, GetElementPtrInst *GEPB,
159 Instruction *Index, Value *Start, Value *MaxLen);
160
161 Value *createMaskedFindMismatch(IRBuilder<> &Builder, DomTreeUpdater &DTU,
162 GetElementPtrInst *GEPA,
163 GetElementPtrInst *GEPB, Value *ExtStart,
164 Value *ExtEnd);
165 Value *createPredicatedFindMismatch(IRBuilder<> &Builder, DomTreeUpdater &DTU,
166 GetElementPtrInst *GEPA,
167 GetElementPtrInst *GEPB, Value *ExtStart,
168 Value *ExtEnd);
169
170 void transformByteCompare(GetElementPtrInst *GEPA, GetElementPtrInst *GEPB,
171 PHINode *IndPhi, Value *MaxLen, Instruction *Index,
172 Value *Start, bool IncIdx, BasicBlock *FoundBB,
173 BasicBlock *EndBB);
174
175 bool recognizeFindFirstByte();
176
177 Value *expandFindFirstByte(IRBuilder<> &Builder, DomTreeUpdater &DTU,
178 unsigned VF, Type *CharTy, Value *IndPhi,
179 BasicBlock *ExitSucc, BasicBlock *ExitFail,
180 Value *SearchStart, Value *SearchEnd,
181 Value *NeedleStart, Value *NeedleEnd);
182
183 void transformFindFirstByte(PHINode *IndPhi, unsigned VF, Type *CharTy,
184 BasicBlock *ExitSucc, BasicBlock *ExitFail,
185 Value *SearchStart, Value *SearchEnd,
186 Value *NeedleStart, Value *NeedleEnd);
187 /// @}
188};
189} // anonymous namespace
190
193 LPMUpdater &) {
194 if (DisableAll)
195 return PreservedAnalyses::all();
196
197 const auto *DL = &L.getHeader()->getDataLayout();
198
199 LoopIdiomVectorizeStyle VecStyle = VectorizeStyle;
200 if (LITVecStyle.getNumOccurrences())
201 VecStyle = LITVecStyle;
202
203 unsigned BCVF = ByteCompareVF;
204 if (ByteCmpVF.getNumOccurrences())
205 BCVF = ByteCmpVF;
206
207 Function &F = *L.getHeader()->getParent();
208 auto &FAMP = AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR);
209 auto *ORE = FAMP.getCachedResult<OptimizationRemarkEmitterAnalysis>(F);
210
211 std::optional<OptimizationRemarkEmitter> ORELocal;
212 if (!ORE) {
213 ORELocal.emplace(&F);
214 ORE = &*ORELocal;
215 }
216
217 LoopIdiomVectorize LIV(VecStyle, BCVF, &AR.DT, &AR.LI, &AR.TTI, DL, *ORE);
218 if (!LIV.run(&L))
219 return PreservedAnalyses::all();
220
222}
223
224//===----------------------------------------------------------------------===//
225//
226// Implementation of LoopIdiomVectorize
227//
228//===----------------------------------------------------------------------===//
229
230bool LoopIdiomVectorize::run(Loop *L) {
231 CurLoop = L;
232
233 Function &F = *L->getHeader()->getParent();
234 if (DisableAll || F.hasOptSize())
235 return false;
236
237 // Bail if vectorization is disabled on loop.
238 LoopVectorizeHints Hints(L, /*InterleaveOnlyWhenForced=*/true, ORE);
239 if (!Hints.allowVectorization(&F, L, /*VectorizeOnlyWhenForced=*/false)) {
240 LLVM_DEBUG(dbgs() << DEBUG_TYPE << " is disabled on " << L->getName()
241 << " due to vectorization hints\n");
242 return false;
243 }
244
245 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) {
246 LLVM_DEBUG(dbgs() << DEBUG_TYPE << " is disabled on " << F.getName()
247 << " due to its NoImplicitFloat attribute");
248 return false;
249 }
250
251 // If the loop could not be converted to canonical form, it must have an
252 // indirectbr in it, just give up.
253 if (!L->getLoopPreheader())
254 return false;
255
256 LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F[" << F.getName() << "] Loop %"
257 << CurLoop->getHeader()->getName() << "\n");
258
259 if (recognizeByteCompare())
260 return true;
261
262 if (recognizeFindFirstByte())
263 return true;
264
265 return false;
266}
267
268static void fixSuccessorPhis(Loop *L, Value *ScalarRes, Value *VectorRes,
269 BasicBlock *SuccBB, BasicBlock *IncBB) {
270 for (PHINode &PN : SuccBB->phis()) {
271 // Look through the incoming values to find ScalarRes, meaning this is a
272 // PHI collecting the results of the transformation.
273 bool ResPhi = false;
274 for (Value *Op : PN.incoming_values())
275 if (Op == ScalarRes) {
276 ResPhi = true;
277 break;
278 }
279
280 // Any PHI that depended upon the result of the transformation needs a new
281 // incoming value from IncBB.
282 if (ResPhi)
283 PN.addIncoming(VectorRes, IncBB);
284 else {
285 // There should be no other outside uses of other values in the
286 // original loop. Any incoming values should either:
287 // 1. Be for blocks outside the loop, which aren't interesting. Or ..
288 // 2. These are from blocks in the loop with values defined outside
289 // the loop. We should a similar incoming value from CmpBB.
290 for (BasicBlock *BB : PN.blocks())
291 if (L->contains(BB)) {
292 PN.addIncoming(PN.getIncomingValueForBlock(BB), IncBB);
293 break;
294 }
295 }
296 }
297}
298
299bool LoopIdiomVectorize::recognizeByteCompare() {
300 // Currently the transformation only works on scalable vector types, although
301 // there is no fundamental reason why it cannot be made to work for fixed
302 // width too.
303
304 // We also need to know the minimum page size for the target in order to
305 // generate runtime memory checks to ensure the vector version won't fault.
306 if (!TTI->supportsScalableVectors() || !TTI->getMinPageSize().has_value() ||
308 return false;
309
310 BasicBlock *Header = CurLoop->getHeader();
311
312 // In LoopIdiomVectorize::run we have already checked that the loop
313 // has a preheader so we can assume it's in a canonical form.
314 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 2)
315 return false;
316
317 PHINode *PN = dyn_cast<PHINode>(&Header->front());
318 if (!PN || PN->getNumIncomingValues() != 2)
319 return false;
320
321 auto LoopBlocks = CurLoop->getBlocks();
322 // The first block in the loop should contain only 4 instructions, e.g.
323 //
324 // while.cond:
325 // %res.phi = phi i32 [ %start, %ph ], [ %inc, %while.body ]
326 // %inc = add i32 %res.phi, 1
327 // %cmp.not = icmp eq i32 %inc, %n
328 // br i1 %cmp.not, label %while.end, label %while.body
329 //
330 if (LoopBlocks[0]->size() > 4)
331 return false;
332
333 // The second block should contain 7 instructions, e.g.
334 //
335 // while.body:
336 // %idx = zext i32 %inc to i64
337 // %idx.a = getelementptr inbounds i8, ptr %a, i64 %idx
338 // %load.a = load i8, ptr %idx.a
339 // %idx.b = getelementptr inbounds i8, ptr %b, i64 %idx
340 // %load.b = load i8, ptr %idx.b
341 // %cmp.not.ld = icmp eq i8 %load.a, %load.b
342 // br i1 %cmp.not.ld, label %while.cond, label %while.end
343 //
344 if (LoopBlocks[1]->size() > 7)
345 return false;
346
347 // The incoming value to the PHI node from the loop should be an add of 1.
348 Value *StartIdx = nullptr;
349 Instruction *Index = nullptr;
350 if (!CurLoop->contains(PN->getIncomingBlock(0))) {
351 StartIdx = PN->getIncomingValue(0);
353 } else {
354 StartIdx = PN->getIncomingValue(1);
356 }
357
358 // Limit to 32-bit types for now
359 if (!Index || !Index->getType()->isIntegerTy(32) ||
360 !match(Index, m_c_Add(m_Specific(PN), m_One())))
361 return false;
362
363 // If we match the pattern, PN and Index will be replaced with the result of
364 // the cttz.elts intrinsic. If any other instructions are used outside of
365 // the loop, we cannot replace it.
366 for (BasicBlock *BB : LoopBlocks)
367 for (Instruction &I : *BB)
368 if (&I != PN && &I != Index)
369 for (User *U : I.users())
370 if (!CurLoop->contains(cast<Instruction>(U)))
371 return false;
372
373 // Match the branch instruction for the header
374 Value *MaxLen;
375 BasicBlock *EndBB, *WhileBB;
376 if (!match(Header->getTerminator(),
378 m_Value(MaxLen)),
379 m_BasicBlock(EndBB), m_BasicBlock(WhileBB))) ||
380 !CurLoop->contains(WhileBB))
381 return false;
382
383 // WhileBB should contain the pattern of load & compare instructions. Match
384 // the pattern and find the GEP instructions used by the loads.
385 BasicBlock *FoundBB;
386 BasicBlock *TrueBB;
387 Value *LoadA, *LoadB;
388 if (!match(WhileBB->getTerminator(),
390 m_Value(LoadB)),
391 m_BasicBlock(TrueBB), m_BasicBlock(FoundBB))) ||
392 !CurLoop->contains(TrueBB))
393 return false;
394
395 Value *A, *B;
396 if (!match(LoadA, m_Load(m_Value(A))) || !match(LoadB, m_Load(m_Value(B))))
397 return false;
398
399 LoadInst *LoadAI = cast<LoadInst>(LoadA);
400 LoadInst *LoadBI = cast<LoadInst>(LoadB);
401 if (!LoadAI->isSimple() || !LoadBI->isSimple())
402 return false;
403
406
407 if (!GEPA || !GEPB)
408 return false;
409
410 Value *PtrA = GEPA->getPointerOperand();
411 Value *PtrB = GEPB->getPointerOperand();
412
413 // Check we are loading i8 values from two loop invariant pointers
414 if (!CurLoop->isLoopInvariant(PtrA) || !CurLoop->isLoopInvariant(PtrB) ||
415 !GEPA->getResultElementType()->isIntegerTy(8) ||
416 !GEPB->getResultElementType()->isIntegerTy(8) ||
417 !LoadAI->getType()->isIntegerTy(8) ||
418 !LoadBI->getType()->isIntegerTy(8) || PtrA == PtrB)
419 return false;
420
421 // Check that the index to the GEPs is the index we found earlier
422 if (GEPA->getNumIndices() > 1 || GEPB->getNumIndices() > 1)
423 return false;
424
425 Value *IdxA = GEPA->getOperand(GEPA->getNumIndices());
426 Value *IdxB = GEPB->getOperand(GEPB->getNumIndices());
427 if (IdxA != IdxB || !match(IdxA, m_ZExt(m_Specific(Index))))
428 return false;
429
430 // We only ever expect the pre-incremented index value to be used inside the
431 // loop.
432 if (!PN->hasOneUse())
433 return false;
434
435 // Ensure that when the Found and End blocks are identical the PHIs have the
436 // supported format. We don't currently allow cases like this:
437 // while.cond:
438 // ...
439 // br i1 %cmp.not, label %while.end, label %while.body
440 //
441 // while.body:
442 // ...
443 // br i1 %cmp.not2, label %while.cond, label %while.end
444 //
445 // while.end:
446 // %final_ptr = phi ptr [ %c, %while.body ], [ %d, %while.cond ]
447 //
448 // Where the incoming values for %final_ptr are unique and from each of the
449 // loop blocks, but not actually defined in the loop. This requires extra
450 // work setting up the byte.compare block, i.e. by introducing a select to
451 // choose the correct value.
452 // TODO: We could add support for this in future.
453 if (FoundBB == EndBB) {
454 for (PHINode &EndPN : EndBB->phis()) {
455 Value *WhileCondVal = EndPN.getIncomingValueForBlock(Header);
456 Value *WhileBodyVal = EndPN.getIncomingValueForBlock(WhileBB);
457
458 // The value of the index when leaving the while.cond block is always the
459 // same as the end value (MaxLen) so we permit either. The value when
460 // leaving the while.body block should only be the index. Otherwise for
461 // any other values we only allow ones that are same for both blocks.
462 if (WhileCondVal != WhileBodyVal &&
463 ((WhileCondVal != Index && WhileCondVal != MaxLen) ||
464 (WhileBodyVal != Index)))
465 return false;
466 }
467 }
468
469 LLVM_DEBUG(dbgs() << "FOUND IDIOM IN LOOP: \n"
470 << *(EndBB->getParent()) << "\n\n");
471
472 // The index is incremented before the GEP/Load pair so we need to
473 // add 1 to the start value.
474 transformByteCompare(GEPA, GEPB, PN, MaxLen, Index, StartIdx, /*IncIdx=*/true,
475 FoundBB, EndBB);
476 return true;
477}
478
479Value *LoopIdiomVectorize::createMaskedFindMismatch(
480 IRBuilder<> &Builder, DomTreeUpdater &DTU, GetElementPtrInst *GEPA,
481 GetElementPtrInst *GEPB, Value *ExtStart, Value *ExtEnd) {
482 Type *I64Type = Builder.getInt64Ty();
483 Type *ResType = Builder.getInt32Ty();
484 Type *LoadType = Builder.getInt8Ty();
485 Value *PtrA = GEPA->getPointerOperand();
486 Value *PtrB = GEPB->getPointerOperand();
487
488 ScalableVectorType *PredVTy =
489 ScalableVectorType::get(Builder.getInt1Ty(), ByteCompareVF);
490
491 Value *InitialPred = Builder.CreateIntrinsic(
492 Intrinsic::get_active_lane_mask, {PredVTy, I64Type}, {ExtStart, ExtEnd});
493
494 Value *VecLen = Builder.CreateVScale(I64Type);
495 VecLen =
496 Builder.CreateMul(VecLen, ConstantInt::get(I64Type, ByteCompareVF), "",
497 /*HasNUW=*/true, /*HasNSW=*/true);
498
499 Value *PFalse = Builder.CreateVectorSplat(PredVTy->getElementCount(),
500 Builder.getInt1(false));
501
502 Builder.CreateBr(VectorLoopStartBlock);
503
504 DTU.applyUpdates({{DominatorTree::Insert, VectorLoopPreheaderBlock,
505 VectorLoopStartBlock}});
506
507 // Set up the first vector loop block by creating the PHIs, doing the vector
508 // loads and comparing the vectors.
509 Builder.SetInsertPoint(VectorLoopStartBlock);
510 PHINode *LoopPred = Builder.CreatePHI(PredVTy, 2, "mismatch_vec_loop_pred");
511 LoopPred->addIncoming(InitialPred, VectorLoopPreheaderBlock);
512 PHINode *VectorIndexPhi = Builder.CreatePHI(I64Type, 2, "mismatch_vec_index");
513 VectorIndexPhi->addIncoming(ExtStart, VectorLoopPreheaderBlock);
514 Type *VectorLoadType =
515 ScalableVectorType::get(Builder.getInt8Ty(), ByteCompareVF);
516 Value *Passthru = ConstantInt::getNullValue(VectorLoadType);
517
518 Value *VectorLhsGep =
519 Builder.CreateGEP(LoadType, PtrA, VectorIndexPhi, "", GEPA->isInBounds());
520 Value *VectorLhsLoad = Builder.CreateMaskedLoad(VectorLoadType, VectorLhsGep,
521 Align(1), LoopPred, Passthru);
522
523 Value *VectorRhsGep =
524 Builder.CreateGEP(LoadType, PtrB, VectorIndexPhi, "", GEPB->isInBounds());
525 Value *VectorRhsLoad = Builder.CreateMaskedLoad(VectorLoadType, VectorRhsGep,
526 Align(1), LoopPred, Passthru);
527
528 Value *VectorMatchCmp = Builder.CreateICmpNE(VectorLhsLoad, VectorRhsLoad);
529 VectorMatchCmp = Builder.CreateSelect(LoopPred, VectorMatchCmp, PFalse);
530 Value *VectorMatchHasActiveLanes = Builder.CreateOrReduce(VectorMatchCmp);
531 Builder.CreateCondBr(VectorMatchHasActiveLanes, VectorLoopMismatchBlock,
532 VectorLoopIncBlock);
533
534 DTU.applyUpdates(
535 {{DominatorTree::Insert, VectorLoopStartBlock, VectorLoopMismatchBlock},
536 {DominatorTree::Insert, VectorLoopStartBlock, VectorLoopIncBlock}});
537
538 // Increment the index counter and calculate the predicate for the next
539 // iteration of the loop. We branch back to the start of the loop if there
540 // is at least one active lane.
541 Builder.SetInsertPoint(VectorLoopIncBlock);
542 Value *NewVectorIndexPhi =
543 Builder.CreateAdd(VectorIndexPhi, VecLen, "",
544 /*HasNUW=*/true, /*HasNSW=*/true);
545 VectorIndexPhi->addIncoming(NewVectorIndexPhi, VectorLoopIncBlock);
546 Value *NewPred =
547 Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
548 {PredVTy, I64Type}, {NewVectorIndexPhi, ExtEnd});
549 LoopPred->addIncoming(NewPred, VectorLoopIncBlock);
550
551 Value *PredHasActiveLanes =
552 Builder.CreateExtractElement(NewPred, uint64_t(0));
553 Builder.CreateCondBr(PredHasActiveLanes, VectorLoopStartBlock, EndBlock);
554
555 DTU.applyUpdates(
556 {{DominatorTree::Insert, VectorLoopIncBlock, VectorLoopStartBlock},
557 {DominatorTree::Insert, VectorLoopIncBlock, EndBlock}});
558
559 // If we found a mismatch then we need to calculate which lane in the vector
560 // had a mismatch and add that on to the current loop index.
561 Builder.SetInsertPoint(VectorLoopMismatchBlock);
562 PHINode *FoundPred = Builder.CreatePHI(PredVTy, 1, "mismatch_vec_found_pred");
563 FoundPred->addIncoming(VectorMatchCmp, VectorLoopStartBlock);
564 PHINode *LastLoopPred =
565 Builder.CreatePHI(PredVTy, 1, "mismatch_vec_last_loop_pred");
566 LastLoopPred->addIncoming(LoopPred, VectorLoopStartBlock);
567 PHINode *VectorFoundIndex =
568 Builder.CreatePHI(I64Type, 1, "mismatch_vec_found_index");
569 VectorFoundIndex->addIncoming(VectorIndexPhi, VectorLoopStartBlock);
570
571 Value *PredMatchCmp = Builder.CreateAnd(LastLoopPred, FoundPred);
572 Value *Ctz = Builder.CreateCountTrailingZeroElems(ResType, PredMatchCmp);
573 Ctz = Builder.CreateZExt(Ctz, I64Type);
574 Value *VectorLoopRes64 = Builder.CreateAdd(VectorFoundIndex, Ctz, "",
575 /*HasNUW=*/true, /*HasNSW=*/true);
576 return Builder.CreateTrunc(VectorLoopRes64, ResType);
577}
578
579Value *LoopIdiomVectorize::createPredicatedFindMismatch(
580 IRBuilder<> &Builder, DomTreeUpdater &DTU, GetElementPtrInst *GEPA,
581 GetElementPtrInst *GEPB, Value *ExtStart, Value *ExtEnd) {
582 Type *I64Type = Builder.getInt64Ty();
583 Type *I32Type = Builder.getInt32Ty();
584 Type *ResType = I32Type;
585 Type *LoadType = Builder.getInt8Ty();
586 Value *PtrA = GEPA->getPointerOperand();
587 Value *PtrB = GEPB->getPointerOperand();
588
589 auto *JumpToVectorLoop = UncondBrInst::Create(VectorLoopStartBlock);
590 Builder.Insert(JumpToVectorLoop);
591
592 DTU.applyUpdates({{DominatorTree::Insert, VectorLoopPreheaderBlock,
593 VectorLoopStartBlock}});
594
595 // Set up the first Vector loop block by creating the PHIs, doing the vector
596 // loads and comparing the vectors.
597 Builder.SetInsertPoint(VectorLoopStartBlock);
598 auto *VectorIndexPhi = Builder.CreatePHI(I64Type, 2, "mismatch_vector_index");
599 VectorIndexPhi->addIncoming(ExtStart, VectorLoopPreheaderBlock);
600
601 // Calculate AVL by subtracting the vector loop index from the trip count
602 Value *AVL = Builder.CreateSub(ExtEnd, VectorIndexPhi, "avl", /*HasNUW=*/true,
603 /*HasNSW=*/true);
604
605 auto *VectorLoadType = ScalableVectorType::get(LoadType, ByteCompareVF);
606 auto *VF = ConstantInt::get(I32Type, ByteCompareVF);
607
608 Value *VL = Builder.CreateIntrinsic(Intrinsic::experimental_get_vector_length,
609 {I64Type}, {AVL, VF, Builder.getTrue()});
610 Value *GepOffset = VectorIndexPhi;
611
612 Value *VectorLhsGep =
613 Builder.CreateGEP(LoadType, PtrA, GepOffset, "", GEPA->isInBounds());
614 VectorType *TrueMaskTy =
615 VectorType::get(Builder.getInt1Ty(), VectorLoadType->getElementCount());
616 Value *AllTrueMask = Constant::getAllOnesValue(TrueMaskTy);
617 Value *VectorLhsLoad = Builder.CreateIntrinsic(
618 Intrinsic::vp_load, {VectorLoadType, VectorLhsGep->getType()},
619 {VectorLhsGep, AllTrueMask, VL}, nullptr, "lhs.load");
620
621 Value *VectorRhsGep =
622 Builder.CreateGEP(LoadType, PtrB, GepOffset, "", GEPB->isInBounds());
623 Value *VectorRhsLoad = Builder.CreateIntrinsic(
624 Intrinsic::vp_load, {VectorLoadType, VectorLhsGep->getType()},
625 {VectorRhsGep, AllTrueMask, VL}, nullptr, "rhs.load");
626
627 Value *VectorMatchCmp =
628 Builder.CreateICmpNE(VectorLhsLoad, VectorRhsLoad, "mismatch.cmp");
629 Value *CTZ = Builder.CreateIntrinsic(
630 Intrinsic::vp_cttz_elts, {ResType, VectorMatchCmp->getType()},
631 {VectorMatchCmp, /*ZeroIsPoison=*/Builder.getInt1(false), AllTrueMask,
632 VL});
633 Value *MismatchFound = Builder.CreateICmpNE(CTZ, VL);
634 auto *VectorEarlyExit = CondBrInst::Create(
635 MismatchFound, VectorLoopMismatchBlock, VectorLoopIncBlock);
636 Builder.Insert(VectorEarlyExit);
637
638 DTU.applyUpdates(
639 {{DominatorTree::Insert, VectorLoopStartBlock, VectorLoopMismatchBlock},
640 {DominatorTree::Insert, VectorLoopStartBlock, VectorLoopIncBlock}});
641
642 // Increment the index counter and calculate the predicate for the next
643 // iteration of the loop. We branch back to the start of the loop if there
644 // is at least one active lane.
645 Builder.SetInsertPoint(VectorLoopIncBlock);
646 Value *VL64 = Builder.CreateZExt(VL, I64Type);
647 Value *NewVectorIndexPhi =
648 Builder.CreateAdd(VectorIndexPhi, VL64, "",
649 /*HasNUW=*/true, /*HasNSW=*/true);
650 VectorIndexPhi->addIncoming(NewVectorIndexPhi, VectorLoopIncBlock);
651 Value *ExitCond = Builder.CreateICmpNE(NewVectorIndexPhi, ExtEnd);
652 auto *VectorLoopBranchBack =
653 CondBrInst::Create(ExitCond, VectorLoopStartBlock, EndBlock);
654 Builder.Insert(VectorLoopBranchBack);
655
656 DTU.applyUpdates(
657 {{DominatorTree::Insert, VectorLoopIncBlock, VectorLoopStartBlock},
658 {DominatorTree::Insert, VectorLoopIncBlock, EndBlock}});
659
660 // If we found a mismatch then we need to calculate which lane in the vector
661 // had a mismatch and add that on to the current loop index.
662 Builder.SetInsertPoint(VectorLoopMismatchBlock);
663
664 // Add LCSSA phis for CTZ and VectorIndexPhi.
665 auto *CTZLCSSAPhi = Builder.CreatePHI(CTZ->getType(), 1, "ctz");
666 CTZLCSSAPhi->addIncoming(CTZ, VectorLoopStartBlock);
667 auto *VectorIndexLCSSAPhi =
668 Builder.CreatePHI(VectorIndexPhi->getType(), 1, "mismatch_vector_index");
669 VectorIndexLCSSAPhi->addIncoming(VectorIndexPhi, VectorLoopStartBlock);
670
671 Value *CTZI64 = Builder.CreateZExt(CTZLCSSAPhi, I64Type);
672 Value *VectorLoopRes64 = Builder.CreateAdd(VectorIndexLCSSAPhi, CTZI64, "",
673 /*HasNUW=*/true, /*HasNSW=*/true);
674 return Builder.CreateTrunc(VectorLoopRes64, ResType);
675}
676
677Value *LoopIdiomVectorize::expandFindMismatch(
678 IRBuilder<> &Builder, DomTreeUpdater &DTU, GetElementPtrInst *GEPA,
679 GetElementPtrInst *GEPB, Instruction *Index, Value *Start, Value *MaxLen) {
680 Value *PtrA = GEPA->getPointerOperand();
681 Value *PtrB = GEPB->getPointerOperand();
682
683 // Get the arguments and types for the intrinsic.
684 BasicBlock *Preheader = CurLoop->getLoopPreheader();
685 Instruction *PHBranch = Preheader->getTerminator();
686 LLVMContext &Ctx = PHBranch->getContext();
687 Type *LoadType = Type::getInt8Ty(Ctx);
688 Type *ResType = Builder.getInt32Ty();
689
690 // Split block in the original loop preheader.
691 EndBlock = SplitBlock(Preheader, PHBranch, DT, LI, nullptr, "mismatch_end");
692
693 // Create the blocks that we're going to need:
694 // 1. A block for checking the zero-extended length exceeds 0
695 // 2. A block to check that the start and end addresses of a given array
696 // lie on the same page.
697 // 3. The vector loop preheader.
698 // 4. The first vector loop block.
699 // 5. The vector loop increment block.
700 // 6. A block we can jump to from the vector loop when a mismatch is found.
701 // 7. The first block of the scalar loop itself, containing PHIs , loads
702 // and cmp.
703 // 8. A scalar loop increment block to increment the PHIs and go back
704 // around the loop.
705
706 BasicBlock *MinItCheckBlock = BasicBlock::Create(
707 Ctx, "mismatch_min_it_check", EndBlock->getParent(), EndBlock);
708
709 // Update the terminator added by SplitBlock to branch to the first block
710 Preheader->getTerminator()->setSuccessor(0, MinItCheckBlock);
711
712 BasicBlock *MemCheckBlock = BasicBlock::Create(
713 Ctx, "mismatch_mem_check", EndBlock->getParent(), EndBlock);
714
715 VectorLoopPreheaderBlock = BasicBlock::Create(
716 Ctx, "mismatch_vec_loop_preheader", EndBlock->getParent(), EndBlock);
717
718 VectorLoopStartBlock = BasicBlock::Create(Ctx, "mismatch_vec_loop",
719 EndBlock->getParent(), EndBlock);
720
721 VectorLoopIncBlock = BasicBlock::Create(Ctx, "mismatch_vec_loop_inc",
722 EndBlock->getParent(), EndBlock);
723
724 VectorLoopMismatchBlock = BasicBlock::Create(Ctx, "mismatch_vec_loop_found",
725 EndBlock->getParent(), EndBlock);
726
727 BasicBlock *LoopPreHeaderBlock = BasicBlock::Create(
728 Ctx, "mismatch_loop_pre", EndBlock->getParent(), EndBlock);
729
730 BasicBlock *LoopStartBlock =
731 BasicBlock::Create(Ctx, "mismatch_loop", EndBlock->getParent(), EndBlock);
732
733 BasicBlock *LoopIncBlock = BasicBlock::Create(
734 Ctx, "mismatch_loop_inc", EndBlock->getParent(), EndBlock);
735
736 DTU.applyUpdates({{DominatorTree::Insert, Preheader, MinItCheckBlock},
737 {DominatorTree::Delete, Preheader, EndBlock}});
738
739 // Update LoopInfo with the new vector & scalar loops.
740 auto VectorLoop = LI->AllocateLoop();
741 auto ScalarLoop = LI->AllocateLoop();
742
743 if (CurLoop->getParentLoop()) {
744 CurLoop->getParentLoop()->addBasicBlockToLoop(MinItCheckBlock, *LI);
745 CurLoop->getParentLoop()->addBasicBlockToLoop(MemCheckBlock, *LI);
746 CurLoop->getParentLoop()->addBasicBlockToLoop(VectorLoopPreheaderBlock,
747 *LI);
748 CurLoop->getParentLoop()->addChildLoop(VectorLoop);
749 CurLoop->getParentLoop()->addBasicBlockToLoop(VectorLoopMismatchBlock, *LI);
750 CurLoop->getParentLoop()->addBasicBlockToLoop(LoopPreHeaderBlock, *LI);
751 CurLoop->getParentLoop()->addChildLoop(ScalarLoop);
752 } else {
753 LI->addTopLevelLoop(VectorLoop);
754 LI->addTopLevelLoop(ScalarLoop);
755 }
756
757 // Add the new basic blocks to their associated loops.
758 VectorLoop->addBasicBlockToLoop(VectorLoopStartBlock, *LI);
759 VectorLoop->addBasicBlockToLoop(VectorLoopIncBlock, *LI);
760
761 ScalarLoop->addBasicBlockToLoop(LoopStartBlock, *LI);
762 ScalarLoop->addBasicBlockToLoop(LoopIncBlock, *LI);
763
764 // Set up some types and constants that we intend to reuse.
765 Type *I64Type = Builder.getInt64Ty();
766
767 // Check the zero-extended iteration count > 0
768 Builder.SetInsertPoint(MinItCheckBlock);
769 Value *ExtStart = Builder.CreateZExt(Start, I64Type);
770 Value *ExtEnd = Builder.CreateZExt(MaxLen, I64Type);
771 // This check doesn't really cost us very much.
772
773 Value *LimitCheck = Builder.CreateICmpULE(Start, MaxLen);
774 CondBrInst *MinItCheckBr =
775 CondBrInst::Create(LimitCheck, MemCheckBlock, LoopPreHeaderBlock);
776 MinItCheckBr->setMetadata(
777 LLVMContext::MD_prof,
778 MDBuilder(MinItCheckBr->getContext()).createBranchWeights(99, 1));
779 Builder.Insert(MinItCheckBr);
780
781 DTU.applyUpdates(
782 {{DominatorTree::Insert, MinItCheckBlock, MemCheckBlock},
783 {DominatorTree::Insert, MinItCheckBlock, LoopPreHeaderBlock}});
784
785 // For each of the arrays, check the start/end addresses are on the same
786 // page.
787 Builder.SetInsertPoint(MemCheckBlock);
788
789 // The early exit in the original loop means that when performing vector
790 // loads we are potentially reading ahead of the early exit. So we could
791 // fault if crossing a page boundary. Therefore, we create runtime memory
792 // checks based on the minimum page size as follows:
793 // 1. Calculate the addresses of the first memory accesses in the loop,
794 // i.e. LhsStart and RhsStart.
795 // 2. Get the last accessed addresses in the loop, i.e. LhsEnd and RhsEnd.
796 // 3. Determine which pages correspond to all the memory accesses, i.e
797 // LhsStartPage, LhsEndPage, RhsStartPage, RhsEndPage.
798 // 4. If LhsStartPage == LhsEndPage and RhsStartPage == RhsEndPage, then
799 // we know we won't cross any page boundaries in the loop so we can
800 // enter the vector loop! Otherwise we fall back on the scalar loop.
801 Value *LhsStartGEP = Builder.CreateGEP(LoadType, PtrA, ExtStart);
802 Value *RhsStartGEP = Builder.CreateGEP(LoadType, PtrB, ExtStart);
803 Value *RhsStart = Builder.CreatePtrToInt(RhsStartGEP, I64Type);
804 Value *LhsStart = Builder.CreatePtrToInt(LhsStartGEP, I64Type);
805 Value *LhsEndGEP = Builder.CreateGEP(LoadType, PtrA, ExtEnd);
806 Value *RhsEndGEP = Builder.CreateGEP(LoadType, PtrB, ExtEnd);
807 Value *LhsEnd = Builder.CreatePtrToInt(LhsEndGEP, I64Type);
808 Value *RhsEnd = Builder.CreatePtrToInt(RhsEndGEP, I64Type);
809
810 const uint64_t MinPageSize = TTI->getMinPageSize().value();
811 const uint64_t AddrShiftAmt = llvm::Log2_64(MinPageSize);
812 Value *LhsStartPage = Builder.CreateLShr(LhsStart, AddrShiftAmt);
813 Value *LhsEndPage = Builder.CreateLShr(LhsEnd, AddrShiftAmt);
814 Value *RhsStartPage = Builder.CreateLShr(RhsStart, AddrShiftAmt);
815 Value *RhsEndPage = Builder.CreateLShr(RhsEnd, AddrShiftAmt);
816 Value *LhsPageCmp = Builder.CreateICmpNE(LhsStartPage, LhsEndPage);
817 Value *RhsPageCmp = Builder.CreateICmpNE(RhsStartPage, RhsEndPage);
818
819 Value *CombinedPageCmp = Builder.CreateOr(LhsPageCmp, RhsPageCmp);
820 CondBrInst *CombinedPageCmpCmpBr = CondBrInst::Create(
821 CombinedPageCmp, LoopPreHeaderBlock, VectorLoopPreheaderBlock);
822 CombinedPageCmpCmpBr->setMetadata(
823 LLVMContext::MD_prof, MDBuilder(CombinedPageCmpCmpBr->getContext())
824 .createBranchWeights(10, 90));
825 Builder.Insert(CombinedPageCmpCmpBr);
826
827 DTU.applyUpdates(
828 {{DominatorTree::Insert, MemCheckBlock, LoopPreHeaderBlock},
829 {DominatorTree::Insert, MemCheckBlock, VectorLoopPreheaderBlock}});
830
831 // Set up the vector loop preheader, i.e. calculate initial loop predicate,
832 // zero-extend MaxLen to 64-bits, determine the number of vector elements
833 // processed in each iteration, etc.
834 Builder.SetInsertPoint(VectorLoopPreheaderBlock);
835
836 // At this point we know two things must be true:
837 // 1. Start <= End
838 // 2. ExtMaxLen <= MinPageSize due to the page checks.
839 // Therefore, we know that we can use a 64-bit induction variable that
840 // starts from 0 -> ExtMaxLen and it will not overflow.
841 Value *VectorLoopRes = nullptr;
842 switch (VectorizeStyle) {
844 VectorLoopRes =
845 createMaskedFindMismatch(Builder, DTU, GEPA, GEPB, ExtStart, ExtEnd);
846 break;
848 VectorLoopRes = createPredicatedFindMismatch(Builder, DTU, GEPA, GEPB,
849 ExtStart, ExtEnd);
850 break;
851 }
852
853 Builder.CreateBr(EndBlock);
854
855 DTU.applyUpdates(
856 {{DominatorTree::Insert, VectorLoopMismatchBlock, EndBlock}});
857
858 // Generate code for scalar loop.
859 Builder.SetInsertPoint(LoopPreHeaderBlock);
860 Builder.CreateBr(LoopStartBlock);
861
862 DTU.applyUpdates(
863 {{DominatorTree::Insert, LoopPreHeaderBlock, LoopStartBlock}});
864
865 Builder.SetInsertPoint(LoopStartBlock);
866 PHINode *IndexPhi = Builder.CreatePHI(ResType, 2, "mismatch_index");
867 IndexPhi->addIncoming(Start, LoopPreHeaderBlock);
868
869 // Otherwise compare the values
870 // Load bytes from each array and compare them.
871 Value *GepOffset = Builder.CreateZExt(IndexPhi, I64Type);
872
873 Value *LhsGep =
874 Builder.CreateGEP(LoadType, PtrA, GepOffset, "", GEPA->isInBounds());
875 Value *LhsLoad = Builder.CreateLoad(LoadType, LhsGep);
876
877 Value *RhsGep =
878 Builder.CreateGEP(LoadType, PtrB, GepOffset, "", GEPB->isInBounds());
879 Value *RhsLoad = Builder.CreateLoad(LoadType, RhsGep);
880
881 Value *MatchCmp = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
882 // If we have a mismatch then exit the loop ...
883 Builder.CreateCondBr(MatchCmp, LoopIncBlock, EndBlock);
884
885 DTU.applyUpdates({{DominatorTree::Insert, LoopStartBlock, LoopIncBlock},
886 {DominatorTree::Insert, LoopStartBlock, EndBlock}});
887
888 // Have we reached the maximum permitted length for the loop?
889 Builder.SetInsertPoint(LoopIncBlock);
890 Value *PhiInc = Builder.CreateAdd(IndexPhi, ConstantInt::get(ResType, 1), "",
891 /*HasNUW=*/Index->hasNoUnsignedWrap(),
892 /*HasNSW=*/Index->hasNoSignedWrap());
893 IndexPhi->addIncoming(PhiInc, LoopIncBlock);
894 Value *IVCmp = Builder.CreateICmpEQ(PhiInc, MaxLen);
895 Builder.CreateCondBr(IVCmp, EndBlock, LoopStartBlock);
896
897 DTU.applyUpdates({{DominatorTree::Insert, LoopIncBlock, EndBlock},
898 {DominatorTree::Insert, LoopIncBlock, LoopStartBlock}});
899
900 // In the end block we need to insert a PHI node to deal with three cases:
901 // 1. We didn't find a mismatch in the scalar loop, so we return MaxLen.
902 // 2. We exitted the scalar loop early due to a mismatch and need to return
903 // the index that we found.
904 // 3. We didn't find a mismatch in the vector loop, so we return MaxLen.
905 // 4. We exitted the vector loop early due to a mismatch and need to return
906 // the index that we found.
907 Builder.SetInsertPoint(EndBlock, EndBlock->getFirstInsertionPt());
908 PHINode *ResPhi = Builder.CreatePHI(ResType, 4, "mismatch_result");
909 ResPhi->addIncoming(MaxLen, LoopIncBlock);
910 ResPhi->addIncoming(IndexPhi, LoopStartBlock);
911 ResPhi->addIncoming(MaxLen, VectorLoopIncBlock);
912 ResPhi->addIncoming(VectorLoopRes, VectorLoopMismatchBlock);
913
914 Value *FinalRes = Builder.CreateTrunc(ResPhi, ResType);
915
916 if (VerifyLoops) {
917 ScalarLoop->verifyLoop();
918 VectorLoop->verifyLoop();
919 if (!VectorLoop->isRecursivelyLCSSAForm(*DT, *LI))
920 report_fatal_error("Loops must remain in LCSSA form!");
921 if (!ScalarLoop->isRecursivelyLCSSAForm(*DT, *LI))
922 report_fatal_error("Loops must remain in LCSSA form!");
923 }
924
925 return FinalRes;
926}
927
928void LoopIdiomVectorize::transformByteCompare(GetElementPtrInst *GEPA,
929 GetElementPtrInst *GEPB,
930 PHINode *IndPhi, Value *MaxLen,
931 Instruction *Index, Value *Start,
932 bool IncIdx, BasicBlock *FoundBB,
933 BasicBlock *EndBB) {
934
935 // Insert the byte compare code at the end of the preheader block
936 BasicBlock *Preheader = CurLoop->getLoopPreheader();
937 BasicBlock *Header = CurLoop->getHeader();
938 UncondBrInst *PHBranch = cast<UncondBrInst>(Preheader->getTerminator());
939 IRBuilder<> Builder(PHBranch);
940 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
941 Builder.SetCurrentDebugLocation(PHBranch->getDebugLoc());
942
943 // Increment the pointer if this was done before the loads in the loop.
944 if (IncIdx)
945 Start = Builder.CreateAdd(Start, ConstantInt::get(Start->getType(), 1));
946
947 Value *ByteCmpRes =
948 expandFindMismatch(Builder, DTU, GEPA, GEPB, Index, Start, MaxLen);
949
950 // Replaces uses of index & induction Phi with intrinsic (we already
951 // checked that the the first instruction of Header is the Phi above).
952 assert(IndPhi->hasOneUse() && "Index phi node has more than one use!");
953 Index->replaceAllUsesWith(ByteCmpRes);
954
955 // If no mismatch was found, we can jump to the end block. Create a
956 // new basic block for the compare instruction.
957 auto *CmpBB = BasicBlock::Create(Preheader->getContext(), "byte.compare",
958 Preheader->getParent());
959 CmpBB->moveBefore(EndBB);
960
961 // Replace the branch in the preheader with an always-true conditional branch.
962 // This ensures there is still a reference to the original loop.
963 Builder.CreateCondBr(Builder.getTrue(), CmpBB, Header);
964 PHBranch->eraseFromParent();
965
966 BasicBlock *MismatchEnd = cast<Instruction>(ByteCmpRes)->getParent();
967 DTU.applyUpdates({{DominatorTree::Insert, MismatchEnd, CmpBB}});
968
969 // Create the branch to either the end or found block depending on the value
970 // returned by the intrinsic.
971 Builder.SetInsertPoint(CmpBB);
972 if (FoundBB != EndBB) {
973 Value *FoundCmp = Builder.CreateICmpEQ(ByteCmpRes, MaxLen);
974 Builder.CreateCondBr(FoundCmp, EndBB, FoundBB);
975 DTU.applyUpdates({{DominatorTree::Insert, CmpBB, FoundBB},
976 {DominatorTree::Insert, CmpBB, EndBB}});
977
978 } else {
979 Builder.CreateBr(FoundBB);
980 DTU.applyUpdates({{DominatorTree::Insert, CmpBB, FoundBB}});
981 }
982
983 // Ensure all Phis in the successors of CmpBB have an incoming value from it.
984 fixSuccessorPhis(CurLoop, ByteCmpRes, ByteCmpRes, EndBB, CmpBB);
985 if (EndBB != FoundBB)
986 fixSuccessorPhis(CurLoop, ByteCmpRes, ByteCmpRes, FoundBB, CmpBB);
987
988 // The new CmpBB block isn't part of the loop, but will need to be added to
989 // the outer loop if there is one.
990 if (!CurLoop->isOutermost())
991 CurLoop->getParentLoop()->addBasicBlockToLoop(CmpBB, *LI);
992
993 if (VerifyLoops && CurLoop->getParentLoop()) {
994 CurLoop->getParentLoop()->verifyLoop();
995 if (!CurLoop->getParentLoop()->isRecursivelyLCSSAForm(*DT, *LI))
996 report_fatal_error("Loops must remain in LCSSA form!");
997 }
998}
999
1000bool LoopIdiomVectorize::recognizeFindFirstByte() {
1001 // Currently the transformation only works on scalable vector types, although
1002 // there is no fundamental reason why it cannot be made to work for fixed
1003 // vectors. We also need to know the target's minimum page size in order to
1004 // generate runtime memory checks to ensure the vector version won't fault.
1005 if (!TTI->supportsScalableVectors() || !TTI->getMinPageSize().has_value() ||
1007 return false;
1008
1009 // We exclude loops with trip counts > minimum page size via runtime checks,
1010 // so make sure that the minimum page size is something sensible such that
1011 // induction variables cannot overflow.
1012 if (uint64_t(*TTI->getMinPageSize()) >
1013 (std::numeric_limits<uint64_t>::max() / 2))
1014 return false;
1015
1016 // Define some constants we need throughout.
1017 BasicBlock *Header = CurLoop->getHeader();
1018 LLVMContext &Ctx = Header->getContext();
1019
1020 // We are expecting the four blocks defined below: Header, MatchBB, InnerBB,
1021 // and OuterBB. For now, we will bail our for almost anything else. The Four
1022 // blocks contain one nested loop.
1023 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 4 ||
1024 CurLoop->getSubLoops().size() != 1)
1025 return false;
1026
1027 auto *InnerLoop = CurLoop->getSubLoops().front();
1028 Function &F = *InnerLoop->getHeader()->getParent();
1029
1030 // Bail if vectorization is disabled on inner loop.
1031 LoopVectorizeHints Hints(InnerLoop, /*InterleaveOnlyWhenForced=*/true, ORE);
1032 if (!Hints.allowVectorization(&F, InnerLoop,
1033 /*VectorizeOnlyWhenForced=*/false)) {
1034 LLVM_DEBUG(dbgs() << DEBUG_TYPE << " is disabled on inner loop "
1035 << InnerLoop->getName()
1036 << " due to vectorization hints\n");
1037 return false;
1038 }
1039
1040 PHINode *IndPhi = dyn_cast<PHINode>(&Header->front());
1041 if (!IndPhi || IndPhi->getNumIncomingValues() != 2)
1042 return false;
1043
1044 // Check instruction counts.
1045 auto LoopBlocks = CurLoop->getBlocks();
1046 if (LoopBlocks[0]->size() > 3 || LoopBlocks[1]->size() > 4 ||
1047 LoopBlocks[2]->size() > 3 || LoopBlocks[3]->size() > 3)
1048 return false;
1049
1050 // Check that no instruction other than IndPhi has outside uses.
1051 for (BasicBlock *BB : LoopBlocks)
1052 for (Instruction &I : *BB)
1053 if (&I != IndPhi)
1054 for (User *U : I.users())
1055 if (!CurLoop->contains(cast<Instruction>(U)))
1056 return false;
1057
1058 // Match the branch instruction in the header. We are expecting an
1059 // unconditional branch to the inner loop.
1060 //
1061 // Header:
1062 // %14 = phi ptr [ %24, %OuterBB ], [ %3, %Header.preheader ]
1063 // %15 = load i8, ptr %14, align 1
1064 // br label %MatchBB
1065 BasicBlock *MatchBB;
1066 if (!match(Header->getTerminator(), m_UnconditionalBr(MatchBB)) ||
1067 !InnerLoop->contains(MatchBB))
1068 return false;
1069
1070 // MatchBB should be the entrypoint into the inner loop containing the
1071 // comparison between a search element and a needle.
1072 //
1073 // MatchBB:
1074 // %20 = phi ptr [ %7, %Header ], [ %17, %InnerBB ]
1075 // %21 = load i8, ptr %20, align 1
1076 // %22 = icmp eq i8 %15, %21
1077 // br i1 %22, label %ExitSucc, label %InnerBB
1078 BasicBlock *ExitSucc, *InnerBB;
1079 Value *LoadSearch, *LoadNeedle;
1080 CmpPredicate MatchPred;
1081 if (!match(MatchBB->getTerminator(),
1082 m_Br(m_ICmp(MatchPred, m_Value(LoadSearch), m_Value(LoadNeedle)),
1083 m_BasicBlock(ExitSucc), m_BasicBlock(InnerBB))) ||
1084 MatchPred != ICmpInst::ICMP_EQ || !InnerLoop->contains(InnerBB))
1085 return false;
1086
1087 // We expect outside uses of `IndPhi' in ExitSucc (and only there).
1088 for (User *U : IndPhi->users())
1089 if (!CurLoop->contains(cast<Instruction>(U))) {
1090 auto *PN = dyn_cast<PHINode>(U);
1091 if (!PN || PN->getParent() != ExitSucc)
1092 return false;
1093 }
1094
1095 // Match the loads and check they are simple.
1096 Value *Search, *Needle;
1097 if (!match(LoadSearch, m_Load(m_Value(Search))) ||
1098 !match(LoadNeedle, m_Load(m_Value(Needle))) ||
1099 !cast<LoadInst>(LoadSearch)->isSimple() ||
1100 !cast<LoadInst>(LoadNeedle)->isSimple())
1101 return false;
1102
1103 // Check we are loading valid characters.
1104 Type *CharTy = LoadSearch->getType();
1105 if (!CharTy->isIntegerTy() || LoadNeedle->getType() != CharTy)
1106 return false;
1107
1108 // Pick the vectorisation factor based on CharTy, work out the cost of the
1109 // match intrinsic and decide if we should use it.
1110 // Note: For the time being we assume 128-bit vectors.
1111 unsigned VF = 128 / CharTy->getIntegerBitWidth();
1113 ScalableVectorType::get(CharTy, VF), FixedVectorType::get(CharTy, VF),
1115 IntrinsicCostAttributes Attrs(Intrinsic::experimental_vector_match, Args[2],
1116 Args);
1117 if (TTI->getIntrinsicInstrCost(Attrs, TTI::TCK_SizeAndLatency) > 4)
1118 return false;
1119
1120 // The loads come from two PHIs, each with two incoming values.
1121 PHINode *PSearch = dyn_cast<PHINode>(Search);
1122 PHINode *PNeedle = dyn_cast<PHINode>(Needle);
1123 if (!PSearch || PSearch->getNumIncomingValues() != 2 || !PNeedle ||
1124 PNeedle->getNumIncomingValues() != 2)
1125 return false;
1126
1127 // One PHI comes from the outer loop (PSearch), the other one from the inner
1128 // loop (PNeedle). PSearch effectively corresponds to IndPhi.
1129 if (InnerLoop->contains(PSearch))
1130 std::swap(PSearch, PNeedle);
1131 if (PSearch != &Header->front() || PNeedle != &MatchBB->front())
1132 return false;
1133
1134 // The incoming values of both PHI nodes should be a gep of 1.
1135 Value *SearchStart = PSearch->getIncomingValue(0);
1136 Value *SearchIndex = PSearch->getIncomingValue(1);
1137 if (CurLoop->contains(PSearch->getIncomingBlock(0)))
1138 std::swap(SearchStart, SearchIndex);
1139
1140 Value *NeedleStart = PNeedle->getIncomingValue(0);
1141 Value *NeedleIndex = PNeedle->getIncomingValue(1);
1142 if (InnerLoop->contains(PNeedle->getIncomingBlock(0)))
1143 std::swap(NeedleStart, NeedleIndex);
1144
1145 // Match the GEPs.
1146 if (!match(SearchIndex, m_GEP(m_Specific(PSearch), m_One())) ||
1147 !match(NeedleIndex, m_GEP(m_Specific(PNeedle), m_One())))
1148 return false;
1149
1150 // Check the GEPs result type matches `CharTy'.
1151 GetElementPtrInst *GEPSearch = cast<GetElementPtrInst>(SearchIndex);
1152 GetElementPtrInst *GEPNeedle = cast<GetElementPtrInst>(NeedleIndex);
1153 if (GEPSearch->getResultElementType() != CharTy ||
1154 GEPNeedle->getResultElementType() != CharTy)
1155 return false;
1156
1157 // InnerBB should increment the address of the needle pointer.
1158 //
1159 // InnerBB:
1160 // %17 = getelementptr inbounds i8, ptr %20, i64 1
1161 // %18 = icmp eq ptr %17, %10
1162 // br i1 %18, label %OuterBB, label %MatchBB
1163 BasicBlock *OuterBB;
1164 Value *NeedleEnd;
1165 if (!match(InnerBB->getTerminator(),
1167 m_Value(NeedleEnd)),
1168 m_BasicBlock(OuterBB), m_Specific(MatchBB))) ||
1169 !CurLoop->contains(OuterBB))
1170 return false;
1171
1172 // OuterBB should increment the address of the search element pointer.
1173 //
1174 // OuterBB:
1175 // %24 = getelementptr inbounds i8, ptr %14, i64 1
1176 // %25 = icmp eq ptr %24, %6
1177 // br i1 %25, label %ExitFail, label %Header
1178 BasicBlock *ExitFail;
1179 Value *SearchEnd;
1180 if (!match(OuterBB->getTerminator(),
1182 m_Value(SearchEnd)),
1183 m_BasicBlock(ExitFail), m_Specific(Header))))
1184 return false;
1185
1186 if (!CurLoop->isLoopInvariant(SearchStart) ||
1187 !CurLoop->isLoopInvariant(SearchEnd) ||
1188 !CurLoop->isLoopInvariant(NeedleStart) ||
1189 !CurLoop->isLoopInvariant(NeedleEnd))
1190 return false;
1191
1192 LLVM_DEBUG(dbgs() << "Found idiom in loop: \n" << *CurLoop << "\n\n");
1193
1194 transformFindFirstByte(IndPhi, VF, CharTy, ExitSucc, ExitFail, SearchStart,
1195 SearchEnd, NeedleStart, NeedleEnd);
1196 return true;
1197}
1198
1199Value *LoopIdiomVectorize::expandFindFirstByte(
1200 IRBuilder<> &Builder, DomTreeUpdater &DTU, unsigned VF, Type *CharTy,
1201 Value *IndPhi, BasicBlock *ExitSucc, BasicBlock *ExitFail,
1202 Value *SearchStart, Value *SearchEnd, Value *NeedleStart,
1203 Value *NeedleEnd) {
1204 // Set up some types and constants that we intend to reuse.
1205 auto *I64Ty = Builder.getInt64Ty();
1206 auto *PredVTy = ScalableVectorType::get(Builder.getInt1Ty(), VF);
1207 auto *CharVTy = ScalableVectorType::get(CharTy, VF);
1208 auto *ConstVF = ConstantInt::get(I64Ty, VF);
1209
1210 // Other common arguments.
1211 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1212 LLVMContext &Ctx = Preheader->getContext();
1213 Value *Passthru = ConstantInt::getNullValue(CharVTy);
1214
1215 // Split block in the original loop preheader.
1216 // SPH is the new preheader to the old scalar loop.
1217 BasicBlock *SPH = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1218 nullptr, "scalar_preheader");
1219
1220 // Create the blocks that we're going to use.
1221 //
1222 // We will have the following loops:
1223 // (O) Outer loop where we iterate over the elements of the search array.
1224 // (I) Inner loop where we iterate over the elements of the needle array.
1225 //
1226 // Overall, the blocks do the following:
1227 // (0) Check if the arrays can't cross page boundaries. If so go to (1),
1228 // otherwise fall back to the original scalar loop.
1229 // (1) Load the search array. Go to (2).
1230 // (2) (a) Load the needle array.
1231 // (b) Splat the first element to the inactive lanes.
1232 // (c) Accumulate any matches found. If we haven't reached the end of the
1233 // needle array loop back to (2), otherwise go to (3).
1234 // (3) Test if we found any match. If so go to (4), otherwise go to (5).
1235 // (4) Compute the index of the first match and exit.
1236 // (5) Check if we've reached the end of the search array. If not loop back to
1237 // (1), otherwise exit.
1238 // Blocks (0,4) are not part of any loop. Blocks (1,3,5) and (2) belong to the
1239 // outer and inner loops, respectively.
1240 BasicBlock *BB0 = BasicBlock::Create(Ctx, "mem_check", SPH->getParent(), SPH);
1241 BasicBlock *BB1 =
1242 BasicBlock::Create(Ctx, "find_first_vec_header", SPH->getParent(), SPH);
1243 BasicBlock *BB2 =
1244 BasicBlock::Create(Ctx, "needle_check_vec", SPH->getParent(), SPH);
1245 BasicBlock *BB3 =
1246 BasicBlock::Create(Ctx, "match_check_vec", SPH->getParent(), SPH);
1247 BasicBlock *BB4 =
1248 BasicBlock::Create(Ctx, "calculate_match", SPH->getParent(), SPH);
1249 BasicBlock *BB5 =
1250 BasicBlock::Create(Ctx, "search_check_vec", SPH->getParent(), SPH);
1251
1252 // Update LoopInfo with the new loops.
1253 auto OuterLoop = LI->AllocateLoop();
1254 auto InnerLoop = LI->AllocateLoop();
1255
1256 if (auto ParentLoop = CurLoop->getParentLoop()) {
1257 ParentLoop->addBasicBlockToLoop(BB0, *LI);
1258 ParentLoop->addChildLoop(OuterLoop);
1259 ParentLoop->addBasicBlockToLoop(BB4, *LI);
1260 } else {
1261 LI->addTopLevelLoop(OuterLoop);
1262 }
1263
1264 // Add the inner loop to the outer.
1265 OuterLoop->addChildLoop(InnerLoop);
1266
1267 // Add the new basic blocks to the corresponding loops.
1268 OuterLoop->addBasicBlockToLoop(BB1, *LI);
1269 OuterLoop->addBasicBlockToLoop(BB3, *LI);
1270 OuterLoop->addBasicBlockToLoop(BB5, *LI);
1271 InnerLoop->addBasicBlockToLoop(BB2, *LI);
1272
1273 // Update the terminator added by SplitBlock to branch to the first block.
1274 Preheader->getTerminator()->setSuccessor(0, BB0);
1275 DTU.applyUpdates({{DominatorTree::Delete, Preheader, SPH},
1276 {DominatorTree::Insert, Preheader, BB0}});
1277
1278 // (0) Check if we could be crossing a page boundary; if so, fallback to the
1279 // old scalar loops. Also create a predicate of VF elements to be used in the
1280 // vector loops.
1281 Builder.SetInsertPoint(BB0);
1282 Value *ISearchStart =
1283 Builder.CreatePtrToInt(SearchStart, I64Ty, "search_start_int");
1284 Value *ISearchEnd =
1285 Builder.CreatePtrToInt(SearchEnd, I64Ty, "search_end_int");
1286 Value *SearchIdxInit = Constant::getNullValue(I64Ty);
1287 Value *SearchTripCount =
1288 Builder.CreateZExt(Builder.CreatePtrDiff(CharTy, SearchEnd, SearchStart,
1289 "search_trip_count"),
1290 I64Ty);
1291 Value *INeedleStart =
1292 Builder.CreatePtrToInt(NeedleStart, I64Ty, "needle_start_int");
1293 Value *INeedleEnd =
1294 Builder.CreatePtrToInt(NeedleEnd, I64Ty, "needle_end_int");
1295 Value *NeedleIdxInit = Constant::getNullValue(I64Ty);
1296 Value *NeedleTripCount =
1297 Builder.CreateZExt(Builder.CreatePtrDiff(CharTy, NeedleEnd, NeedleStart,
1298 "needle_trip_count"),
1299 I64Ty);
1300 Value *PredVF =
1301 Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask, {PredVTy, I64Ty},
1302 {ConstantInt::get(I64Ty, 0), ConstVF});
1303
1304 const uint64_t MinPageSize = TTI->getMinPageSize().value();
1305 const uint64_t AddrShiftAmt = llvm::Log2_64(MinPageSize);
1306 Value *SearchStartPage =
1307 Builder.CreateLShr(ISearchStart, AddrShiftAmt, "search_start_page");
1308 Value *SearchEndPage =
1309 Builder.CreateLShr(ISearchEnd, AddrShiftAmt, "search_end_page");
1310 Value *NeedleStartPage =
1311 Builder.CreateLShr(INeedleStart, AddrShiftAmt, "needle_start_page");
1312 Value *NeedleEndPage =
1313 Builder.CreateLShr(INeedleEnd, AddrShiftAmt, "needle_end_page");
1314 Value *SearchPageCmp =
1315 Builder.CreateICmpNE(SearchStartPage, SearchEndPage, "search_page_cmp");
1316 Value *NeedlePageCmp =
1317 Builder.CreateICmpNE(NeedleStartPage, NeedleEndPage, "needle_page_cmp");
1318
1319 Value *CombinedPageCmp =
1320 Builder.CreateOr(SearchPageCmp, NeedlePageCmp, "combined_page_cmp");
1321 CondBrInst *CombinedPageBr = Builder.CreateCondBr(CombinedPageCmp, SPH, BB1);
1322 CombinedPageBr->setMetadata(LLVMContext::MD_prof,
1323 MDBuilder(Ctx).createBranchWeights(10, 90));
1324 DTU.applyUpdates(
1325 {{DominatorTree::Insert, BB0, SPH}, {DominatorTree::Insert, BB0, BB1}});
1326
1327 // (1) Load the search array and branch to the inner loop.
1328 Builder.SetInsertPoint(BB1);
1329 PHINode *SearchIdx = Builder.CreatePHI(I64Ty, 2, "search_idx");
1330 Value *PredSearch = Builder.CreateIntrinsic(
1331 Intrinsic::get_active_lane_mask, {PredVTy, I64Ty},
1332 {SearchIdx, SearchTripCount}, nullptr, "search_pred");
1333 PredSearch = Builder.CreateAnd(PredVF, PredSearch, "search_masked");
1334 Value *Search = Builder.CreateGEP(CharTy, SearchStart, SearchIdx, "psearch");
1335 Value *LoadSearch = Builder.CreateMaskedLoad(
1336 CharVTy, Search, Align(1), PredSearch, Passthru, "search_load_vec");
1337 Value *MatchInit = Constant::getNullValue(PredVTy);
1338 Builder.CreateBr(BB2);
1339 DTU.applyUpdates({{DominatorTree::Insert, BB1, BB2}});
1340
1341 // (2) Inner loop.
1342 Builder.SetInsertPoint(BB2);
1343 PHINode *NeedleIdx = Builder.CreatePHI(I64Ty, 2, "needle_idx");
1344 PHINode *Match = Builder.CreatePHI(PredVTy, 2, "pmatch");
1345
1346 // (2.a) Load the needle array.
1347 Value *PredNeedle = Builder.CreateIntrinsic(
1348 Intrinsic::get_active_lane_mask, {PredVTy, I64Ty},
1349 {NeedleIdx, NeedleTripCount}, nullptr, "needle_pred");
1350 PredNeedle = Builder.CreateAnd(PredVF, PredNeedle, "needle_masked");
1351 Value *Needle = Builder.CreateGEP(CharTy, NeedleStart, NeedleIdx, "pneedle");
1352 Value *LoadNeedle = Builder.CreateMaskedLoad(
1353 CharVTy, Needle, Align(1), PredNeedle, Passthru, "needle_load_vec");
1354
1355 // (2.b) Splat the first element to the inactive lanes.
1356 Value *Needle0 =
1357 Builder.CreateExtractElement(LoadNeedle, uint64_t(0), "needle0");
1358 Value *Needle0Splat = Builder.CreateVectorSplat(ElementCount::getScalable(VF),
1359 Needle0, "needle0");
1360 LoadNeedle = Builder.CreateSelect(PredNeedle, LoadNeedle, Needle0Splat,
1361 "needle_splat");
1362 LoadNeedle = Builder.CreateExtractVector(
1363 FixedVectorType::get(CharTy, VF), LoadNeedle, uint64_t(0), "needle_vec");
1364
1365 // (2.c) Accumulate matches.
1366 Value *MatchSeg = Builder.CreateIntrinsic(
1367 Intrinsic::experimental_vector_match, {CharVTy, LoadNeedle->getType()},
1368 {LoadSearch, LoadNeedle, PredSearch}, nullptr, "match_segment");
1369 Value *MatchAcc = Builder.CreateOr(Match, MatchSeg, "match_accumulator");
1370 Value *NextNeedleIdx =
1371 Builder.CreateAdd(NeedleIdx, ConstVF, "needle_idx_next");
1372 Builder.CreateCondBr(Builder.CreateICmpULT(NextNeedleIdx, NeedleTripCount),
1373 BB2, BB3);
1374 DTU.applyUpdates(
1375 {{DominatorTree::Insert, BB2, BB2}, {DominatorTree::Insert, BB2, BB3}});
1376
1377 // (3) Check if we found a match.
1378 Builder.SetInsertPoint(BB3);
1379 PHINode *MatchPredAccLCSSA = Builder.CreatePHI(PredVTy, 1, "match_pred");
1380 Value *IfAnyMatch = Builder.CreateOrReduce(MatchPredAccLCSSA);
1381 Builder.CreateCondBr(IfAnyMatch, BB4, BB5);
1382 DTU.applyUpdates(
1383 {{DominatorTree::Insert, BB3, BB4}, {DominatorTree::Insert, BB3, BB5}});
1384
1385 // (4) We found a match. Compute the index of its location and exit.
1386 Builder.SetInsertPoint(BB4);
1387 PHINode *MatchLCSSA =
1388 Builder.CreatePHI(SearchStart->getType(), 1, "match_start");
1389 PHINode *MatchPredLCSSA = Builder.CreatePHI(PredVTy, 1, "match_vec");
1390 Value *MatchCnt = Builder.CreateIntrinsic(
1391 Intrinsic::experimental_cttz_elts, {I64Ty, PredVTy},
1392 {MatchPredLCSSA, /*ZeroIsPoison=*/Builder.getInt1(true)}, nullptr,
1393 "match_idx");
1394 Value *MatchVal =
1395 Builder.CreateGEP(CharTy, MatchLCSSA, MatchCnt, "match_res");
1396 Builder.CreateBr(ExitSucc);
1397 DTU.applyUpdates({{DominatorTree::Insert, BB4, ExitSucc}});
1398
1399 // (5) Check if we've reached the end of the search array.
1400 Builder.SetInsertPoint(BB5);
1401 Value *NextSearchIdx =
1402 Builder.CreateAdd(SearchIdx, ConstVF, "search_idx_next");
1403 Builder.CreateCondBr(Builder.CreateICmpULT(NextSearchIdx, SearchTripCount),
1404 BB1, ExitFail);
1405 DTU.applyUpdates({{DominatorTree::Insert, BB5, BB1},
1406 {DominatorTree::Insert, BB5, ExitFail}});
1407
1408 // Set up the PHI nodes.
1409 SearchIdx->addIncoming(SearchIdxInit, BB0);
1410 SearchIdx->addIncoming(NextSearchIdx, BB5);
1411 NeedleIdx->addIncoming(NeedleIdxInit, BB1);
1412 NeedleIdx->addIncoming(NextNeedleIdx, BB2);
1413 Match->addIncoming(MatchInit, BB1);
1414 Match->addIncoming(MatchAcc, BB2);
1415 // These are needed to retain LCSSA form.
1416 MatchPredAccLCSSA->addIncoming(MatchAcc, BB2);
1417 MatchLCSSA->addIncoming(Search, BB3);
1418 MatchPredLCSSA->addIncoming(MatchPredAccLCSSA, BB3);
1419
1420 // Ensure all Phis in the successors of BB4/BB5 have an incoming value from
1421 // them.
1422 fixSuccessorPhis(CurLoop, IndPhi, MatchVal, ExitSucc, BB4);
1423 if (ExitSucc != ExitFail)
1424 fixSuccessorPhis(CurLoop, IndPhi, MatchVal, ExitFail, BB5);
1425
1426 if (VerifyLoops) {
1427 OuterLoop->verifyLoop();
1428 InnerLoop->verifyLoop();
1429 if (!OuterLoop->isRecursivelyLCSSAForm(*DT, *LI))
1430 report_fatal_error("Loops must remain in LCSSA form!");
1431 }
1432
1433 return MatchVal;
1434}
1435
1436void LoopIdiomVectorize::transformFindFirstByte(
1437 PHINode *IndPhi, unsigned VF, Type *CharTy, BasicBlock *ExitSucc,
1438 BasicBlock *ExitFail, Value *SearchStart, Value *SearchEnd,
1439 Value *NeedleStart, Value *NeedleEnd) {
1440 // Insert the find first byte code at the end of the preheader block.
1441 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1442 UncondBrInst *PHBranch = cast<UncondBrInst>(Preheader->getTerminator());
1443 IRBuilder<> Builder(PHBranch);
1444 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1445 Builder.SetCurrentDebugLocation(PHBranch->getDebugLoc());
1446
1447 expandFindFirstByte(Builder, DTU, VF, CharTy, IndPhi, ExitSucc, ExitFail,
1448 SearchStart, SearchEnd, NeedleStart, NeedleEnd);
1449
1450 if (VerifyLoops && CurLoop->getParentLoop()) {
1451 CurLoop->getParentLoop()->verifyLoop();
1452 if (!CurLoop->getParentLoop()->isRecursivelyLCSSAForm(*DT, *LI))
1453 report_fatal_error("Loops must remain in LCSSA form!");
1454 }
1455}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define DEBUG_TYPE
static MDNode * createBranchWeights(LLVMContext &Context, uint64_t TrueWeight, uint64_t FalseWeight)
static cl::opt< bool > VerifyLoops("loop-idiom-vectorize-verify", cl::Hidden, cl::init(false), cl::desc("Verify loops generated Loop Idiom Vectorize Pass."))
static cl::opt< bool > DisableAll("disable-loop-idiom-vectorize-all", cl::Hidden, cl::init(false), cl::desc("Disable Loop Idiom Vectorize Pass."))
static void fixSuccessorPhis(Loop *L, Value *ScalarRes, Value *VectorRes, BasicBlock *SuccBB, BasicBlock *IncBB)
static cl::opt< LoopIdiomVectorizeStyle > LITVecStyle("loop-idiom-vectorize-style", cl::Hidden, cl::desc("The vectorization style for loop idiom transform."), cl::values(clEnumValN(LoopIdiomVectorizeStyle::Masked, "masked", "Use masked vector intrinsics"), clEnumValN(LoopIdiomVectorizeStyle::Predicated, "predicated", "Use VP intrinsics")), cl::init(LoopIdiomVectorizeStyle::Masked))
static cl::opt< bool > DisableFindFirstByte("disable-loop-idiom-vectorize-find-first-byte", cl::Hidden, cl::init(false), cl::desc("Do not convert find-first-byte loop(s)."))
static cl::opt< unsigned > ByteCmpVF("loop-idiom-vectorize-bytecmp-vf", cl::Hidden, cl::desc("The vectorization factor for byte-compare patterns."), cl::init(16))
static cl::opt< bool > DisableByteCmp("disable-loop-idiom-vectorize-bytecmp", cl::Hidden, cl::init(false), cl::desc("Proceed with Loop Idiom Vectorize Pass, but do " "not convert byte-compare loop(s)."))
This file defines the LoopVectorizationLegality class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isSimple(Instruction *I)
#define LLVM_DEBUG(...)
Definition Debug.h:114
static cl::opt< unsigned > MinPageSize("min-page-size", cl::init(0), cl::Hidden, cl::desc("Use this to override the target's minimum page size."))
This pass exposes codegen information to IR-level passes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:518
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction & front() const
Definition BasicBlock.h:472
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:312
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:873
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI bool isInBounds() const
Determine whether the GEP has the inbounds flag.
Type * getResultElementType() const
unsigned getNumIndices() const
Module * getParent()
Get the module that this global value is contained inside of...
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition IRBuilder.h:497
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2347
CallInst * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Definition IRBuilder.h:1120
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition IRBuilder.h:564
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2572
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1223
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:502
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1539
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:579
Value * CreateVScale(Type *Ty, const Twine &Name="")
Create a call to llvm.vscale.<Ty>().
Definition IRBuilder.h:981
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition IRBuilder.h:247
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:584
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2335
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:1967
LLVM_ABI CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1217
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2496
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2331
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition IRBuilder.h:172
Value * CreateCountTrailingZeroElems(Type *ResTy, Value *Mask, bool ZeroIsPoison=true, const Twine &Name="")
Create a call to llvm.experimental_cttz_elts.
Definition IRBuilder.h:1161
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1446
LLVM_ABI Value * CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name="", bool IsNUW=false)
Return the difference between two pointer values.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1877
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2077
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1577
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1429
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2189
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2063
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
Value * CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2351
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1599
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:569
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1463
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2811
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
An instruction for reading from memory.
bool isSimple() const
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
Definition MDBuilder.cpp:38
The optimization diagnostic interface.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Class to represent scalable SIMD vectors.
static LLVM_ABI ScalableVectorType * get(Type *ElementType, unsigned MinNumElts)
Definition Type.cpp:895
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:311
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:310
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:440
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
iterator_range< user_iterator > users()
Definition Value.h:427
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
const ParentTy * getParent() const
Definition ilist_node.h:34
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
br_match m_UnconditionalBr(BasicBlock *&Succ)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_GEP(const OperandTypes &...Ops)
Matches GetElementPtrInst.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:337
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
OuterAnalysisManagerProxy< FunctionAnalysisManager, Loop, LoopStandardAnalysisResults & > FunctionAnalysisManagerLoopProxy
A proxy from a FunctionAnalysisManager to a Loop.
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...