blob: bbdea4de4e28e02d2b8b02b1a3463d8550ca1397 [file] [log] [blame]
David Blaikie1213dbf2015-06-26 16:57:30 +00001//===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines vectorizer utilities.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "llvm/Analysis/VectorUtils.h"
James Molloy55d633b2015-10-12 12:34:45 +000015#include "llvm/ADT/EquivalenceClasses.h"
16#include "llvm/Analysis/DemandedBits.h"
Hal Finkel9cf58c42015-07-11 10:52:42 +000017#include "llvm/Analysis/LoopInfo.h"
Florian Hahn1086ce22018-09-12 08:01:57 +000018#include "llvm/Analysis/LoopIterator.h"
Hal Finkel9cf58c42015-07-11 10:52:42 +000019#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000020#include "llvm/Analysis/ScalarEvolutionExpressions.h"
James Molloy55d633b2015-10-12 12:34:45 +000021#include "llvm/Analysis/TargetTransformInfo.h"
David Majnemerb4b27232016-04-19 19:10:21 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000023#include "llvm/IR/Constants.h"
Hal Finkel9cf58c42015-07-11 10:52:42 +000024#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/IR/IRBuilder.h"
Hal Finkel9cf58c42015-07-11 10:52:42 +000026#include "llvm/IR/PatternMatch.h"
27#include "llvm/IR/Value.h"
Renato Golin3b1d3b02015-08-30 10:49:04 +000028
Florian Hahn1086ce22018-09-12 08:01:57 +000029#define DEBUG_TYPE "vectorutils"
30
David Majnemer5eaf08f2015-08-18 22:07:20 +000031using namespace llvm;
32using namespace llvm::PatternMatch;
David Blaikie1213dbf2015-06-26 16:57:30 +000033
Florian Hahn1086ce22018-09-12 08:01:57 +000034/// Maximum factor for an interleaved memory access.
35static cl::opt<unsigned> MaxInterleaveGroupFactor(
36 "max-interleave-group-factor", cl::Hidden,
37 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
38 cl::init(8));
39
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000040/// Identify if the intrinsic is trivially vectorizable.
David Blaikie1213dbf2015-06-26 16:57:30 +000041/// This method returns true if the intrinsic's argument types are all
42/// scalars for the scalar form of the intrinsic and all vectors for
43/// the vector form of the intrinsic.
44bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
45 switch (ID) {
46 case Intrinsic::sqrt:
47 case Intrinsic::sin:
48 case Intrinsic::cos:
49 case Intrinsic::exp:
50 case Intrinsic::exp2:
51 case Intrinsic::log:
52 case Intrinsic::log10:
53 case Intrinsic::log2:
54 case Intrinsic::fabs:
55 case Intrinsic::minnum:
56 case Intrinsic::maxnum:
57 case Intrinsic::copysign:
58 case Intrinsic::floor:
59 case Intrinsic::ceil:
60 case Intrinsic::trunc:
61 case Intrinsic::rint:
62 case Intrinsic::nearbyint:
63 case Intrinsic::round:
64 case Intrinsic::bswap:
Simon Pilgrimba319de2016-06-04 20:21:07 +000065 case Intrinsic::bitreverse:
David Blaikie1213dbf2015-06-26 16:57:30 +000066 case Intrinsic::ctpop:
67 case Intrinsic::pow:
68 case Intrinsic::fma:
69 case Intrinsic::fmuladd:
70 case Intrinsic::ctlz:
71 case Intrinsic::cttz:
72 case Intrinsic::powi:
73 return true;
74 default:
75 return false;
76 }
77}
78
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000079/// Identifies if the intrinsic has a scalar operand. It check for
David Blaikie1213dbf2015-06-26 16:57:30 +000080/// ctlz,cttz and powi special intrinsics whose argument is scalar.
81bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,
82 unsigned ScalarOpdIdx) {
83 switch (ID) {
84 case Intrinsic::ctlz:
85 case Intrinsic::cttz:
86 case Intrinsic::powi:
87 return (ScalarOpdIdx == 1);
88 default:
89 return false;
90 }
91}
92
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000093/// Returns intrinsic ID for call.
David Blaikie1213dbf2015-06-26 16:57:30 +000094/// For the input call instruction it finds mapping intrinsic and returns
95/// its ID, in case it does not found it return not_intrinsic.
David Majnemerb4b27232016-04-19 19:10:21 +000096Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
97 const TargetLibraryInfo *TLI) {
98 Intrinsic::ID ID = getIntrinsicForCallSite(CI, TLI);
99 if (ID == Intrinsic::not_intrinsic)
David Blaikie1213dbf2015-06-26 16:57:30 +0000100 return Intrinsic::not_intrinsic;
101
David Majnemerb4b27232016-04-19 19:10:21 +0000102 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
Dan Gohman2c74fe92017-11-08 21:59:51 +0000103 ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
104 ID == Intrinsic::sideeffect)
David Majnemerb4b27232016-04-19 19:10:21 +0000105 return ID;
David Blaikie1213dbf2015-06-26 16:57:30 +0000106 return Intrinsic::not_intrinsic;
107}
Hal Finkel9cf58c42015-07-11 10:52:42 +0000108
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000109/// Find the operand of the GEP that should be checked for consecutive
Hal Finkel9cf58c42015-07-11 10:52:42 +0000110/// stores. This ignores trailing indices that have no effect on the final
111/// pointer.
112unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
113 const DataLayout &DL = Gep->getModule()->getDataLayout();
114 unsigned LastOperand = Gep->getNumOperands() - 1;
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000115 unsigned GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
Hal Finkel9cf58c42015-07-11 10:52:42 +0000116
117 // Walk backwards and try to peel off zeros.
David Majnemer5eaf08f2015-08-18 22:07:20 +0000118 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
Hal Finkel9cf58c42015-07-11 10:52:42 +0000119 // Find the type we're currently indexing into.
120 gep_type_iterator GEPTI = gep_type_begin(Gep);
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000121 std::advance(GEPTI, LastOperand - 2);
Hal Finkel9cf58c42015-07-11 10:52:42 +0000122
123 // If it's a type with the same allocation size as the result of the GEP we
124 // can peel off the zero index.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000125 if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
Hal Finkel9cf58c42015-07-11 10:52:42 +0000126 break;
127 --LastOperand;
128 }
129
130 return LastOperand;
131}
132
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000133/// If the argument is a GEP, then returns the operand identified by
Hal Finkel9cf58c42015-07-11 10:52:42 +0000134/// getGEPInductionOperand. However, if there is some other non-loop-invariant
135/// operand, it returns that instead.
David Majnemer5eaf08f2015-08-18 22:07:20 +0000136Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
Hal Finkel9cf58c42015-07-11 10:52:42 +0000137 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
138 if (!GEP)
139 return Ptr;
140
141 unsigned InductionOperand = getGEPInductionOperand(GEP);
142
143 // Check that all of the gep indices are uniform except for our induction
144 // operand.
145 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
146 if (i != InductionOperand &&
147 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
148 return Ptr;
149 return GEP->getOperand(InductionOperand);
150}
151
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000152/// If a value has only one user that is a CastInst, return it.
David Majnemer5eaf08f2015-08-18 22:07:20 +0000153Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
154 Value *UniqueCast = nullptr;
Hal Finkel9cf58c42015-07-11 10:52:42 +0000155 for (User *U : Ptr->users()) {
156 CastInst *CI = dyn_cast<CastInst>(U);
157 if (CI && CI->getType() == Ty) {
158 if (!UniqueCast)
159 UniqueCast = CI;
160 else
161 return nullptr;
162 }
163 }
164 return UniqueCast;
165}
166
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000167/// Get the stride of a pointer access in a loop. Looks for symbolic
Hal Finkel9cf58c42015-07-11 10:52:42 +0000168/// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
David Majnemer5eaf08f2015-08-18 22:07:20 +0000169Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
Craig Toppere3dcce92015-08-01 22:20:21 +0000170 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
Hal Finkel9cf58c42015-07-11 10:52:42 +0000171 if (!PtrTy || PtrTy->isAggregateType())
172 return nullptr;
173
174 // Try to remove a gep instruction to make the pointer (actually index at this
Vedant Kumard3196742018-02-28 19:08:52 +0000175 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
Hal Finkel9cf58c42015-07-11 10:52:42 +0000176 // pointer, otherwise, we are analyzing the index.
David Majnemer5eaf08f2015-08-18 22:07:20 +0000177 Value *OrigPtr = Ptr;
Hal Finkel9cf58c42015-07-11 10:52:42 +0000178
179 // The size of the pointer access.
180 int64_t PtrAccessSize = 1;
181
182 Ptr = stripGetElementPtr(Ptr, SE, Lp);
183 const SCEV *V = SE->getSCEV(Ptr);
184
185 if (Ptr != OrigPtr)
186 // Strip off casts.
187 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
188 V = C->getOperand();
189
190 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
191 if (!S)
192 return nullptr;
193
194 V = S->getStepRecurrence(*SE);
195 if (!V)
196 return nullptr;
197
198 // Strip off the size of access multiplication if we are still analyzing the
199 // pointer.
200 if (OrigPtr == Ptr) {
Hal Finkel9cf58c42015-07-11 10:52:42 +0000201 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
202 if (M->getOperand(0)->getSCEVType() != scConstant)
203 return nullptr;
204
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000205 const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
Hal Finkel9cf58c42015-07-11 10:52:42 +0000206
207 // Huge step value - give up.
208 if (APStepVal.getBitWidth() > 64)
209 return nullptr;
210
211 int64_t StepVal = APStepVal.getSExtValue();
212 if (PtrAccessSize != StepVal)
213 return nullptr;
214 V = M->getOperand(1);
215 }
216 }
217
218 // Strip off casts.
219 Type *StripedOffRecurrenceCast = nullptr;
220 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
221 StripedOffRecurrenceCast = C->getType();
222 V = C->getOperand();
223 }
224
225 // Look for the loop invariant symbolic value.
226 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
227 if (!U)
228 return nullptr;
229
David Majnemer5eaf08f2015-08-18 22:07:20 +0000230 Value *Stride = U->getValue();
Hal Finkel9cf58c42015-07-11 10:52:42 +0000231 if (!Lp->isLoopInvariant(Stride))
232 return nullptr;
233
234 // If we have stripped off the recurrence cast we have to make sure that we
235 // return the value that is used in this loop so that we can replace it later.
236 if (StripedOffRecurrenceCast)
237 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
238
239 return Stride;
240}
David Majnemer599ca442015-07-13 01:15:53 +0000241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000242/// Given a vector and an element number, see if the scalar value is
David Majnemer599ca442015-07-13 01:15:53 +0000243/// already around as a register, for example if it were inserted then extracted
244/// from the vector.
David Majnemer5eaf08f2015-08-18 22:07:20 +0000245Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
David Majnemer599ca442015-07-13 01:15:53 +0000246 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
247 VectorType *VTy = cast<VectorType>(V->getType());
248 unsigned Width = VTy->getNumElements();
249 if (EltNo >= Width) // Out of range access.
250 return UndefValue::get(VTy->getElementType());
251
252 if (Constant *C = dyn_cast<Constant>(V))
253 return C->getAggregateElement(EltNo);
254
255 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
256 // If this is an insert to a variable element, we don't know what it is.
257 if (!isa<ConstantInt>(III->getOperand(2)))
258 return nullptr;
259 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
260
261 // If this is an insert to the element we are looking for, return the
262 // inserted value.
263 if (EltNo == IIElt)
264 return III->getOperand(1);
265
266 // Otherwise, the insertelement doesn't modify the value, recurse on its
267 // vector input.
268 return findScalarElement(III->getOperand(0), EltNo);
269 }
270
271 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
272 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
273 int InEl = SVI->getMaskValue(EltNo);
274 if (InEl < 0)
275 return UndefValue::get(VTy->getElementType());
276 if (InEl < (int)LHSWidth)
277 return findScalarElement(SVI->getOperand(0), InEl);
278 return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
279 }
280
281 // Extract a value from a vector add operation with a constant zero.
282 Value *Val = nullptr; Constant *Con = nullptr;
David Majnemerc6bb0e22015-08-18 22:07:25 +0000283 if (match(V, m_Add(m_Value(Val), m_Constant(Con))))
284 if (Constant *Elt = Con->getAggregateElement(EltNo))
285 if (Elt->isNullValue())
286 return findScalarElement(Val, EltNo);
David Majnemer599ca442015-07-13 01:15:53 +0000287
288 // Otherwise, we don't know.
289 return nullptr;
290}
Renato Golin3b1d3b02015-08-30 10:49:04 +0000291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292/// Get splat value if the input is a splat vector or return nullptr.
Elena Demikhovsky63a7ca92015-08-30 13:48:02 +0000293/// This function is not fully general. It checks only 2 cases:
294/// the input value is (1) a splat constants vector or (2) a sequence
295/// of instructions that broadcast a single value into a vector.
296///
Elena Demikhovsky0781d7b2015-12-01 12:08:36 +0000297const llvm::Value *llvm::getSplatValue(const Value *V) {
298
299 if (auto *C = dyn_cast<Constant>(V))
Elena Demikhovsky47fa2712015-12-01 12:30:40 +0000300 if (isa<VectorType>(V->getType()))
301 return C->getSplatValue();
Elena Demikhovsky63a7ca92015-08-30 13:48:02 +0000302
303 auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V);
Renato Golin3b1d3b02015-08-30 10:49:04 +0000304 if (!ShuffleInst)
305 return nullptr;
Elena Demikhovsky63a7ca92015-08-30 13:48:02 +0000306 // All-zero (or undef) shuffle mask elements.
307 for (int MaskElt : ShuffleInst->getShuffleMask())
308 if (MaskElt != 0 && MaskElt != -1)
Renato Golin3b1d3b02015-08-30 10:49:04 +0000309 return nullptr;
310 // The first shuffle source is 'insertelement' with index 0.
Elena Demikhovsky63a7ca92015-08-30 13:48:02 +0000311 auto *InsertEltInst =
312 dyn_cast<InsertElementInst>(ShuffleInst->getOperand(0));
Renato Golin3b1d3b02015-08-30 10:49:04 +0000313 if (!InsertEltInst || !isa<ConstantInt>(InsertEltInst->getOperand(2)) ||
Craig Topper79ab6432017-07-06 18:39:47 +0000314 !cast<ConstantInt>(InsertEltInst->getOperand(2))->isZero())
Renato Golin3b1d3b02015-08-30 10:49:04 +0000315 return nullptr;
316
317 return InsertEltInst->getOperand(1);
318}
James Molloy55d633b2015-10-12 12:34:45 +0000319
Charlie Turner54336a52015-11-26 20:39:51 +0000320MapVector<Instruction *, uint64_t>
James Molloy45f67d52015-11-09 14:32:05 +0000321llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
322 const TargetTransformInfo *TTI) {
James Molloy55d633b2015-10-12 12:34:45 +0000323
324 // DemandedBits will give us every value's live-out bits. But we want
325 // to ensure no extra casts would need to be inserted, so every DAG
326 // of connected values must have the same minimum bitwidth.
James Molloy45f67d52015-11-09 14:32:05 +0000327 EquivalenceClasses<Value *> ECs;
328 SmallVector<Value *, 16> Worklist;
329 SmallPtrSet<Value *, 4> Roots;
330 SmallPtrSet<Value *, 16> Visited;
331 DenseMap<Value *, uint64_t> DBits;
332 SmallPtrSet<Instruction *, 4> InstructionSet;
Charlie Turner54336a52015-11-26 20:39:51 +0000333 MapVector<Instruction *, uint64_t> MinBWs;
James Molloy45f67d52015-11-09 14:32:05 +0000334
James Molloy55d633b2015-10-12 12:34:45 +0000335 // Determine the roots. We work bottom-up, from truncs or icmps.
336 bool SeenExtFromIllegalType = false;
337 for (auto *BB : Blocks)
338 for (auto &I : *BB) {
339 InstructionSet.insert(&I);
340
341 if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
342 !TTI->isTypeLegal(I.getOperand(0)->getType()))
343 SeenExtFromIllegalType = true;
James Molloy45f67d52015-11-09 14:32:05 +0000344
James Molloy55d633b2015-10-12 12:34:45 +0000345 // Only deal with non-vector integers up to 64-bits wide.
346 if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
347 !I.getType()->isVectorTy() &&
348 I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
349 // Don't make work for ourselves. If we know the loaded type is legal,
350 // don't add it to the worklist.
351 if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
352 continue;
James Molloy45f67d52015-11-09 14:32:05 +0000353
James Molloy55d633b2015-10-12 12:34:45 +0000354 Worklist.push_back(&I);
355 Roots.insert(&I);
356 }
357 }
358 // Early exit.
359 if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
360 return MinBWs;
James Molloy45f67d52015-11-09 14:32:05 +0000361
James Molloy55d633b2015-10-12 12:34:45 +0000362 // Now proceed breadth-first, unioning values together.
363 while (!Worklist.empty()) {
364 Value *Val = Worklist.pop_back_val();
365 Value *Leader = ECs.getOrInsertLeaderValue(Val);
James Molloy45f67d52015-11-09 14:32:05 +0000366
James Molloy55d633b2015-10-12 12:34:45 +0000367 if (Visited.count(Val))
368 continue;
369 Visited.insert(Val);
370
371 // Non-instructions terminate a chain successfully.
372 if (!isa<Instruction>(Val))
373 continue;
374 Instruction *I = cast<Instruction>(Val);
375
376 // If we encounter a type that is larger than 64 bits, we can't represent
377 // it so bail out.
James Molloyaa1d6382016-05-10 12:27:23 +0000378 if (DB.getDemandedBits(I).getBitWidth() > 64)
Charlie Turner54336a52015-11-26 20:39:51 +0000379 return MapVector<Instruction *, uint64_t>();
James Molloy45f67d52015-11-09 14:32:05 +0000380
James Molloyaa1d6382016-05-10 12:27:23 +0000381 uint64_t V = DB.getDemandedBits(I).getZExtValue();
382 DBits[Leader] |= V;
383 DBits[I] = V;
James Molloy45f67d52015-11-09 14:32:05 +0000384
James Molloy55d633b2015-10-12 12:34:45 +0000385 // Casts, loads and instructions outside of our range terminate a chain
386 // successfully.
387 if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
388 !InstructionSet.count(I))
389 continue;
390
391 // Unsafe casts terminate a chain unsuccessfully. We can't do anything
392 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
393 // transform anything that relies on them.
394 if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
395 !I->getType()->isIntegerTy()) {
396 DBits[Leader] |= ~0ULL;
397 continue;
398 }
399
400 // We don't modify the types of PHIs. Reductions will already have been
401 // truncated if possible, and inductions' sizes will have been chosen by
402 // indvars.
403 if (isa<PHINode>(I))
404 continue;
405
406 if (DBits[Leader] == ~0ULL)
407 // All bits demanded, no point continuing.
408 continue;
409
410 for (Value *O : cast<User>(I)->operands()) {
411 ECs.unionSets(Leader, O);
412 Worklist.push_back(O);
413 }
414 }
415
416 // Now we've discovered all values, walk them to see if there are
417 // any users we didn't see. If there are, we can't optimize that
418 // chain.
419 for (auto &I : DBits)
420 for (auto *U : I.first->users())
421 if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
422 DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
James Molloy45f67d52015-11-09 14:32:05 +0000423
James Molloy55d633b2015-10-12 12:34:45 +0000424 for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
425 uint64_t LeaderDemandedBits = 0;
426 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
427 LeaderDemandedBits |= DBits[*MI];
428
429 uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
430 llvm::countLeadingZeros(LeaderDemandedBits);
431 // Round up to a power of 2
432 if (!isPowerOf2_64((uint64_t)MinBW))
433 MinBW = NextPowerOf2(MinBW);
James Molloy8e46cd02016-03-30 10:11:43 +0000434
435 // We don't modify the types of PHIs. Reductions will already have been
436 // truncated if possible, and inductions' sizes will have been chosen by
437 // indvars.
438 // If we are required to shrink a PHI, abandon this entire equivalence class.
439 bool Abort = false;
440 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
441 if (isa<PHINode>(*MI) && MinBW < (*MI)->getType()->getScalarSizeInBits()) {
442 Abort = true;
443 break;
444 }
445 if (Abort)
446 continue;
447
James Molloy55d633b2015-10-12 12:34:45 +0000448 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) {
449 if (!isa<Instruction>(*MI))
450 continue;
451 Type *Ty = (*MI)->getType();
452 if (Roots.count(*MI))
453 Ty = cast<Instruction>(*MI)->getOperand(0)->getType();
454 if (MinBW < Ty->getScalarSizeInBits())
455 MinBWs[cast<Instruction>(*MI)] = MinBW;
456 }
457 }
458
459 return MinBWs;
460}
Matt Arsenault727e2792016-06-30 21:17:59 +0000461
462/// \returns \p I after propagating metadata from \p VL.
463Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
464 Instruction *I0 = cast<Instruction>(VL[0]);
465 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
466 I0->getAllMetadataOtherThanDebugLoc(Metadata);
467
Justin Lebar11a32042016-09-11 01:39:08 +0000468 for (auto Kind :
469 {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
470 LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
471 LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load}) {
Matt Arsenault727e2792016-06-30 21:17:59 +0000472 MDNode *MD = I0->getMetadata(Kind);
473
474 for (int J = 1, E = VL.size(); MD && J != E; ++J) {
475 const Instruction *IJ = cast<Instruction>(VL[J]);
476 MDNode *IMD = IJ->getMetadata(Kind);
477 switch (Kind) {
478 case LLVMContext::MD_tbaa:
479 MD = MDNode::getMostGenericTBAA(MD, IMD);
480 break;
481 case LLVMContext::MD_alias_scope:
482 MD = MDNode::getMostGenericAliasScope(MD, IMD);
483 break;
Matt Arsenault727e2792016-06-30 21:17:59 +0000484 case LLVMContext::MD_fpmath:
485 MD = MDNode::getMostGenericFPMath(MD, IMD);
486 break;
Justin Lebar11a32042016-09-11 01:39:08 +0000487 case LLVMContext::MD_noalias:
Matt Arsenault727e2792016-06-30 21:17:59 +0000488 case LLVMContext::MD_nontemporal:
Justin Lebar11a32042016-09-11 01:39:08 +0000489 case LLVMContext::MD_invariant_load:
Matt Arsenault727e2792016-06-30 21:17:59 +0000490 MD = MDNode::intersect(MD, IMD);
491 break;
492 default:
493 llvm_unreachable("unhandled metadata");
494 }
495 }
496
497 Inst->setMetadata(Kind, MD);
498 }
499
500 return Inst;
501}
Matthew Simpsonba5cf9d2017-02-01 17:45:46 +0000502
503Constant *llvm::createInterleaveMask(IRBuilder<> &Builder, unsigned VF,
504 unsigned NumVecs) {
505 SmallVector<Constant *, 16> Mask;
506 for (unsigned i = 0; i < VF; i++)
507 for (unsigned j = 0; j < NumVecs; j++)
508 Mask.push_back(Builder.getInt32(j * VF + i));
509
510 return ConstantVector::get(Mask);
511}
512
513Constant *llvm::createStrideMask(IRBuilder<> &Builder, unsigned Start,
514 unsigned Stride, unsigned VF) {
515 SmallVector<Constant *, 16> Mask;
516 for (unsigned i = 0; i < VF; i++)
517 Mask.push_back(Builder.getInt32(Start + i * Stride));
518
519 return ConstantVector::get(Mask);
520}
521
522Constant *llvm::createSequentialMask(IRBuilder<> &Builder, unsigned Start,
523 unsigned NumInts, unsigned NumUndefs) {
524 SmallVector<Constant *, 16> Mask;
525 for (unsigned i = 0; i < NumInts; i++)
526 Mask.push_back(Builder.getInt32(Start + i));
527
528 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
529 for (unsigned i = 0; i < NumUndefs; i++)
530 Mask.push_back(Undef);
531
532 return ConstantVector::get(Mask);
533}
534
535/// A helper function for concatenating vectors. This function concatenates two
536/// vectors having the same element type. If the second vector has fewer
537/// elements than the first, it is padded with undefs.
538static Value *concatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
539 Value *V2) {
540 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
541 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
542 assert(VecTy1 && VecTy2 &&
543 VecTy1->getScalarType() == VecTy2->getScalarType() &&
544 "Expect two vectors with the same element type");
545
546 unsigned NumElts1 = VecTy1->getNumElements();
547 unsigned NumElts2 = VecTy2->getNumElements();
548 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
549
550 if (NumElts1 > NumElts2) {
551 // Extend with UNDEFs.
552 Constant *ExtMask =
553 createSequentialMask(Builder, 0, NumElts2, NumElts1 - NumElts2);
554 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
555 }
556
557 Constant *Mask = createSequentialMask(Builder, 0, NumElts1 + NumElts2, 0);
558 return Builder.CreateShuffleVector(V1, V2, Mask);
559}
560
561Value *llvm::concatenateVectors(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) {
562 unsigned NumVecs = Vecs.size();
563 assert(NumVecs > 1 && "Should be at least two vectors");
564
565 SmallVector<Value *, 8> ResList;
566 ResList.append(Vecs.begin(), Vecs.end());
567 do {
568 SmallVector<Value *, 8> TmpList;
569 for (unsigned i = 0; i < NumVecs - 1; i += 2) {
570 Value *V0 = ResList[i], *V1 = ResList[i + 1];
571 assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
572 "Only the last vector may have a different type");
573
574 TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
575 }
576
577 // Push the last vector if the total number of vectors is odd.
578 if (NumVecs % 2 != 0)
579 TmpList.push_back(ResList[NumVecs - 1]);
580
581 ResList = TmpList;
582 NumVecs = ResList.size();
583 } while (NumVecs > 1);
584
585 return ResList[0];
586}
Florian Hahn1086ce22018-09-12 08:01:57 +0000587
588bool InterleavedAccessInfo::isStrided(int Stride) {
589 unsigned Factor = std::abs(Stride);
590 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
591}
592
593void InterleavedAccessInfo::collectConstStrideAccesses(
594 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
595 const ValueToValueMap &Strides) {
596 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
597
598 // Since it's desired that the load/store instructions be maintained in
599 // "program order" for the interleaved access analysis, we have to visit the
600 // blocks in the loop in reverse postorder (i.e., in a topological order).
601 // Such an ordering will ensure that any load/store that may be executed
602 // before a second load/store will precede the second load/store in
603 // AccessStrideInfo.
604 LoopBlocksDFS DFS(TheLoop);
605 DFS.perform(LI);
606 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
607 for (auto &I : *BB) {
608 auto *LI = dyn_cast<LoadInst>(&I);
609 auto *SI = dyn_cast<StoreInst>(&I);
610 if (!LI && !SI)
611 continue;
612
613 Value *Ptr = getLoadStorePointerOperand(&I);
614 // We don't check wrapping here because we don't know yet if Ptr will be
615 // part of a full group or a group with gaps. Checking wrapping for all
616 // pointers (even those that end up in groups with no gaps) will be overly
617 // conservative. For full groups, wrapping should be ok since if we would
618 // wrap around the address space we would do a memory access at nullptr
619 // even without the transformation. The wrapping checks are therefore
620 // deferred until after we've formed the interleaved groups.
621 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
622 /*Assume=*/true, /*ShouldCheckWrap=*/false);
623
624 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
625 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
626 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
627
628 // An alignment of 0 means target ABI alignment.
629 unsigned Align = getLoadStoreAlignment(&I);
630 if (!Align)
631 Align = DL.getABITypeAlignment(PtrTy->getElementType());
632
633 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
634 }
635}
636
637// Analyze interleaved accesses and collect them into interleaved load and
638// store groups.
639//
640// When generating code for an interleaved load group, we effectively hoist all
641// loads in the group to the location of the first load in program order. When
642// generating code for an interleaved store group, we sink all stores to the
643// location of the last store. This code motion can change the order of load
644// and store instructions and may break dependences.
645//
646// The code generation strategy mentioned above ensures that we won't violate
647// any write-after-read (WAR) dependences.
648//
649// E.g., for the WAR dependence: a = A[i]; // (1)
650// A[i] = b; // (2)
651//
652// The store group of (2) is always inserted at or below (2), and the load
653// group of (1) is always inserted at or above (1). Thus, the instructions will
654// never be reordered. All other dependences are checked to ensure the
655// correctness of the instruction reordering.
656//
657// The algorithm visits all memory accesses in the loop in bottom-up program
658// order. Program order is established by traversing the blocks in the loop in
659// reverse postorder when collecting the accesses.
660//
661// We visit the memory accesses in bottom-up order because it can simplify the
662// construction of store groups in the presence of write-after-write (WAW)
663// dependences.
664//
665// E.g., for the WAW dependence: A[i] = a; // (1)
666// A[i] = b; // (2)
667// A[i + 1] = c; // (3)
668//
669// We will first create a store group with (3) and (2). (1) can't be added to
670// this group because it and (2) are dependent. However, (1) can be grouped
671// with other accesses that may precede it in program order. Note that a
672// bottom-up order does not imply that WAW dependences should not be checked.
673void InterleavedAccessInfo::analyzeInterleaving() {
674 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
675 const ValueToValueMap &Strides = LAI->getSymbolicStrides();
676
677 // Holds all accesses with a constant stride.
678 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
679 collectConstStrideAccesses(AccessStrideInfo, Strides);
680
681 if (AccessStrideInfo.empty())
682 return;
683
684 // Collect the dependences in the loop.
685 collectDependences();
686
687 // Holds all interleaved store groups temporarily.
688 SmallSetVector<InterleaveGroup *, 4> StoreGroups;
689 // Holds all interleaved load groups temporarily.
690 SmallSetVector<InterleaveGroup *, 4> LoadGroups;
691
692 // Search in bottom-up program order for pairs of accesses (A and B) that can
693 // form interleaved load or store groups. In the algorithm below, access A
694 // precedes access B in program order. We initialize a group for B in the
695 // outer loop of the algorithm, and then in the inner loop, we attempt to
696 // insert each A into B's group if:
697 //
698 // 1. A and B have the same stride,
699 // 2. A and B have the same memory object size, and
700 // 3. A belongs in B's group according to its distance from B.
701 //
702 // Special care is taken to ensure group formation will not break any
703 // dependences.
704 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
705 BI != E; ++BI) {
706 Instruction *B = BI->first;
707 StrideDescriptor DesB = BI->second;
708
709 // Initialize a group for B if it has an allowable stride. Even if we don't
710 // create a group for B, we continue with the bottom-up algorithm to ensure
711 // we don't break any of B's dependences.
712 InterleaveGroup *Group = nullptr;
713 if (isStrided(DesB.Stride)) {
714 Group = getInterleaveGroup(B);
715 if (!Group) {
716 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
717 << '\n');
718 Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
719 }
720 if (B->mayWriteToMemory())
721 StoreGroups.insert(Group);
722 else
723 LoadGroups.insert(Group);
724 }
725
726 for (auto AI = std::next(BI); AI != E; ++AI) {
727 Instruction *A = AI->first;
728 StrideDescriptor DesA = AI->second;
729
730 // Our code motion strategy implies that we can't have dependences
731 // between accesses in an interleaved group and other accesses located
732 // between the first and last member of the group. Note that this also
733 // means that a group can't have more than one member at a given offset.
734 // The accesses in a group can have dependences with other accesses, but
735 // we must ensure we don't extend the boundaries of the group such that
736 // we encompass those dependent accesses.
737 //
738 // For example, assume we have the sequence of accesses shown below in a
739 // stride-2 loop:
740 //
741 // (1, 2) is a group | A[i] = a; // (1)
742 // | A[i-1] = b; // (2) |
743 // A[i-3] = c; // (3)
744 // A[i] = d; // (4) | (2, 4) is not a group
745 //
746 // Because accesses (2) and (3) are dependent, we can group (2) with (1)
747 // but not with (4). If we did, the dependent access (3) would be within
748 // the boundaries of the (2, 4) group.
749 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
750 // If a dependence exists and A is already in a group, we know that A
751 // must be a store since A precedes B and WAR dependences are allowed.
752 // Thus, A would be sunk below B. We release A's group to prevent this
753 // illegal code motion. A will then be free to form another group with
754 // instructions that precede it.
755 if (isInterleaved(A)) {
756 InterleaveGroup *StoreGroup = getInterleaveGroup(A);
757 StoreGroups.remove(StoreGroup);
758 releaseGroup(StoreGroup);
759 }
760
761 // If a dependence exists and A is not already in a group (or it was
762 // and we just released it), B might be hoisted above A (if B is a
763 // load) or another store might be sunk below A (if B is a store). In
764 // either case, we can't add additional instructions to B's group. B
765 // will only form a group with instructions that it precedes.
766 break;
767 }
768
769 // At this point, we've checked for illegal code motion. If either A or B
770 // isn't strided, there's nothing left to do.
771 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
772 continue;
773
774 // Ignore A if it's already in a group or isn't the same kind of memory
775 // operation as B.
776 // Note that mayReadFromMemory() isn't mutually exclusive to
777 // mayWriteToMemory in the case of atomic loads. We shouldn't see those
778 // here, canVectorizeMemory() should have returned false - except for the
779 // case we asked for optimization remarks.
780 if (isInterleaved(A) ||
781 (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
782 (A->mayWriteToMemory() != B->mayWriteToMemory()))
783 continue;
784
785 // Check rules 1 and 2. Ignore A if its stride or size is different from
786 // that of B.
787 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
788 continue;
789
790 // Ignore A if the memory object of A and B don't belong to the same
791 // address space
792 if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
793 continue;
794
795 // Calculate the distance from A to B.
796 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
797 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
798 if (!DistToB)
799 continue;
800 int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
801
802 // Check rule 3. Ignore A if its distance to B is not a multiple of the
803 // size.
804 if (DistanceToB % static_cast<int64_t>(DesB.Size))
805 continue;
806
807 // Ignore A if either A or B is in a predicated block. Although we
808 // currently prevent group formation for predicated accesses, we may be
809 // able to relax this limitation in the future once we handle more
810 // complicated blocks.
811 if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
812 continue;
813
814 // The index of A is the index of B plus A's distance to B in multiples
815 // of the size.
816 int IndexA =
817 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
818
819 // Try to insert A into B's group.
820 if (Group->insertMember(A, IndexA, DesA.Align)) {
821 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
822 << " into the interleave group with" << *B
823 << '\n');
824 InterleaveGroupMap[A] = Group;
825
826 // Set the first load in program order as the insert position.
827 if (A->mayReadFromMemory())
828 Group->setInsertPos(A);
829 }
830 } // Iteration over A accesses.
831 } // Iteration over B accesses.
832
833 // Remove interleaved store groups with gaps.
834 for (InterleaveGroup *Group : StoreGroups)
835 if (Group->getNumMembers() != Group->getFactor()) {
836 LLVM_DEBUG(
837 dbgs() << "LV: Invalidate candidate interleaved store group due "
838 "to gaps.\n");
839 releaseGroup(Group);
840 }
841 // Remove interleaved groups with gaps (currently only loads) whose memory
842 // accesses may wrap around. We have to revisit the getPtrStride analysis,
843 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
844 // not check wrapping (see documentation there).
845 // FORNOW we use Assume=false;
846 // TODO: Change to Assume=true but making sure we don't exceed the threshold
847 // of runtime SCEV assumptions checks (thereby potentially failing to
848 // vectorize altogether).
849 // Additional optional optimizations:
850 // TODO: If we are peeling the loop and we know that the first pointer doesn't
851 // wrap then we can deduce that all pointers in the group don't wrap.
852 // This means that we can forcefully peel the loop in order to only have to
853 // check the first pointer for no-wrap. When we'll change to use Assume=true
854 // we'll only need at most one runtime check per interleaved group.
855 for (InterleaveGroup *Group : LoadGroups) {
856 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
857 // load would wrap around the address space we would do a memory access at
858 // nullptr even without the transformation.
859 if (Group->getNumMembers() == Group->getFactor())
860 continue;
861
862 // Case 2: If first and last members of the group don't wrap this implies
863 // that all the pointers in the group don't wrap.
864 // So we check only group member 0 (which is always guaranteed to exist),
865 // and group member Factor - 1; If the latter doesn't exist we rely on
866 // peeling (if it is a non-reveresed accsess -- see Case 3).
867 Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
868 if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
869 /*ShouldCheckWrap=*/true)) {
870 LLVM_DEBUG(
871 dbgs() << "LV: Invalidate candidate interleaved group due to "
872 "first group member potentially pointer-wrapping.\n");
873 releaseGroup(Group);
874 continue;
875 }
876 Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
877 if (LastMember) {
878 Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
879 if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
880 /*ShouldCheckWrap=*/true)) {
881 LLVM_DEBUG(
882 dbgs() << "LV: Invalidate candidate interleaved group due to "
883 "last group member potentially pointer-wrapping.\n");
884 releaseGroup(Group);
885 }
886 } else {
887 // Case 3: A non-reversed interleaved load group with gaps: We need
888 // to execute at least one scalar epilogue iteration. This will ensure
889 // we don't speculatively access memory out-of-bounds. We only need
890 // to look for a member at index factor - 1, since every group must have
891 // a member at index zero.
892 if (Group->isReverse()) {
893 LLVM_DEBUG(
894 dbgs() << "LV: Invalidate candidate interleaved group due to "
895 "a reverse access with gaps.\n");
896 releaseGroup(Group);
897 continue;
898 }
899 LLVM_DEBUG(
900 dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
901 RequiresScalarEpilogue = true;
902 }
903 }
904}