LLVM 24.0.0git
RISCVGatherScatterLowering.cpp
Go to the documentation of this file.
1//===- RISCVGatherScatterLowering.cpp - Gather/Scatter lowering -----------===//
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 custom lowers llvm.gather and llvm.scatter instructions to
10// RISC-V intrinsics.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RISCV.h"
15#include "RISCVTargetMachine.h"
22#include "llvm/IR/IRBuilder.h"
26#include "llvm/Pass.h"
28#include <optional>
29
30using namespace llvm;
31using namespace PatternMatch;
32
33#define DEBUG_TYPE "riscv-gather-scatter-lowering"
34
35namespace {
36
37class RISCVGatherScatterLoweringImpl {
38 const RISCVSubtarget *ST;
39 const RISCVTargetLowering *TLI;
40 function_ref<LoopInfo &()> GetLI;
41 LoopInfo *LI = nullptr;
42 const DataLayout *DL;
43
44 SmallVector<WeakTrackingVH> MaybeDeadPHIs;
45
46 // Cache of the BasePtr and Stride determined from this GEP. When a GEP is
47 // used by multiple gathers/scatters, this allow us to reuse the scalar
48 // instructions we created for the first gather/scatter for the others.
50
51public:
52 RISCVGatherScatterLoweringImpl(const RISCVSubtarget *ST,
53 function_ref<LoopInfo &()> GetLI,
54 const DataLayout *DL)
55 : ST(ST), TLI(ST->getTargetLowering()), GetLI(GetLI), DL(DL) {}
56
57 bool run(Function &F);
58
59private:
60 bool tryCreateStridedLoadStore(IntrinsicInst *II);
61
62 std::pair<Value *, Value *> determineBaseAndStride(Instruction *Ptr,
63 IRBuilderBase &Builder);
64
65 bool matchStridedRecurrence(Value *Index, Loop *L, Value *&Stride,
66 PHINode *&BasePtr, BinaryOperator *&Inc,
67 IRBuilderBase &Builder);
68};
69
70} // end anonymous namespace
71
72namespace {
73class RISCVGatherScatterLoweringLegacy : public FunctionPass {
74public:
75 static char ID;
76
77 RISCVGatherScatterLoweringLegacy() : FunctionPass(ID) {}
78
79 bool runOnFunction(Function &F) override;
80
81 void getAnalysisUsage(AnalysisUsage &AU) const override {
82 AU.setPreservesCFG();
83 AU.addRequired<TargetPassConfig>();
84 AU.addRequired<LoopInfoWrapperPass>();
85 }
86
87 StringRef getPassName() const override {
88 return "RISC-V gather/scatter lowering";
89 }
90};
91} // namespace
92
93char RISCVGatherScatterLoweringLegacy::ID = 0;
94
95INITIALIZE_PASS_BEGIN(RISCVGatherScatterLoweringLegacy, DEBUG_TYPE,
96 "RISC-V gather/scatter lowering pass", false, false)
99INITIALIZE_PASS_END(RISCVGatherScatterLoweringLegacy, DEBUG_TYPE,
100 "RISC-V gather/scatter lowering pass", false, false)
101
103 return new RISCVGatherScatterLoweringLegacy();
104}
105
106// TODO: Should we consider the mask when looking for a stride?
107static std::pair<Value *, Value *> matchStridedConstant(Constant *StartC) {
108 if (!isa<FixedVectorType>(StartC->getType()))
109 return std::make_pair(nullptr, nullptr);
110
111 unsigned NumElts = cast<FixedVectorType>(StartC->getType())->getNumElements();
112
113 // Check that the start value is a strided constant.
114 auto *StartVal =
116 if (!StartVal)
117 return std::make_pair(nullptr, nullptr);
118 APInt StrideVal(StartVal->getValue().getBitWidth(), 0);
119 ConstantInt *Prev = StartVal;
120 for (unsigned i = 1; i != NumElts; ++i) {
122 if (!C)
123 return std::make_pair(nullptr, nullptr);
124
125 APInt LocalStride = C->getValue() - Prev->getValue();
126 if (i == 1)
127 StrideVal = LocalStride;
128 else if (StrideVal != LocalStride)
129 return std::make_pair(nullptr, nullptr);
130
131 Prev = C;
132 }
133
134 Value *Stride = ConstantInt::get(StartVal->getType(), StrideVal);
135
136 return std::make_pair(StartVal, Stride);
137}
138
139static std::pair<Value *, Value *> matchStridedStart(Value *Start,
140 IRBuilderBase &Builder) {
141 // Base case, start is a strided constant.
142 auto *StartC = dyn_cast<Constant>(Start);
143 if (StartC)
144 return matchStridedConstant(StartC);
145
146 // Base case, start is a stepvector
148 auto *Ty = Start->getType()->getScalarType();
149 return std::make_pair(ConstantInt::get(Ty, 0), ConstantInt::get(Ty, 1));
150 }
151
152 // Not a constant, maybe it's a strided constant with a splat added or
153 // multiplied.
154 auto *BO = dyn_cast<BinaryOperator>(Start);
155 if (!BO || (BO->getOpcode() != Instruction::Add &&
156 BO->getOpcode() != Instruction::Or &&
157 BO->getOpcode() != Instruction::Shl &&
158 BO->getOpcode() != Instruction::Mul))
159 return std::make_pair(nullptr, nullptr);
160
161 if (BO->getOpcode() == Instruction::Or &&
162 !cast<PossiblyDisjointInst>(BO)->isDisjoint())
163 return std::make_pair(nullptr, nullptr);
164
165 // Look for an operand that is splatted.
166 unsigned OtherIndex = 0;
167 Value *Splat = getSplatValue(BO->getOperand(1));
168 if (!Splat && Instruction::isCommutative(BO->getOpcode())) {
169 Splat = getSplatValue(BO->getOperand(0));
170 OtherIndex = 1;
171 }
172 if (!Splat)
173 return std::make_pair(nullptr, nullptr);
174
175 Value *Stride;
176 std::tie(Start, Stride) = matchStridedStart(BO->getOperand(OtherIndex),
177 Builder);
178 if (!Start)
179 return std::make_pair(nullptr, nullptr);
180
181 Builder.SetInsertPoint(BO);
182 Builder.SetCurrentDebugLocation(DebugLoc());
183 // Add the splat value to the start or multiply the start and stride by the
184 // splat.
185 switch (BO->getOpcode()) {
186 default:
187 llvm_unreachable("Unexpected opcode");
188 case Instruction::Or:
189 Start = Builder.CreateDisjointOr(Start, Splat);
190 break;
191 case Instruction::Add:
192 Start = Builder.CreateAdd(Start, Splat);
193 break;
194 case Instruction::Mul:
195 Start = Builder.CreateMul(Start, Splat);
196 Stride = Builder.CreateMul(Stride, Splat);
197 break;
198 case Instruction::Shl:
199 Start = Builder.CreateShl(Start, Splat);
200 Stride = Builder.CreateShl(Stride, Splat);
201 break;
202 }
203
204 return std::make_pair(Start, Stride);
205}
206
207// Recursively, walk about the use-def chain until we find a Phi with a strided
208// start value. Build and update a scalar recurrence as we unwind the recursion.
209// We also update the Stride as we unwind. Our goal is to move all of the
210// arithmetic out of the loop.
211bool RISCVGatherScatterLoweringImpl::matchStridedRecurrence(
212 Value *Index, Loop *L, Value *&Stride, PHINode *&BasePtr,
213 BinaryOperator *&Inc, IRBuilderBase &Builder) {
214 // Our base case is a Phi.
215 if (auto *Phi = dyn_cast<PHINode>(Index)) {
216 // A phi node we want to perform this function on should be from the
217 // loop header.
218 if (Phi->getParent() != L->getHeader())
219 return false;
220
221 Value *Step, *Start;
222 if (!matchSimpleRecurrence(Phi, Inc, Start, Step) ||
223 Inc->getOpcode() != Instruction::Add)
224 return false;
225 assert(Phi->getNumIncomingValues() == 2 && "Expected 2 operand phi.");
226 unsigned IncrementingBlock = Phi->getIncomingValue(0) == Inc ? 0 : 1;
227 assert(Phi->getIncomingValue(IncrementingBlock) == Inc &&
228 "Expected one operand of phi to be Inc");
229
230 // Step should be a splat.
231 Step = getSplatValue(Step);
232 if (!Step)
233 return false;
234
235 std::tie(Start, Stride) = matchStridedStart(Start, Builder);
236 if (!Start)
237 return false;
238 assert(Stride != nullptr);
239
240 // Build scalar phi and increment.
241 BasePtr =
242 PHINode::Create(Start->getType(), 2, Phi->getName() + ".scalar", Phi->getIterator());
243 Inc = BinaryOperator::CreateAdd(BasePtr, Step, Inc->getName() + ".scalar",
244 Inc->getIterator());
245 BasePtr->addIncoming(Start, Phi->getIncomingBlock(1 - IncrementingBlock));
246 BasePtr->addIncoming(Inc, Phi->getIncomingBlock(IncrementingBlock));
247
248 // Note that this Phi might be eligible for removal.
249 MaybeDeadPHIs.push_back(Phi);
250 return true;
251 }
252
253 // Otherwise look for binary operator.
254 auto *BO = dyn_cast<BinaryOperator>(Index);
255 if (!BO)
256 return false;
257
258 switch (BO->getOpcode()) {
259 default:
260 return false;
261 case Instruction::Or:
262 // We need to be able to treat Or as Add.
263 if (!cast<PossiblyDisjointInst>(BO)->isDisjoint())
264 return false;
265 break;
266 case Instruction::Add:
267 break;
268 case Instruction::Shl:
269 break;
270 case Instruction::Mul:
271 break;
272 }
273
274 // We should have one operand in the loop and one splat.
275 Value *OtherOp;
276 if (isa<Instruction>(BO->getOperand(0)) &&
277 L->contains(cast<Instruction>(BO->getOperand(0)))) {
278 Index = cast<Instruction>(BO->getOperand(0));
279 OtherOp = BO->getOperand(1);
280 } else if (isa<Instruction>(BO->getOperand(1)) &&
281 L->contains(cast<Instruction>(BO->getOperand(1))) &&
282 Instruction::isCommutative(BO->getOpcode())) {
283 Index = cast<Instruction>(BO->getOperand(1));
284 OtherOp = BO->getOperand(0);
285 } else {
286 return false;
287 }
288
289 // Make sure other op is loop invariant.
290 if (!L->isLoopInvariant(OtherOp))
291 return false;
292
293 // Make sure we have a splat.
294 Value *SplatOp = getSplatValue(OtherOp);
295 if (!SplatOp)
296 return false;
297
298 // Recurse up the use-def chain.
299 if (!matchStridedRecurrence(Index, L, Stride, BasePtr, Inc, Builder))
300 return false;
301
302 // Locate the Step and Start values from the recurrence.
303 unsigned StepIndex = Inc->getOperand(0) == BasePtr ? 1 : 0;
304 unsigned StartBlock = BasePtr->getOperand(0) == Inc ? 1 : 0;
305 Value *Step = Inc->getOperand(StepIndex);
306 Value *Start = BasePtr->getOperand(StartBlock);
307
308 // We need to adjust the start value in the preheader.
309 Builder.SetInsertPoint(
310 BasePtr->getIncomingBlock(StartBlock)->getTerminator());
312
313 // TODO: Share this switch with matchStridedStart?
314 switch (BO->getOpcode()) {
315 default:
316 llvm_unreachable("Unexpected opcode!");
317 case Instruction::Add:
318 case Instruction::Or: {
319 // An add only affects the start value. It's ok to do this for Or because
320 // we already checked that there are no common set bits.
321 Start = Builder.CreateAdd(Start, SplatOp, "start");
322 break;
323 }
324 case Instruction::Mul: {
325 Start = Builder.CreateMul(Start, SplatOp, "start");
326 Stride = Builder.CreateMul(Stride, SplatOp, "stride");
327 break;
328 }
329 case Instruction::Shl: {
330 Start = Builder.CreateShl(Start, SplatOp, "start");
331 Stride = Builder.CreateShl(Stride, SplatOp, "stride");
332 break;
333 }
334 }
335
336 // If the Step was defined inside the loop, adjust it before its definition
337 // instead of in the preheader.
338 if (auto *StepI = dyn_cast<Instruction>(Step); StepI && L->contains(StepI))
339 Builder.SetInsertPoint(*StepI->getInsertionPointAfterDef());
340
341 switch (BO->getOpcode()) {
342 default:
343 break;
344 case Instruction::Mul:
345 Step = Builder.CreateMul(Step, SplatOp, "step");
346 break;
347 case Instruction::Shl:
348 Step = Builder.CreateShl(Step, SplatOp, "step");
349 break;
350 }
351
352 Inc->setOperand(StepIndex, Step);
353 BasePtr->setIncomingValue(StartBlock, Start);
354 return true;
355}
356
357std::pair<Value *, Value *>
358RISCVGatherScatterLoweringImpl::determineBaseAndStride(Instruction *Ptr,
359 IRBuilderBase &Builder) {
360
361 // A gather/scatter of a splat is a zero strided load/store.
362 if (auto *BasePtr = getSplatValue(Ptr)) {
363 Type *IntPtrTy = DL->getIntPtrType(BasePtr->getType());
364 return std::make_pair(BasePtr, ConstantInt::get(IntPtrTy, 0));
365 }
366
367 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
368 if (!GEP)
369 return std::make_pair(nullptr, nullptr);
370
371 auto I = StridedAddrs.find(GEP);
372 if (I != StridedAddrs.end())
373 return I->second;
374
375 SmallVector<Value *, 2> Ops(GEP->operands());
376
377 // If the base pointer is a vector, check if it's strided.
378 Value *Base = GEP->getPointerOperand();
379 if (auto *BaseInst = dyn_cast<Instruction>(Base);
380 BaseInst && BaseInst->getType()->isVectorTy()) {
381 // If GEP's offset is scalar then we can add it to the base pointer's base.
382 auto IsScalar = [](Value *Idx) { return !Idx->getType()->isVectorTy(); };
383 if (all_of(GEP->indices(), IsScalar)) {
384 auto [BaseBase, Stride] = determineBaseAndStride(BaseInst, Builder);
385 if (BaseBase) {
386 Builder.SetInsertPoint(GEP);
387 SmallVector<Value *> Indices(GEP->indices());
388 Value *OffsetBase =
389 Builder.CreateGEP(GEP->getSourceElementType(), BaseBase, Indices,
390 GEP->getName() + "offset", GEP->isInBounds());
391 return {OffsetBase, Stride};
392 }
393 }
394 }
395
396 // Base pointer needs to be a scalar.
397 Value *ScalarBase = Base;
398 if (ScalarBase->getType()->isVectorTy()) {
399 ScalarBase = getSplatValue(ScalarBase);
400 if (!ScalarBase)
401 return std::make_pair(nullptr, nullptr);
402 }
403
404 std::optional<unsigned> VecOperand;
405 unsigned TypeScale = 0;
406
407 // Look for a vector operand and scale.
409 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
410 if (!Ops[i]->getType()->isVectorTy())
411 continue;
412
413 if (VecOperand)
414 return std::make_pair(nullptr, nullptr);
415
416 VecOperand = i;
417
418 TypeSize TS = GTI.getSequentialElementStride(*DL);
419 if (TS.isScalable())
420 return std::make_pair(nullptr, nullptr);
421
422 TypeScale = TS.getFixedValue();
423 }
424
425 // We need to find a vector index to simplify.
426 if (!VecOperand)
427 return std::make_pair(nullptr, nullptr);
428
429 // We can't extract the stride if the arithmetic is done at a different size
430 // than the pointer type. Adding the stride later may not wrap correctly.
431 // Technically we could handle wider indices, but I don't expect that in
432 // practice. Handle one special case here - constants. This simplifies
433 // writing test cases.
434 Value *VecIndex = Ops[*VecOperand];
435 Type *VecIntPtrTy = DL->getIntPtrType(GEP->getType());
436 if (VecIndex->getType() != VecIntPtrTy) {
437 auto *VecIndexC = dyn_cast<Constant>(VecIndex);
438 if (!VecIndexC)
439 return std::make_pair(nullptr, nullptr);
440 if (VecIndex->getType()->getScalarSizeInBits() > VecIntPtrTy->getScalarSizeInBits())
441 VecIndex = ConstantFoldCastInstruction(Instruction::Trunc, VecIndexC, VecIntPtrTy);
442 else
443 VecIndex = ConstantFoldCastInstruction(Instruction::SExt, VecIndexC, VecIntPtrTy);
444 }
445
446 // Handle the non-recursive case. This is what we see if the vectorizer
447 // decides to use a scalar IV + vid on demand instead of a vector IV.
448 auto [Start, Stride] = matchStridedStart(VecIndex, Builder);
449 if (Start) {
450 assert(Stride);
451 Builder.SetInsertPoint(GEP);
452
453 // Replace the vector index with the scalar start and build a scalar GEP.
454 Ops[*VecOperand] = Start;
455 Type *SourceTy = GEP->getSourceElementType();
456 Value *BasePtr =
457 Builder.CreateGEP(SourceTy, ScalarBase, ArrayRef(Ops).drop_front());
458
459 // Convert stride to pointer size if needed.
460 Type *IntPtrTy = DL->getIntPtrType(BasePtr->getType());
461 assert(Stride->getType() == IntPtrTy && "Unexpected type");
462
463 // Scale the stride by the size of the indexed type.
464 if (TypeScale != 1)
465 Stride = Builder.CreateMul(Stride, ConstantInt::get(IntPtrTy, TypeScale));
466
467 auto P = std::make_pair(BasePtr, Stride);
468 StridedAddrs[GEP] = P;
469 return P;
470 }
471
472 if (!LI)
473 LI = &GetLI();
474
475 // Make sure we're in a loop and that has a pre-header and a single latch.
476 Loop *L = LI->getLoopFor(GEP->getParent());
477 if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
478 return std::make_pair(nullptr, nullptr);
479
480 BinaryOperator *Inc;
481 PHINode *BasePhi;
482 if (!matchStridedRecurrence(VecIndex, L, Stride, BasePhi, Inc, Builder))
483 return std::make_pair(nullptr, nullptr);
484
485 assert(BasePhi->getNumIncomingValues() == 2 && "Expected 2 operand phi.");
486 unsigned IncrementingBlock = BasePhi->getOperand(0) == Inc ? 0 : 1;
487 assert(BasePhi->getIncomingValue(IncrementingBlock) == Inc &&
488 "Expected one operand of phi to be Inc");
489
490 Builder.SetInsertPoint(GEP);
491
492 // Replace the vector index with the scalar phi and build a scalar GEP.
493 Ops[*VecOperand] = BasePhi;
494 Type *SourceTy = GEP->getSourceElementType();
495 Value *BasePtr =
496 Builder.CreateGEP(SourceTy, ScalarBase, ArrayRef(Ops).drop_front());
497
498 // Final adjustments to stride should go in the start block.
499 Builder.SetInsertPoint(
500 BasePhi->getIncomingBlock(1 - IncrementingBlock)->getTerminator());
501
502 // Convert stride to pointer size if needed.
503 Type *IntPtrTy = DL->getIntPtrType(BasePtr->getType());
504 assert(Stride->getType() == IntPtrTy && "Unexpected type");
505
506 // Scale the stride by the size of the indexed type.
507 if (TypeScale != 1)
508 Stride = Builder.CreateMul(Stride, ConstantInt::get(IntPtrTy, TypeScale));
509
510 auto P = std::make_pair(BasePtr, Stride);
511 StridedAddrs[GEP] = P;
512 return P;
513}
514
515bool RISCVGatherScatterLoweringImpl::tryCreateStridedLoadStore(
516 IntrinsicInst *II) {
517 VectorType *DataType;
518 Value *StoreVal = nullptr, *Ptr, *Mask, *EVL = nullptr;
520 switch (II->getIntrinsicID()) {
521 case Intrinsic::masked_gather:
522 DataType = cast<VectorType>(II->getType());
523 Ptr = II->getArgOperand(0);
524 Alignment = II->getParamAlign(0).valueOrOne();
525 Mask = II->getArgOperand(1);
526 break;
527 case Intrinsic::vp_gather:
528 DataType = cast<VectorType>(II->getType());
529 Ptr = II->getArgOperand(0);
530 // FIXME: Falling back to ABI alignment is incorrect.
531 Alignment = II->getParamAlign(0).value_or(
532 DL->getABITypeAlign(DataType->getElementType()));
533 Mask = II->getArgOperand(1);
534 EVL = II->getArgOperand(2);
535 break;
536 case Intrinsic::masked_scatter:
537 DataType = cast<VectorType>(II->getArgOperand(0)->getType());
538 StoreVal = II->getArgOperand(0);
539 Ptr = II->getArgOperand(1);
540 Alignment = II->getParamAlign(1).valueOrOne();
541 Mask = II->getArgOperand(2);
542 break;
543 case Intrinsic::vp_scatter:
544 DataType = cast<VectorType>(II->getArgOperand(0)->getType());
545 StoreVal = II->getArgOperand(0);
546 Ptr = II->getArgOperand(1);
547 // FIXME: Falling back to ABI alignment is incorrect.
548 Alignment = II->getParamAlign(1).value_or(
549 DL->getABITypeAlign(DataType->getElementType()));
550 Mask = II->getArgOperand(2);
551 EVL = II->getArgOperand(3);
552 break;
553 default:
554 llvm_unreachable("Unexpected intrinsic");
555 }
556
557 // Make sure the operation will be supported by the backend.
558 EVT DataTypeVT = TLI->getValueType(*DL, DataType);
559 if (!TLI->isLegalStridedLoadStore(DataTypeVT, Alignment))
560 return false;
561
562 // FIXME: Let the backend type legalize by splitting/widening?
563 if (!TLI->isTypeLegal(DataTypeVT))
564 return false;
565
566 // Pointer should be an instruction.
567 auto *PtrI = dyn_cast<Instruction>(Ptr);
568 if (!PtrI)
569 return false;
570
571 IRBuilder Builder(PtrI->getIterator(), InstSimplifyFolder(*DL));
572
573 Value *BasePtr, *Stride;
574 std::tie(BasePtr, Stride) = determineBaseAndStride(PtrI, Builder);
575 if (!BasePtr)
576 return false;
577 assert(Stride != nullptr);
578
579 Builder.SetInsertPoint(II);
580
581 if (!EVL)
582 EVL = Builder.CreateElementCount(
583 Builder.getInt32Ty(), cast<VectorType>(DataType)->getElementCount());
584
585 Value *Call;
586
587 if (!StoreVal) {
588 Call = Builder.CreateIntrinsic(
589 Intrinsic::experimental_vp_strided_load,
590 {DataType, BasePtr->getType(), Stride->getType()},
591 {BasePtr, Stride, Mask, EVL});
592
593 // Merge llvm.masked.gather's passthru
594 if (II->getIntrinsicID() == Intrinsic::masked_gather)
595 Call = Builder.CreateSelect(Mask, Call, II->getArgOperand(2));
596 } else
597 Call = Builder.CreateIntrinsic(
598 Intrinsic::experimental_vp_strided_store,
599 {DataType, BasePtr->getType(), Stride->getType()},
600 {StoreVal, BasePtr, Stride, Mask, EVL});
601
602 Call->takeName(II);
603 II->replaceAllUsesWith(Call);
604 II->eraseFromParent();
605
606 if (PtrI->use_empty())
608
609 return true;
610}
611
612bool RISCVGatherScatterLoweringImpl::run(Function &F) {
614 return false;
615
617
618 bool Changed = false;
619
620 for (BasicBlock &BB : F) {
621 for (Instruction &I : BB) {
622 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
623 if (!II)
624 continue;
625 switch (II->getIntrinsicID()) {
626 case Intrinsic::masked_gather:
627 case Intrinsic::masked_scatter:
628 case Intrinsic::vp_gather:
629 case Intrinsic::vp_scatter:
630 Worklist.push_back(II);
631 break;
632 default:
633 break;
634 }
635 }
636 }
637
638 // Rewrite gather/scatter to form strided load/store if possible.
639 for (auto *II : Worklist)
640 Changed |= tryCreateStridedLoadStore(II);
641
642 // Remove any dead phis.
643 while (!MaybeDeadPHIs.empty()) {
644 if (auto *Phi = dyn_cast_or_null<PHINode>(MaybeDeadPHIs.pop_back_val()))
646 }
647
648 return Changed;
649}
650
651bool RISCVGatherScatterLoweringLegacy::runOnFunction(Function &F) {
652 if (skipFunction(F))
653 return false;
654
655 auto &TPC = getAnalysis<TargetPassConfig>();
656 auto &TM = TPC.getTM<RISCVTargetMachine>();
657 auto *ST = &TM.getSubtarget<RISCVSubtarget>(F);
658 auto GetLI = [&]() -> LoopInfo & {
659 return getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
660 };
661 return RISCVGatherScatterLoweringImpl(ST, GetLI, &F.getDataLayout()).run(F);
662}
663
664PreservedAnalyses
666 auto *ST = &TM->getSubtarget<RISCVSubtarget>(F);
667 auto GetLI = [&]() -> LoopInfo & { return FAM.getResult<LoopAnalysis>(F); };
668 bool Changed =
669 RISCVGatherScatterLoweringImpl(ST, GetLI, &F.getDataLayout()).run(F);
670 if (!Changed)
671 return PreservedAnalyses::all();
672
674}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Common GEP
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static std::pair< Value *, Value * > matchStridedStart(Value *Start, IRBuilderBase &Builder)
static std::pair< Value *, Value * > matchStridedConstant(Constant *StartC)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
Definition APInt.h:78
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
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:228
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:522
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2011
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1507
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:1418
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1452
LLVM_ABI Value * CreateElementCount(Type *Ty, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
A wrapper class for inspecting calls to intrinsic functions.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
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.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
static PreservedAnalyses allInSet()
Construct a preserved analyses object with a single preserved set.
Definition Analysis.h:125
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
bool useRVVForFixedLengthVectors() const
bool hasVInstructions() const
bool isLegalStridedLoadStore(EVT DataType, Align Alignment) const
Return true if a stride load store of the given result type and alignment is legal.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
Target-Independent Code Generator Pass Configuration Options.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
void setOperand(unsigned i, Value *Val)
Definition User.h:212
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
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
bool match(Val *V, const Pattern &P)
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionPass * createRISCVGatherScatterLoweringLegacyPass()
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:622
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
IntPtrTy
Definition InstrProf.h:82
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.