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