LLVM 24.0.0git
MVEGatherScatterLowering.cpp
Go to the documentation of this file.
1//===- MVEGatherScatterLowering.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/// arm.mve.gather and arm.mve.scatter intrinsics, optimising the code to
11/// produce a better final result as we go.
12//
13//===----------------------------------------------------------------------===//
14
15#include "ARM.h"
16#include "ARMBaseInstrInfo.h"
17#include "ARMSubtarget.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/Constant.h"
26#include "llvm/IR/Constants.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstrTypes.h"
31#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/IntrinsicsARM.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Value.h"
40#include "llvm/Pass.h"
43#include <cassert>
44
45using namespace llvm;
46
47#define DEBUG_TYPE "arm-mve-gather-scatter-lowering"
48
49namespace {
50
51class MVEGatherScatterLowering : public FunctionPass {
52public:
53 static char ID; // Pass identification, replacement for typeid
54
55 explicit MVEGatherScatterLowering() : FunctionPass(ID) {
57 }
58
59 bool runOnFunction(Function &F) override;
60
61 StringRef getPassName() const override {
62 return "MVE gather/scatter lowering";
63 }
64
65 void getAnalysisUsage(AnalysisUsage &AU) const override {
66 AU.setPreservesCFG();
70 }
71
72private:
73 LoopInfo *LI = nullptr;
74 const DataLayout *DL;
75
76 // Check this is a valid gather with correct alignment
77 bool isLegalTypeAndAlignment(unsigned NumElements, unsigned ElemSize,
78 Align Alignment);
79 // Check whether Ptr is hidden behind a bitcast and look through it
80 void lookThroughBitcast(Value *&Ptr);
81 // Decompose a ptr into Base and Offsets, potentially using a GEP to return a
82 // scalar base and vector offsets, or else fallback to using a base of 0 and
83 // offset of Ptr where possible.
84 Value *decomposePtr(Value *Ptr, Value *&Offsets, int &Scale,
85 FixedVectorType *Ty, Type *MemoryTy,
86 IRBuilder<> &Builder);
87 // Check for a getelementptr and deduce base and offsets from it, on success
88 // returning the base directly and the offsets indirectly using the Offsets
89 // argument
92 // Compute the scale of this gather/scatter instruction
93 int computeScale(unsigned GEPElemSize, unsigned MemoryElemSize);
94 // If the value is a constant, or derived from constants via additions
95 // and multilications, return its numeric value
96 std::optional<int64_t> getIfConst(const Value *V);
97 // If Inst is an add instruction, check whether one summand is a
98 // constant. If so, scale this constant and return it together with
99 // the other summand.
100 std::pair<Value *, int64_t> getVarAndConst(Value *Inst, int TypeScale);
101
102 Instruction *lowerGather(IntrinsicInst *I);
103 // Create a gather from a base + vector of offsets
104 Instruction *tryCreateMaskedGatherOffset(IntrinsicInst *I, Value *Ptr,
105 Instruction *&Root,
106 IRBuilder<> &Builder);
107 // Create a gather from a vector of pointers
108 Instruction *tryCreateMaskedGatherBase(IntrinsicInst *I, Value *Ptr,
109 IRBuilder<> &Builder,
110 int64_t Increment = 0);
111 // Create an incrementing gather from a vector of pointers
112 Instruction *tryCreateMaskedGatherBaseWB(IntrinsicInst *I, Value *Ptr,
113 IRBuilder<> &Builder,
114 int64_t Increment = 0);
115
116 Instruction *lowerScatter(IntrinsicInst *I);
117 // Create a scatter to a base + vector of offsets
118 Instruction *tryCreateMaskedScatterOffset(IntrinsicInst *I, Value *Offsets,
119 IRBuilder<> &Builder);
120 // Create a scatter to a vector of pointers
121 Instruction *tryCreateMaskedScatterBase(IntrinsicInst *I, Value *Ptr,
122 IRBuilder<> &Builder,
123 int64_t Increment = 0);
124 // Create an incrementing scatter from a vector of pointers
125 Instruction *tryCreateMaskedScatterBaseWB(IntrinsicInst *I, Value *Ptr,
126 IRBuilder<> &Builder,
127 int64_t Increment = 0);
128
129 // QI gathers and scatters can increment their offsets on their own if
130 // the increment is a constant value (digit)
131 Instruction *tryCreateIncrementingGatScat(IntrinsicInst *I, Value *Ptr,
132 IRBuilder<> &Builder);
133 // QI gathers/scatters can increment their offsets on their own if the
134 // increment is a constant value (digit) - this creates a writeback QI
135 // gather/scatter
136 Instruction *tryCreateIncrementingWBGatScat(IntrinsicInst *I, Value *BasePtr,
137 Value *Ptr, unsigned TypeScale,
138 IRBuilder<> &Builder);
139
140 // Optimise the base and offsets of the given address
141 bool optimiseAddress(Value *Address, BasicBlock *BB, LoopInfo *LI);
142 // Try to fold consecutive geps together into one
143 Value *foldGEP(GetElementPtrInst *GEP, Value *&Offsets, unsigned &Scale,
144 IRBuilder<> &Builder);
145 // Check whether these offsets could be moved out of the loop they're in
146 bool optimiseOffsets(Value *Offsets, BasicBlock *BB, LoopInfo *LI);
147 // Pushes the given add out of the loop
148 void pushOutAdd(PHINode *&Phi, Value *OffsSecondOperand, unsigned StartIndex);
149 // Pushes the given mul or shl out of the loop
150 void pushOutMulShl(unsigned Opc, PHINode *&Phi, Value *IncrementPerRound,
151 Value *OffsSecondOperand, unsigned LoopIncrement,
152 IRBuilder<> &Builder);
153};
154
155} // end anonymous namespace
156
157char MVEGatherScatterLowering::ID = 0;
158
159INITIALIZE_PASS(MVEGatherScatterLowering, DEBUG_TYPE,
160 "MVE gather/scattering lowering pass", false, false)
161
163 return new MVEGatherScatterLowering();
164}
165
166bool MVEGatherScatterLowering::isLegalTypeAndAlignment(unsigned NumElements,
167 unsigned ElemSize,
168 Align Alignment) {
169 if (((NumElements == 4 &&
170 (ElemSize == 32 || ElemSize == 16 || ElemSize == 8)) ||
171 (NumElements == 8 && (ElemSize == 16 || ElemSize == 8)) ||
172 (NumElements == 16 && ElemSize == 8)) &&
173 Alignment >= ElemSize / 8)
174 return true;
175 LLVM_DEBUG(dbgs() << "masked gathers/scatters: instruction does not have "
176 << "valid alignment or vector type \n");
177 return false;
178}
179
180static bool checkOffsetSize(Value *Offsets, unsigned TargetElemCount) {
181 // Offsets that are not of type <N x i32> are sign extended by the
182 // getelementptr instruction, and MVE gathers/scatters treat the offset as
183 // unsigned. Thus, if the element size is smaller than 32, we can only allow
184 // positive offsets - i.e., the offsets are not allowed to be variables we
185 // can't look into.
186 // Additionally, <N x i32> offsets have to either originate from a zext of a
187 // vector with element types smaller or equal the type of the gather we're
188 // looking at, or consist of constants that we can check are small enough
189 // to fit into the gather type.
190 // Thus we check that 0 < value < 2^TargetElemSize.
191 unsigned TargetElemSize = 128 / TargetElemCount;
192 unsigned OffsetElemSize = cast<FixedVectorType>(Offsets->getType())
193 ->getElementType()
194 ->getScalarSizeInBits();
195 if (OffsetElemSize != TargetElemSize || OffsetElemSize != 32) {
196 Constant *ConstOff = dyn_cast<Constant>(Offsets);
197 if (!ConstOff)
198 return false;
199 int64_t TargetElemMaxSize = (1ULL << TargetElemSize);
200 auto CheckValueSize = [TargetElemMaxSize](Value *OffsetElem) {
201 ConstantInt *OConst = dyn_cast<ConstantInt>(OffsetElem);
202 if (!OConst)
203 return false;
204 int SExtValue = OConst->getSExtValue();
205 if (SExtValue >= TargetElemMaxSize || SExtValue < 0)
206 return false;
207 return true;
208 };
209 if (isa<FixedVectorType>(ConstOff->getType())) {
210 for (unsigned i = 0; i < TargetElemCount; i++) {
211 if (!CheckValueSize(ConstOff->getAggregateElement(i)))
212 return false;
213 }
214 } else {
215 if (!CheckValueSize(ConstOff))
216 return false;
217 }
218 }
219 return true;
220}
221
222Value *MVEGatherScatterLowering::decomposePtr(Value *Ptr, Value *&Offsets,
223 int &Scale, FixedVectorType *Ty,
224 Type *MemoryTy,
225 IRBuilder<> &Builder) {
226 if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
227 if (Value *V = decomposeGEP(Offsets, Ty, GEP, Builder)) {
228 Scale =
229 computeScale(DL->getTypeAllocSizeInBits(GEP->getSourceElementType()),
230 MemoryTy->getScalarSizeInBits());
231 return Scale == -1 ? nullptr : V;
232 }
233 }
234
235 // If we couldn't use the GEP (or it doesn't exist), attempt to use a
236 // BasePtr of 0 with Ptr as the Offsets, so long as there are only 4
237 // elements.
238 FixedVectorType *PtrTy = cast<FixedVectorType>(Ptr->getType());
239 if (PtrTy->getNumElements() != 4 || MemoryTy->getScalarSizeInBits() == 32)
240 return nullptr;
241 Value *Zero = ConstantInt::get(Builder.getInt32Ty(), 0);
242 Value *BasePtr = Builder.CreateIntToPtr(Zero, Builder.getPtrTy());
243 Offsets = Builder.CreatePtrToInt(
244 Ptr, FixedVectorType::get(Builder.getInt32Ty(), 4));
245 Scale = 0;
246 return BasePtr;
247}
248
249Value *MVEGatherScatterLowering::decomposeGEP(Value *&Offsets,
250 FixedVectorType *Ty,
251 GetElementPtrInst *GEP,
252 IRBuilder<> &Builder) {
253 if (!GEP) {
254 LLVM_DEBUG(dbgs() << "masked gathers/scatters: no getelementpointer "
255 << "found\n");
256 return nullptr;
257 }
258 LLVM_DEBUG(dbgs() << "masked gathers/scatters: getelementpointer found."
259 << " Looking at intrinsic for base + vector of offsets\n");
260 Value *GEPPtr = GEP->getPointerOperand();
261 Offsets = GEP->getOperand(1);
262 if (GEPPtr->getType()->isVectorTy() ||
263 !isa<FixedVectorType>(Offsets->getType()))
264 return nullptr;
265
266 if (GEP->getNumOperands() != 2) {
267 LLVM_DEBUG(dbgs() << "masked gathers/scatters: getelementptr with too many"
268 << " operands. Expanding.\n");
269 return nullptr;
270 }
271 Offsets = GEP->getOperand(1);
272 unsigned OffsetsElemCount =
273 cast<FixedVectorType>(Offsets->getType())->getNumElements();
274 // Paranoid check whether the number of parallel lanes is the same
275 assert(Ty->getNumElements() == OffsetsElemCount);
276
277 ZExtInst *ZextOffs = dyn_cast<ZExtInst>(Offsets);
278 if (ZextOffs)
279 Offsets = ZextOffs->getOperand(0);
280 FixedVectorType *OffsetType = cast<FixedVectorType>(Offsets->getType());
281
282 // If the offsets are already being zext-ed to <N x i32>, that relieves us of
283 // having to make sure that they won't overflow.
284 if (!ZextOffs || cast<FixedVectorType>(ZextOffs->getDestTy())
285 ->getElementType()
286 ->getScalarSizeInBits() != 32)
287 if (!checkOffsetSize(Offsets, OffsetsElemCount))
288 return nullptr;
289
290 // The offset sizes have been checked; if any truncating or zext-ing is
291 // required to fix them, do that now
292 if (Ty != Offsets->getType()) {
293 if ((Ty->getElementType()->getScalarSizeInBits() <
294 OffsetType->getElementType()->getScalarSizeInBits())) {
295 Offsets = Builder.CreateTrunc(Offsets, Ty);
296 } else {
297 Offsets = Builder.CreateZExt(Offsets, VectorType::getInteger(Ty));
298 }
299 }
300 // If none of the checks failed, return the gep's base pointer
301 LLVM_DEBUG(dbgs() << "masked gathers/scatters: found correct offsets\n");
302 return GEPPtr;
303}
304
305void MVEGatherScatterLowering::lookThroughBitcast(Value *&Ptr) {
306 // Look through bitcast instruction if #elements is the same
307 if (auto *BitCast = dyn_cast<BitCastInst>(Ptr)) {
308 auto *BCTy = cast<FixedVectorType>(BitCast->getType());
309 auto *BCSrcTy = cast<FixedVectorType>(BitCast->getOperand(0)->getType());
310 if (BCTy->getNumElements() == BCSrcTy->getNumElements()) {
311 LLVM_DEBUG(dbgs() << "masked gathers/scatters: looking through "
312 << "bitcast\n");
313 Ptr = BitCast->getOperand(0);
314 }
315 }
316}
317
318int MVEGatherScatterLowering::computeScale(unsigned GEPElemSize,
319 unsigned MemoryElemSize) {
320 // This can be a 32bit load/store scaled by 4, a 16bit load/store scaled by 2,
321 // or a 8bit, 16bit or 32bit load/store scaled by 1
322 if (GEPElemSize == 32 && MemoryElemSize == 32)
323 return 2;
324 else if (GEPElemSize == 16 && MemoryElemSize == 16)
325 return 1;
326 else if (GEPElemSize == 8)
327 return 0;
328 LLVM_DEBUG(dbgs() << "masked gathers/scatters: incorrect scale. Can't "
329 << "create intrinsic\n");
330 return -1;
331}
332
333std::optional<int64_t> MVEGatherScatterLowering::getIfConst(const Value *V) {
334 const Constant *C = dyn_cast<Constant>(V);
335 if (C && C->getSplatValue())
336 return std::optional<int64_t>{C->getUniqueInteger().getSExtValue()};
337 if (!isa<Instruction>(V))
338 return std::optional<int64_t>{};
339
341 if (I->getOpcode() == Instruction::Add || I->getOpcode() == Instruction::Or ||
342 I->getOpcode() == Instruction::Mul ||
343 I->getOpcode() == Instruction::Shl) {
344 std::optional<int64_t> Op0 = getIfConst(I->getOperand(0));
345 std::optional<int64_t> Op1 = getIfConst(I->getOperand(1));
346 if (!Op0 || !Op1)
347 return std::optional<int64_t>{};
348 if (I->getOpcode() == Instruction::Add)
349 return std::optional<int64_t>{*Op0 + *Op1};
350 if (I->getOpcode() == Instruction::Mul)
351 return std::optional<int64_t>{*Op0 * *Op1};
352 if (I->getOpcode() == Instruction::Shl)
353 return std::optional<int64_t>{*Op0 << *Op1};
354 if (I->getOpcode() == Instruction::Or)
355 return std::optional<int64_t>{*Op0 | *Op1};
356 }
357 return std::optional<int64_t>{};
358}
359
360// Return true if I is an Or instruction that is equivalent to an add, due to
361// the operands having no common bits set.
362static bool isAddLikeOr(Instruction *I, const DataLayout &DL) {
363 return I->getOpcode() == Instruction::Or &&
364 haveNoCommonBitsSet(I->getOperand(0), I->getOperand(1), DL);
365}
366
367std::pair<Value *, int64_t>
368MVEGatherScatterLowering::getVarAndConst(Value *Inst, int TypeScale) {
369 std::pair<Value *, int64_t> ReturnFalse =
370 std::pair<Value *, int64_t>(nullptr, 0);
371 // At this point, the instruction we're looking at must be an add or an
372 // add-like-or.
374 if (Add == nullptr ||
375 (Add->getOpcode() != Instruction::Add && !isAddLikeOr(Add, *DL)))
376 return ReturnFalse;
377
378 Value *Summand;
379 std::optional<int64_t> Const;
380 // Find out which operand the value that is increased is
381 if ((Const = getIfConst(Add->getOperand(0))))
382 Summand = Add->getOperand(1);
383 else if ((Const = getIfConst(Add->getOperand(1))))
384 Summand = Add->getOperand(0);
385 else
386 return ReturnFalse;
387
388 // Check that the constant is small enough for an incrementing gather
389 int64_t Immediate = *Const << TypeScale;
390 if (Immediate > 512 || Immediate < -512 || Immediate % 4 != 0)
391 return ReturnFalse;
392
393 return std::pair<Value *, int64_t>(Summand, Immediate);
394}
395
396Instruction *MVEGatherScatterLowering::lowerGather(IntrinsicInst *I) {
397 using namespace PatternMatch;
398 LLVM_DEBUG(dbgs() << "masked gathers: checking transform preconditions\n"
399 << *I << "\n");
400
401 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
402 // Attempt to turn the masked gather in I into a MVE intrinsic
403 // Potentially optimising the addressing modes as we do so.
404 auto *Ty = cast<FixedVectorType>(I->getType());
405 Value *Ptr = I->getArgOperand(0);
406 Align Alignment = I->getParamAlign(0).valueOrOne();
407 Value *Mask = I->getArgOperand(1);
408 Value *PassThru = I->getArgOperand(2);
409
410 if (!isLegalTypeAndAlignment(Ty->getNumElements(), Ty->getScalarSizeInBits(),
411 Alignment))
412 return nullptr;
413 lookThroughBitcast(Ptr);
414 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
415
416 IRBuilder<> Builder(I);
417 Instruction *Root = I;
418
419 Instruction *Load = tryCreateIncrementingGatScat(I, Ptr, Builder);
420 if (!Load)
421 Load = tryCreateMaskedGatherOffset(I, Ptr, Root, Builder);
422 if (!Load)
423 Load = tryCreateMaskedGatherBase(I, Ptr, Builder);
424 if (!Load)
425 return nullptr;
426
427 if (!isa<UndefValue>(PassThru) && !match(PassThru, m_Zero())) {
428 LLVM_DEBUG(dbgs() << "masked gathers: found non-trivial passthru - "
429 << "creating select\n");
430 Load = SelectInst::Create(Mask, Load, PassThru);
431 Builder.Insert(Load);
432 }
433
435 Root->eraseFromParent();
436 if (Root != I)
437 // If this was an extending gather, we need to get rid of the sext/zext
438 // sext/zext as well as of the gather itself
439 I->eraseFromParent();
440
441 LLVM_DEBUG(dbgs() << "masked gathers: successfully built masked gather\n"
442 << *Load << "\n");
443 return Load;
444}
445
446Instruction *MVEGatherScatterLowering::tryCreateMaskedGatherBase(
447 IntrinsicInst *I, Value *Ptr, IRBuilder<> &Builder, int64_t Increment) {
448 using namespace PatternMatch;
449 auto *Ty = cast<FixedVectorType>(I->getType());
450 LLVM_DEBUG(dbgs() << "masked gathers: loading from vector of pointers\n");
451 if (Ty->getNumElements() != 4 || Ty->getScalarSizeInBits() != 32)
452 // Can't build an intrinsic for this
453 return nullptr;
454 Value *Mask = I->getArgOperand(1);
455 if (match(Mask, m_One()))
456 return Builder.CreateIntrinsicWithoutFolding(
457 Intrinsic::arm_mve_vldr_gather_base, {Ty, Ptr->getType()},
458 {Ptr, Builder.getInt32(Increment)});
459 return Builder.CreateIntrinsicWithoutFolding(
460 Intrinsic::arm_mve_vldr_gather_base_predicated,
461 {Ty, Ptr->getType(), Mask->getType()},
462 {Ptr, Builder.getInt32(Increment), Mask});
463}
464
465Instruction *MVEGatherScatterLowering::tryCreateMaskedGatherBaseWB(
466 IntrinsicInst *I, Value *Ptr, IRBuilder<> &Builder, int64_t Increment) {
467 using namespace PatternMatch;
468 auto *Ty = cast<FixedVectorType>(I->getType());
469 LLVM_DEBUG(dbgs() << "masked gathers: loading from vector of pointers with "
470 << "writeback\n");
471 if (Ty->getNumElements() != 4 || Ty->getScalarSizeInBits() != 32)
472 // Can't build an intrinsic for this
473 return nullptr;
474 Value *Mask = I->getArgOperand(1);
475 if (match(Mask, m_One()))
476 return Builder.CreateIntrinsicWithoutFolding(
477 Intrinsic::arm_mve_vldr_gather_base_wb, {Ty, Ptr->getType()},
478 {Ptr, Builder.getInt32(Increment)});
479 return Builder.CreateIntrinsicWithoutFolding(
480 Intrinsic::arm_mve_vldr_gather_base_wb_predicated,
481 {Ty, Ptr->getType(), Mask->getType()},
482 {Ptr, Builder.getInt32(Increment), Mask});
483}
484
485Instruction *MVEGatherScatterLowering::tryCreateMaskedGatherOffset(
486 IntrinsicInst *I, Value *Ptr, Instruction *&Root, IRBuilder<> &Builder) {
487 using namespace PatternMatch;
488
489 Type *MemoryTy = I->getType();
490 Type *ResultTy = MemoryTy;
491
492 unsigned Unsigned = 1;
493 // The size of the gather was already checked in isLegalTypeAndAlignment;
494 // if it was not a full vector width an appropriate extend should follow.
495 auto *Extend = Root;
496 bool TruncResult = false;
497 if (MemoryTy->getPrimitiveSizeInBits() < 128) {
498 if (I->hasOneUse()) {
499 // If the gather has a single extend of the correct type, use an extending
500 // gather and replace the ext. In which case the correct root to replace
501 // is not the CallInst itself, but the instruction which extends it.
502 Instruction *User = *I->users().begin();
503 if (isa<SExtInst>(User) &&
504 User->getType()->getPrimitiveSizeInBits() == 128) {
505 LLVM_DEBUG(dbgs() << "masked gathers: Incorporating extend: "
506 << *User << "\n");
507 Extend = User;
508 ResultTy = User->getType();
509 Unsigned = 0;
510 } else if (isa<ZExtInst>(User) &&
511 User->getType()->getPrimitiveSizeInBits() == 128) {
512 LLVM_DEBUG(dbgs() << "masked gathers: Incorporating extend: "
513 << *ResultTy << "\n");
514 Extend = User;
515 ResultTy = User->getType();
516 }
517 }
518
519 // If an extend hasn't been found and the type is an integer, create an
520 // extending gather and truncate back to the original type.
521 if (ResultTy->getPrimitiveSizeInBits() < 128 &&
522 ResultTy->isIntOrIntVectorTy()) {
523 ResultTy = ResultTy->getWithNewBitWidth(
524 128 / cast<FixedVectorType>(ResultTy)->getNumElements());
525 TruncResult = true;
526 LLVM_DEBUG(dbgs() << "masked gathers: Small input type, truncing to: "
527 << *ResultTy << "\n");
528 }
529
530 // The final size of the gather must be a full vector width
531 if (ResultTy->getPrimitiveSizeInBits() != 128) {
532 LLVM_DEBUG(dbgs() << "masked gathers: Extend needed but not provided "
533 "from the correct type. Expanding\n");
534 return nullptr;
535 }
536 }
537
538 Value *Offsets;
539 int Scale;
540 Value *BasePtr = decomposePtr(
541 Ptr, Offsets, Scale, cast<FixedVectorType>(ResultTy), MemoryTy, Builder);
542 if (!BasePtr)
543 return nullptr;
544
545 Root = Extend;
546 Value *Mask = I->getArgOperand(1);
547 Instruction *Load = nullptr;
548 if (!match(Mask, m_One()))
550 Intrinsic::arm_mve_vldr_gather_offset_predicated,
551 {ResultTy, BasePtr->getType(), Offsets->getType(), Mask->getType()},
552 {BasePtr, Offsets, Builder.getInt32(MemoryTy->getScalarSizeInBits()),
553 Builder.getInt32(Scale), Builder.getInt32(Unsigned), Mask});
554 else
556 Intrinsic::arm_mve_vldr_gather_offset,
557 {ResultTy, BasePtr->getType(), Offsets->getType()},
558 {BasePtr, Offsets, Builder.getInt32(MemoryTy->getScalarSizeInBits()),
559 Builder.getInt32(Scale), Builder.getInt32(Unsigned)});
560
561 if (TruncResult) {
562 Load = TruncInst::Create(Instruction::Trunc, Load, MemoryTy);
563 Builder.Insert(Load);
564 }
565 return Load;
566}
567
568Instruction *MVEGatherScatterLowering::lowerScatter(IntrinsicInst *I) {
569 using namespace PatternMatch;
570 LLVM_DEBUG(dbgs() << "masked scatters: checking transform preconditions\n"
571 << *I << "\n");
572
573 // @llvm.masked.scatter.*(data, ptrs, alignment, mask)
574 // Attempt to turn the masked scatter in I into a MVE intrinsic
575 // Potentially optimising the addressing modes as we do so.
576 Value *Input = I->getArgOperand(0);
577 Value *Ptr = I->getArgOperand(1);
578 Align Alignment = I->getParamAlign(1).valueOrOne();
579 auto *Ty = cast<FixedVectorType>(Input->getType());
580
581 if (!isLegalTypeAndAlignment(Ty->getNumElements(), Ty->getScalarSizeInBits(),
582 Alignment))
583 return nullptr;
584
585 lookThroughBitcast(Ptr);
586 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
587
588 IRBuilder<> Builder(I);
589 Instruction *Store = tryCreateIncrementingGatScat(I, Ptr, Builder);
590 if (!Store)
591 Store = tryCreateMaskedScatterOffset(I, Ptr, Builder);
592 if (!Store)
593 Store = tryCreateMaskedScatterBase(I, Ptr, Builder);
594 if (!Store)
595 return nullptr;
596
597 LLVM_DEBUG(dbgs() << "masked scatters: successfully built masked scatter\n"
598 << *Store << "\n");
599 I->eraseFromParent();
600 return Store;
601}
602
603Instruction *MVEGatherScatterLowering::tryCreateMaskedScatterBase(
604 IntrinsicInst *I, Value *Ptr, IRBuilder<> &Builder, int64_t Increment) {
605 using namespace PatternMatch;
606 Value *Input = I->getArgOperand(0);
607 auto *Ty = cast<FixedVectorType>(Input->getType());
608 // Only QR variants allow truncating
609 if (!(Ty->getNumElements() == 4 && Ty->getScalarSizeInBits() == 32)) {
610 // Can't build an intrinsic for this
611 return nullptr;
612 }
613 Value *Mask = I->getArgOperand(2);
614 // int_arm_mve_vstr_scatter_base(_predicated) addr, offset, data(, mask)
615 LLVM_DEBUG(dbgs() << "masked scatters: storing to a vector of pointers\n");
616 if (match(Mask, m_One()))
617 return Builder.CreateIntrinsicWithoutFolding(
618 Intrinsic::arm_mve_vstr_scatter_base,
619 {Ptr->getType(), Input->getType()},
620 {Ptr, Builder.getInt32(Increment), Input});
621 return Builder.CreateIntrinsicWithoutFolding(
622 Intrinsic::arm_mve_vstr_scatter_base_predicated,
623 {Ptr->getType(), Input->getType(), Mask->getType()},
624 {Ptr, Builder.getInt32(Increment), Input, Mask});
625}
626
627Instruction *MVEGatherScatterLowering::tryCreateMaskedScatterBaseWB(
628 IntrinsicInst *I, Value *Ptr, IRBuilder<> &Builder, int64_t Increment) {
629 using namespace PatternMatch;
630 Value *Input = I->getArgOperand(0);
631 auto *Ty = cast<FixedVectorType>(Input->getType());
632 LLVM_DEBUG(dbgs() << "masked scatters: storing to a vector of pointers "
633 << "with writeback\n");
634 if (Ty->getNumElements() != 4 || Ty->getScalarSizeInBits() != 32)
635 // Can't build an intrinsic for this
636 return nullptr;
637 Value *Mask = I->getArgOperand(2);
638 if (match(Mask, m_One()))
639 return Builder.CreateIntrinsicWithoutFolding(
640 Intrinsic::arm_mve_vstr_scatter_base_wb,
641 {Ptr->getType(), Input->getType()},
642 {Ptr, Builder.getInt32(Increment), Input});
643 return Builder.CreateIntrinsicWithoutFolding(
644 Intrinsic::arm_mve_vstr_scatter_base_wb_predicated,
645 {Ptr->getType(), Input->getType(), Mask->getType()},
646 {Ptr, Builder.getInt32(Increment), Input, Mask});
647}
648
649Instruction *MVEGatherScatterLowering::tryCreateMaskedScatterOffset(
650 IntrinsicInst *I, Value *Ptr, IRBuilder<> &Builder) {
651 using namespace PatternMatch;
652 Value *Input = I->getArgOperand(0);
653 Value *Mask = I->getArgOperand(2);
654 Type *InputTy = Input->getType();
655 Type *MemoryTy = InputTy;
656
657 LLVM_DEBUG(dbgs() << "masked scatters: getelementpointer found. Storing"
658 << " to base + vector of offsets\n");
659 // If the input has been truncated, try to integrate that trunc into the
660 // scatter instruction (we don't care about alignment here)
661 if (TruncInst *Trunc = dyn_cast<TruncInst>(Input)) {
662 Value *PreTrunc = Trunc->getOperand(0);
663 Type *PreTruncTy = PreTrunc->getType();
664 if (PreTruncTy->getPrimitiveSizeInBits() == 128) {
665 Input = PreTrunc;
666 InputTy = PreTruncTy;
667 }
668 }
669 bool ExtendInput = false;
670 if (InputTy->getPrimitiveSizeInBits() < 128 &&
671 InputTy->isIntOrIntVectorTy()) {
672 // If we can't find a trunc to incorporate into the instruction, create an
673 // implicit one with a zext, so that we can still create a scatter. We know
674 // that the input type is 4x/8x/16x and of type i8/i16/i32, so any type
675 // smaller than 128 bits will divide evenly into a 128bit vector.
676 InputTy = InputTy->getWithNewBitWidth(
677 128 / cast<FixedVectorType>(InputTy)->getNumElements());
678 ExtendInput = true;
679 LLVM_DEBUG(dbgs() << "masked scatters: Small input type, will extend:\n"
680 << *Input << "\n");
681 }
682 if (InputTy->getPrimitiveSizeInBits() != 128) {
683 LLVM_DEBUG(dbgs() << "masked scatters: cannot create scatters for "
684 "non-standard input types. Expanding.\n");
685 return nullptr;
686 }
687
688 Value *Offsets;
689 int Scale;
690 Value *BasePtr = decomposePtr(
691 Ptr, Offsets, Scale, cast<FixedVectorType>(InputTy), MemoryTy, Builder);
692 if (!BasePtr)
693 return nullptr;
694
695 if (ExtendInput)
696 Input = Builder.CreateZExt(Input, InputTy);
697 if (!match(Mask, m_One()))
698 return Builder.CreateIntrinsicWithoutFolding(
699 Intrinsic::arm_mve_vstr_scatter_offset_predicated,
700 {BasePtr->getType(), Offsets->getType(), Input->getType(),
701 Mask->getType()},
703 Builder.getInt32(MemoryTy->getScalarSizeInBits()),
704 Builder.getInt32(Scale), Mask});
705 return Builder.CreateIntrinsicWithoutFolding(
706 Intrinsic::arm_mve_vstr_scatter_offset,
707 {BasePtr->getType(), Offsets->getType(), Input->getType()},
709 Builder.getInt32(MemoryTy->getScalarSizeInBits()),
710 Builder.getInt32(Scale)});
711}
712
713Instruction *MVEGatherScatterLowering::tryCreateIncrementingGatScat(
714 IntrinsicInst *I, Value *Ptr, IRBuilder<> &Builder) {
715 FixedVectorType *Ty;
716 if (I->getIntrinsicID() == Intrinsic::masked_gather)
717 Ty = cast<FixedVectorType>(I->getType());
718 else
719 Ty = cast<FixedVectorType>(I->getArgOperand(0)->getType());
720
721 // Incrementing gathers only exist for v4i32
722 if (Ty->getNumElements() != 4 || Ty->getScalarSizeInBits() != 32)
723 return nullptr;
724 // Incrementing gathers are not beneficial outside of a loop
725 Loop *L = LI->getLoopFor(I->getParent());
726 if (L == nullptr)
727 return nullptr;
728
729 // Decompose the GEP into Base and Offsets
730 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
731 Value *Offsets;
732 Value *BasePtr = decomposeGEP(Offsets, Ty, GEP, Builder);
733 if (!BasePtr)
734 return nullptr;
735
736 LLVM_DEBUG(dbgs() << "masked gathers/scatters: trying to build incrementing "
737 "wb gather/scatter\n");
738
739 // The gep was in charge of making sure the offsets are scaled correctly
740 // - calculate that factor so it can be applied by hand
741 int TypeScale =
742 computeScale(DL->getTypeAllocSizeInBits(GEP->getSourceElementType()),
743 DL->getTypeSizeInBits(GEP->getType()) /
744 cast<FixedVectorType>(GEP->getType())->getNumElements());
745 if (TypeScale == -1)
746 return nullptr;
747
748 if (GEP->hasOneUse()) {
749 // Only in this case do we want to build a wb gather, because the wb will
750 // change the phi which does affect other users of the gep (which will still
751 // be using the phi in the old way)
752 if (auto *Load = tryCreateIncrementingWBGatScat(I, BasePtr, Offsets,
753 TypeScale, Builder))
754 return Load;
755 }
756
757 LLVM_DEBUG(dbgs() << "masked gathers/scatters: trying to build incrementing "
758 "non-wb gather/scatter\n");
759
760 std::pair<Value *, int64_t> Add = getVarAndConst(Offsets, TypeScale);
761 if (Add.first == nullptr)
762 return nullptr;
763 Value *OffsetsIncoming = Add.first;
764 int64_t Immediate = Add.second;
765
766 // Make sure the offsets are scaled correctly
767 Instruction *ScaledOffsets = BinaryOperator::Create(
768 Instruction::Shl, OffsetsIncoming,
769 Builder.CreateVectorSplat(Ty->getNumElements(),
770 Builder.getInt32(TypeScale)),
771 "ScaledIndex", I->getIterator());
772 // Add the base to the offsets
773 OffsetsIncoming = BinaryOperator::Create(
774 Instruction::Add, ScaledOffsets,
775 Builder.CreateVectorSplat(
776 Ty->getNumElements(),
777 Builder.CreatePtrToInt(
778 BasePtr,
779 cast<VectorType>(ScaledOffsets->getType())->getElementType())),
780 "StartIndex", I->getIterator());
781
782 if (I->getIntrinsicID() == Intrinsic::masked_gather)
783 return tryCreateMaskedGatherBase(I, OffsetsIncoming, Builder, Immediate);
784 else
785 return tryCreateMaskedScatterBase(I, OffsetsIncoming, Builder, Immediate);
786}
787
788Instruction *MVEGatherScatterLowering::tryCreateIncrementingWBGatScat(
789 IntrinsicInst *I, Value *BasePtr, Value *Offsets, unsigned TypeScale,
790 IRBuilder<> &Builder) {
791 // Check whether this gather's offset is incremented by a constant - if so,
792 // and the load is of the right type, we can merge this into a QI gather
793 Loop *L = LI->getLoopFor(I->getParent());
794 // Offsets that are worth merging into this instruction will be incremented
795 // by a constant, thus we're looking for an add of a phi and a constant
796 PHINode *Phi = dyn_cast<PHINode>(Offsets);
797 if (Phi == nullptr || Phi->getNumIncomingValues() != 2 ||
798 Phi->getParent() != L->getHeader() || !Phi->hasNUses(2))
799 // No phi means no IV to write back to; if there is a phi, we expect it
800 // to have exactly two incoming values; the only phis we are interested in
801 // will be loop IV's and have exactly two uses, one in their increment and
802 // one in the gather's gep
803 return nullptr;
804
805 unsigned IncrementIndex =
806 Phi->getIncomingBlock(0) == L->getLoopLatch() ? 0 : 1;
807 // Look through the phi to the phi increment
808 Offsets = Phi->getIncomingValue(IncrementIndex);
809
810 std::pair<Value *, int64_t> Add = getVarAndConst(Offsets, TypeScale);
811 if (Add.first == nullptr)
812 return nullptr;
813 Value *OffsetsIncoming = Add.first;
814 int64_t Immediate = Add.second;
815 if (OffsetsIncoming != Phi)
816 // Then the increment we are looking at is not an increment of the
817 // induction variable, and we don't want to do a writeback
818 return nullptr;
819
820 Builder.SetInsertPoint(&Phi->getIncomingBlock(1 - IncrementIndex)->back());
821 unsigned NumElems =
822 cast<FixedVectorType>(OffsetsIncoming->getType())->getNumElements();
823
824 // Make sure the offsets are scaled correctly
825 Instruction *ScaledOffsets = BinaryOperator::Create(
826 Instruction::Shl, Phi->getIncomingValue(1 - IncrementIndex),
827 Builder.CreateVectorSplat(NumElems, Builder.getInt32(TypeScale)),
828 "ScaledIndex",
829 Phi->getIncomingBlock(1 - IncrementIndex)->back().getIterator());
830 // Add the base to the offsets
831 OffsetsIncoming = BinaryOperator::Create(
832 Instruction::Add, ScaledOffsets,
833 Builder.CreateVectorSplat(
834 NumElems,
835 Builder.CreatePtrToInt(
836 BasePtr,
837 cast<VectorType>(ScaledOffsets->getType())->getElementType())),
838 "StartIndex",
839 Phi->getIncomingBlock(1 - IncrementIndex)->back().getIterator());
840 // The gather is pre-incrementing
841 OffsetsIncoming = BinaryOperator::Create(
842 Instruction::Sub, OffsetsIncoming,
843 Builder.CreateVectorSplat(NumElems, Builder.getInt32(Immediate)),
844 "PreIncrementStartIndex",
845 Phi->getIncomingBlock(1 - IncrementIndex)->back().getIterator());
846 Phi->setIncomingValue(1 - IncrementIndex, OffsetsIncoming);
847
848 Builder.SetInsertPoint(I);
849
850 Instruction *EndResult;
851 Instruction *NewInduction;
852 if (I->getIntrinsicID() == Intrinsic::masked_gather) {
853 // Build the incrementing gather
854 Value *Load = tryCreateMaskedGatherBaseWB(I, Phi, Builder, Immediate);
855 // One value to be handed to whoever uses the gather, one is the loop
856 // increment
857 EndResult = ExtractValueInst::Create(Load, 0, "Gather");
858 NewInduction = ExtractValueInst::Create(Load, 1, "GatherIncrement");
859 Builder.Insert(EndResult);
860 Builder.Insert(NewInduction);
861 } else {
862 // Build the incrementing scatter
863 EndResult = NewInduction =
864 tryCreateMaskedScatterBaseWB(I, Phi, Builder, Immediate);
865 }
866 Instruction *AddInst = cast<Instruction>(Offsets);
867 AddInst->replaceAllUsesWith(NewInduction);
868 AddInst->eraseFromParent();
869 Phi->setIncomingValue(IncrementIndex, NewInduction);
870
871 return EndResult;
872}
873
874void MVEGatherScatterLowering::pushOutAdd(PHINode *&Phi,
875 Value *OffsSecondOperand,
876 unsigned StartIndex) {
877 LLVM_DEBUG(dbgs() << "masked gathers/scatters: optimising add instruction\n");
878 assert(Phi->getNumIncomingValues() == 2);
879 BasicBlock *NewIndexBlock = Phi->getIncomingBlock(StartIndex);
880 BasicBlock::iterator InsertionPoint = NewIndexBlock->back().getIterator();
881 // Initialize the phi with a vector that contains a sum of the constants
883 Instruction::Add, Phi->getIncomingValue(StartIndex), OffsSecondOperand,
884 "PushedOutAdd", InsertionPoint);
885 unsigned IncrementIndex = StartIndex == 0 ? 1 : 0;
886
887 // Order such that start index comes first (this reduces mov's)
888 Value *IncrementIndexValue = Phi->getIncomingValue(IncrementIndex);
889 BasicBlock *IncrementIndexBlock = Phi->getIncomingBlock(IncrementIndex);
890 Phi->setIncomingValue(0, NewIndex);
891 Phi->setIncomingBlock(0, NewIndexBlock);
892 Phi->setIncomingValue(1, IncrementIndexValue);
893 Phi->setIncomingBlock(1, IncrementIndexBlock);
894}
895
896void MVEGatherScatterLowering::pushOutMulShl(unsigned Opcode, PHINode *&Phi,
897 Value *IncrementPerRound,
898 Value *OffsSecondOperand,
899 unsigned LoopIncrement,
900 IRBuilder<> &Builder) {
901 LLVM_DEBUG(dbgs() << "masked gathers/scatters: optimising mul instruction\n");
902 assert(Phi->getNumIncomingValues() == 2);
903
904 // Create a new scalar add outside of the loop and transform it to a splat
905 // by which loop variable can be incremented
906 BasicBlock *StartIndexBlock =
907 Phi->getIncomingBlock(LoopIncrement == 1 ? 0 : 1);
908 BasicBlock::iterator InsertionPoint = StartIndexBlock->back().getIterator();
909
910 // Create a new index
911 Value *StartIndex =
913 Phi->getIncomingValue(LoopIncrement == 1 ? 0 : 1),
914 OffsSecondOperand, "PushedOutMul", InsertionPoint);
915
916 Instruction *Product =
917 BinaryOperator::Create((Instruction::BinaryOps)Opcode, IncrementPerRound,
918 OffsSecondOperand, "Product", InsertionPoint);
919 BasicBlock *NewIncrementBlock = Phi->getIncomingBlock(LoopIncrement);
920 BasicBlock::iterator NewIncrInsertPt =
921 NewIncrementBlock->back().getIterator();
922 NewIncrInsertPt = std::prev(NewIncrInsertPt);
923
924 // Increment NewIndex by Product instead of the multiplication
925 Instruction *NewIncrement = BinaryOperator::Create(
926 Instruction::Add, Phi, Product, "IncrementPushedOutMul", NewIncrInsertPt);
927
928 Phi->setIncomingValue(0, StartIndex);
929 Phi->setIncomingBlock(0, StartIndexBlock);
930 Phi->setIncomingValue(1, NewIncrement);
931 Phi->setIncomingBlock(1, NewIncrementBlock);
932}
933
934// Check whether all usages of this instruction are as offsets of
935// gathers/scatters or simple arithmetics only used by gathers/scatters
937 if (I->use_empty()) {
938 return false;
939 }
940 bool Gatscat = true;
941 for (Instruction *U : I->users()) {
942 if (isa<GetElementPtrInst>(U) ||
944 return Gatscat;
945 } else {
946 unsigned OpCode = U->getOpcode();
947 if ((OpCode == Instruction::Add || OpCode == Instruction::Mul ||
948 OpCode == Instruction::Shl || isAddLikeOr(U, DL)) &&
950 continue;
951 }
952 return false;
953 }
954 }
955 return Gatscat;
956}
957
958bool MVEGatherScatterLowering::optimiseOffsets(Value *Offsets, BasicBlock *BB,
959 LoopInfo *LI) {
960 LLVM_DEBUG(dbgs() << "masked gathers/scatters: trying to optimize: "
961 << *Offsets << "\n");
962 // Optimise the addresses of gathers/scatters by moving invariant
963 // calculations out of the loop
964 if (!isa<Instruction>(Offsets))
965 return false;
966 Instruction *Offs = cast<Instruction>(Offsets);
967 if (Offs->getOpcode() != Instruction::Add && !isAddLikeOr(Offs, *DL) &&
968 Offs->getOpcode() != Instruction::Mul &&
969 Offs->getOpcode() != Instruction::Shl)
970 return false;
971 Loop *L = LI->getLoopFor(BB);
972 if (L == nullptr)
973 return false;
974 if (!Offs->hasOneUse()) {
975 if (!hasAllGatScatUsers(Offs, *DL))
976 return false;
977 }
978
979 // Find out which, if any, operand of the instruction
980 // is a phi node
981 PHINode *Phi;
982 int OffsSecondOp;
983 if (isa<PHINode>(Offs->getOperand(0))) {
984 Phi = cast<PHINode>(Offs->getOperand(0));
985 OffsSecondOp = 1;
986 } else if (isa<PHINode>(Offs->getOperand(1))) {
987 Phi = cast<PHINode>(Offs->getOperand(1));
988 OffsSecondOp = 0;
989 } else {
990 bool Changed = false;
991 if (isa<Instruction>(Offs->getOperand(0)) &&
992 L->contains(cast<Instruction>(Offs->getOperand(0))))
993 Changed |= optimiseOffsets(Offs->getOperand(0), BB, LI);
994 if (isa<Instruction>(Offs->getOperand(1)) &&
995 L->contains(cast<Instruction>(Offs->getOperand(1))))
996 Changed |= optimiseOffsets(Offs->getOperand(1), BB, LI);
997 if (!Changed)
998 return false;
999 if (isa<PHINode>(Offs->getOperand(0))) {
1000 Phi = cast<PHINode>(Offs->getOperand(0));
1001 OffsSecondOp = 1;
1002 } else if (isa<PHINode>(Offs->getOperand(1))) {
1003 Phi = cast<PHINode>(Offs->getOperand(1));
1004 OffsSecondOp = 0;
1005 } else {
1006 return false;
1007 }
1008 }
1009 // A phi node we want to perform this function on should be from the
1010 // loop header.
1011 if (Phi->getParent() != L->getHeader())
1012 return false;
1013
1014 // We're looking for a simple add recurrence.
1015 BinaryOperator *IncInstruction;
1016 Value *Start, *IncrementPerRound;
1017 if (!matchSimpleRecurrence(Phi, IncInstruction, Start, IncrementPerRound) ||
1018 IncInstruction->getOpcode() != Instruction::Add)
1019 return false;
1020
1021 int IncrementingBlock = Phi->getIncomingValue(0) == IncInstruction ? 0 : 1;
1022
1023 // Get the value that is added to/multiplied with the phi
1024 Value *OffsSecondOperand = Offs->getOperand(OffsSecondOp);
1025
1026 if (IncrementPerRound->getType() != OffsSecondOperand->getType() ||
1027 !L->isLoopInvariant(OffsSecondOperand))
1028 // Something has gone wrong, abort
1029 return false;
1030
1031 // Only proceed if the increment per round is a constant or an instruction
1032 // which does not originate from within the loop
1033 if (!isa<Constant>(IncrementPerRound) &&
1034 !(isa<Instruction>(IncrementPerRound) &&
1035 !L->contains(cast<Instruction>(IncrementPerRound))))
1036 return false;
1037
1038 // If the phi is not used by anything else, we can just adapt it when
1039 // replacing the instruction; if it is, we'll have to duplicate it
1040 PHINode *NewPhi;
1041 if (Phi->hasNUses(2) && IncInstruction->hasOneUse()) {
1042 // No other users -> reuse existing phi (One user is the instruction
1043 // we're looking at, the other is the phi increment)
1044 NewPhi = Phi;
1045 } else {
1046 // There are other users -> create a new phi
1047 NewPhi = PHINode::Create(Phi->getType(), 2, "NewPhi", Phi->getIterator());
1048 // Copy the incoming values of the old phi
1049 NewPhi->addIncoming(Phi->getIncomingValue(IncrementingBlock == 1 ? 0 : 1),
1050 Phi->getIncomingBlock(IncrementingBlock == 1 ? 0 : 1));
1051 IncInstruction = BinaryOperator::Create(
1052 Instruction::BinaryOps(IncInstruction->getOpcode()), NewPhi,
1053 IncrementPerRound, "LoopIncrement", IncInstruction->getIterator());
1054 NewPhi->addIncoming(IncInstruction,
1055 Phi->getIncomingBlock(IncrementingBlock));
1056 IncrementingBlock = 1;
1057 }
1058
1059 IRBuilder<> Builder(Phi);
1060 Builder.SetCurrentDebugLocation(Offs->getDebugLoc());
1061
1062 switch (Offs->getOpcode()) {
1063 case Instruction::Add:
1064 case Instruction::Or:
1065 pushOutAdd(NewPhi, OffsSecondOperand, IncrementingBlock == 1 ? 0 : 1);
1066 break;
1067 case Instruction::Mul:
1068 case Instruction::Shl:
1069 pushOutMulShl(Offs->getOpcode(), NewPhi, IncrementPerRound,
1070 OffsSecondOperand, IncrementingBlock, Builder);
1071 break;
1072 default:
1073 return false;
1074 }
1075 LLVM_DEBUG(dbgs() << "masked gathers/scatters: simplified loop variable "
1076 << "add/mul\n");
1077
1078 // The instruction has now been "absorbed" into the phi value
1079 Offs->replaceAllUsesWith(NewPhi);
1080 Offs->eraseFromParent();
1081 // Clean up the old increment in case it's unused because we built a new
1082 // one
1083 if (IncInstruction->use_empty())
1084 IncInstruction->eraseFromParent();
1085
1086 return true;
1087}
1088
1089static Value *CheckAndCreateOffsetAdd(Value *X, unsigned ScaleX, Value *Y,
1090 unsigned ScaleY, IRBuilder<> &Builder) {
1091 // Splat the non-vector value to a vector of the given type - if the value is
1092 // a constant (and its value isn't too big), we can even use this opportunity
1093 // to scale it to the size of the vector elements
1094 auto FixSummands = [&Builder](FixedVectorType *&VT, Value *&NonVectorVal) {
1095 ConstantInt *Const;
1096 if ((Const = dyn_cast<ConstantInt>(NonVectorVal)) &&
1097 VT->getElementType() != NonVectorVal->getType()) {
1098 unsigned TargetElemSize = VT->getElementType()->getPrimitiveSizeInBits();
1099 uint64_t N = Const->getZExtValue();
1100 if (N < (unsigned)(1 << (TargetElemSize - 1))) {
1101 NonVectorVal = Builder.CreateVectorSplat(
1102 VT->getNumElements(), Builder.getIntN(TargetElemSize, N));
1103 return;
1104 }
1105 }
1106 NonVectorVal =
1107 Builder.CreateVectorSplat(VT->getNumElements(), NonVectorVal);
1108 };
1109
1110 FixedVectorType *XElType = dyn_cast<FixedVectorType>(X->getType());
1111 FixedVectorType *YElType = dyn_cast<FixedVectorType>(Y->getType());
1112 // If one of X, Y is not a vector, we have to splat it in order
1113 // to add the two of them.
1114 if (XElType && !YElType) {
1115 FixSummands(XElType, Y);
1116 YElType = cast<FixedVectorType>(Y->getType());
1117 } else if (YElType && !XElType) {
1118 FixSummands(YElType, X);
1119 XElType = cast<FixedVectorType>(X->getType());
1120 } else if (!XElType && !YElType)
1121 return nullptr;
1122 assert(XElType && YElType && "Unknown vector types");
1123 // Check that the summands are of compatible types
1124 if (XElType != YElType) {
1125 LLVM_DEBUG(dbgs() << "masked gathers/scatters: incompatible gep offsets\n");
1126 return nullptr;
1127 }
1128
1129 if (XElType->getElementType()->getScalarSizeInBits() != 32) {
1130 // Check that by adding the vectors we do not accidentally
1131 // create an overflow
1132 Constant *ConstX = dyn_cast<Constant>(X);
1133 Constant *ConstY = dyn_cast<Constant>(Y);
1134 if (!ConstX || !ConstY)
1135 return nullptr;
1136 unsigned TargetElemSize = 128 / XElType->getNumElements();
1137 for (unsigned i = 0; i < XElType->getNumElements(); i++) {
1138 ConstantInt *ConstXEl =
1140 ConstantInt *ConstYEl =
1142 if (!ConstXEl || !ConstYEl ||
1143 ConstXEl->getZExtValue() * ScaleX +
1144 ConstYEl->getZExtValue() * ScaleY >=
1145 (unsigned)(1 << (TargetElemSize - 1)))
1146 return nullptr;
1147 }
1148 }
1149
1150 Value *XScale = Builder.CreateVectorSplat(
1151 XElType->getNumElements(),
1152 Builder.getIntN(XElType->getScalarSizeInBits(), ScaleX));
1153 Value *YScale = Builder.CreateVectorSplat(
1154 YElType->getNumElements(),
1155 Builder.getIntN(YElType->getScalarSizeInBits(), ScaleY));
1156 Value *Add = Builder.CreateAdd(Builder.CreateMul(X, XScale),
1157 Builder.CreateMul(Y, YScale));
1158
1159 if (checkOffsetSize(Add, XElType->getNumElements()))
1160 return Add;
1161 else
1162 return nullptr;
1163}
1164
1165Value *MVEGatherScatterLowering::foldGEP(GetElementPtrInst *GEP,
1166 Value *&Offsets, unsigned &Scale,
1167 IRBuilder<> &Builder) {
1168 Value *GEPPtr = GEP->getPointerOperand();
1169 Offsets = GEP->getOperand(1);
1170 Scale = DL->getTypeAllocSize(GEP->getSourceElementType());
1171 // We only merge geps with constant offsets, because only for those
1172 // we can make sure that we do not cause an overflow
1173 if (GEP->getNumIndices() != 1 || !isa<Constant>(Offsets))
1174 return nullptr;
1175 if (GetElementPtrInst *BaseGEP = dyn_cast<GetElementPtrInst>(GEPPtr)) {
1176 // Merge the two geps into one
1177 Value *BaseBasePtr = foldGEP(BaseGEP, Offsets, Scale, Builder);
1178 if (!BaseBasePtr)
1179 return nullptr;
1181 Offsets, Scale, GEP->getOperand(1),
1182 DL->getTypeAllocSize(GEP->getSourceElementType()), Builder);
1183 if (Offsets == nullptr)
1184 return nullptr;
1185 Scale = 1; // Scale is always an i8 at this point.
1186 return BaseBasePtr;
1187 }
1188 return GEPPtr;
1189}
1190
1191bool MVEGatherScatterLowering::optimiseAddress(Value *Address, BasicBlock *BB,
1192 LoopInfo *LI) {
1193 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Address);
1194 if (!GEP)
1195 return false;
1196 bool Changed = false;
1197 if (GEP->hasOneUse() && isa<GetElementPtrInst>(GEP->getPointerOperand())) {
1198 IRBuilder<> Builder(GEP);
1199 Value *Offsets;
1200 unsigned Scale;
1201 Value *Base = foldGEP(GEP, Offsets, Scale, Builder);
1202 // We only want to merge the geps if there is a real chance that they can be
1203 // used by an MVE gather; thus the offset has to have the correct size
1204 // (always i32 if it is not of vector type) and the base has to be a
1205 // pointer.
1206 if (Offsets && Base && Base != GEP) {
1207 assert(Scale == 1 && "Expected to fold GEP to a scale of 1");
1208 Type *BaseTy = Builder.getPtrTy();
1209 if (auto *VecTy = dyn_cast<FixedVectorType>(Base->getType()))
1210 BaseTy = FixedVectorType::get(BaseTy, VecTy);
1211 GetElementPtrInst *NewAddress = GetElementPtrInst::Create(
1212 Builder.getInt8Ty(), Builder.CreateBitCast(Base, BaseTy), Offsets,
1213 "gep.merged", GEP->getIterator());
1214 LLVM_DEBUG(dbgs() << "Folded GEP: " << *GEP
1215 << "\n new : " << *NewAddress << "\n");
1216 GEP->replaceAllUsesWith(
1217 Builder.CreateBitCast(NewAddress, GEP->getType()));
1218 GEP = NewAddress;
1219 Changed = true;
1220 }
1221 }
1222 Changed |= optimiseOffsets(GEP->getOperand(1), GEP->getParent(), LI);
1223 return Changed;
1224}
1225
1226bool MVEGatherScatterLowering::runOnFunction(Function &F) {
1227 auto &TPC = getAnalysis<TargetPassConfig>();
1228 auto &TM = TPC.getTM<TargetMachine>();
1229 auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
1230 if (!ST->getCLOpts().maskedgatscat || !ST->hasMVEIntegerOps())
1231 return false;
1232 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1233 DL = &F.getDataLayout();
1236
1237 bool Changed = false;
1238
1239 for (BasicBlock &BB : F) {
1241
1242 for (Instruction &I : BB) {
1243 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1244 if (II && II->getIntrinsicID() == Intrinsic::masked_gather &&
1245 isa<FixedVectorType>(II->getType())) {
1246 Gathers.push_back(II);
1247 Changed |= optimiseAddress(II->getArgOperand(0), II->getParent(), LI);
1248 } else if (II && II->getIntrinsicID() == Intrinsic::masked_scatter &&
1249 isa<FixedVectorType>(II->getArgOperand(0)->getType())) {
1250 Scatters.push_back(II);
1251 Changed |= optimiseAddress(II->getArgOperand(1), II->getParent(), LI);
1252 }
1253 }
1254 }
1255 for (IntrinsicInst *I : Gathers) {
1256 Instruction *L = lowerGather(I);
1257 if (L == nullptr)
1258 continue;
1259
1260 // Get rid of any now dead instructions
1261 SimplifyInstructionsInBlock(L->getParent());
1262 Changed = true;
1263 }
1264
1265 for (IntrinsicInst *I : Scatters) {
1266 Instruction *S = lowerScatter(I);
1267 if (S == nullptr)
1268 continue;
1269
1270 // Get rid of any now dead instructions
1272 Changed = true;
1273 }
1274 return Changed;
1275}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Decomposition decomposeGEP(GEPOperator &GEP, ConstraintInfo &Info, bool IsSigned, const DataLayout &DL)
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Common GEP
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isAddLikeOr(Instruction *I, const DataLayout &DL)
static bool hasAllGatScatUsers(Instruction *I, const DataLayout &DL)
static bool checkOffsetSize(Value *Offsets, unsigned TargetElemCount)
static Value * CheckAndCreateOffsetAdd(Value *X, unsigned ScaleX, Value *Y, unsigned ScaleY, IRBuilder<> &Builder)
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Instruction & back() const
Definition BasicBlock.h:464
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Type * getDestTy() const
Return the destination type, as a convenience.
Definition InstrTypes.h:681
This is the shared class of boolean and integer constants.
Definition Constants.h:87
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
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:63
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2314
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:528
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:471
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition IRBuilder.h:148
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
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
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:571
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:518
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.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
A wrapper class for inspecting calls to intrinsic functions.
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:623
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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 LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition Pass.cpp:114
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Target-Independent Code Generator Pass Configuration Options.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
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
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
bool use_empty() const
Definition Value.h:348
Type * getElementType() const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
bool match(Val *V, const Pattern &P)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
Offsets
Offsets in bytes from the start of the input buffer.
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:118
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
Pass * createMVEGatherScatterLoweringPass()
LLVM_ABI bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition Local.cpp:716
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,...
bool isGatherScatter(IntrinsicInst *IntInst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
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
@ Add
Sum of integers.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void initializeMVEGatherScatterLoweringPass(PassRegistry &)
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39