1 //===----------- 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 14 #include "llvm/Analysis/VectorUtils.h" 15 #include "llvm/ADT/EquivalenceClasses.h" 16 #include "llvm/Analysis/DemandedBits.h" 17 #include "llvm/Analysis/LoopInfo.h" 18 #include "llvm/Analysis/LoopIterator.h" 19 #include "llvm/Analysis/ScalarEvolution.h" 20 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/Constants.h" 24 #include "llvm/IR/GetElementPtrTypeIterator.h" 25 #include "llvm/IR/IRBuilder.h" 26 #include "llvm/IR/PatternMatch.h" 27 #include "llvm/IR/Value.h" 28 29 #define DEBUG_TYPE "vectorutils" 30 31 using namespace llvm; 32 using namespace llvm::PatternMatch; 33 34 /// Maximum factor for an interleaved memory access. 35 static 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 40 /// Return true if all of the intrinsic's arguments and return type are scalars 41 /// for the scalar form of the intrinsic and vectors for the vector form of the 42 /// intrinsic. 43 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) { 44 switch (ID) { 45 case Intrinsic::bswap: // Begin integer bit-manipulation. 46 case Intrinsic::bitreverse: 47 case Intrinsic::ctpop: 48 case Intrinsic::ctlz: 49 case Intrinsic::cttz: 50 case Intrinsic::fshl: 51 case Intrinsic::fshr: 52 case Intrinsic::sqrt: // Begin floating-point. 53 case Intrinsic::sin: 54 case Intrinsic::cos: 55 case Intrinsic::exp: 56 case Intrinsic::exp2: 57 case Intrinsic::log: 58 case Intrinsic::log10: 59 case Intrinsic::log2: 60 case Intrinsic::fabs: 61 case Intrinsic::minnum: 62 case Intrinsic::maxnum: 63 case Intrinsic::minimum: 64 case Intrinsic::maximum: 65 case Intrinsic::copysign: 66 case Intrinsic::floor: 67 case Intrinsic::ceil: 68 case Intrinsic::trunc: 69 case Intrinsic::rint: 70 case Intrinsic::nearbyint: 71 case Intrinsic::round: 72 case Intrinsic::pow: 73 case Intrinsic::fma: 74 case Intrinsic::fmuladd: 75 case Intrinsic::powi: 76 case Intrinsic::canonicalize: 77 return true; 78 default: 79 return false; 80 } 81 } 82 83 /// Identifies if the intrinsic has a scalar operand. It check for 84 /// ctlz,cttz and powi special intrinsics whose argument is scalar. 85 bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, 86 unsigned ScalarOpdIdx) { 87 switch (ID) { 88 case Intrinsic::ctlz: 89 case Intrinsic::cttz: 90 case Intrinsic::powi: 91 return (ScalarOpdIdx == 1); 92 default: 93 return false; 94 } 95 } 96 97 /// Returns intrinsic ID for call. 98 /// For the input call instruction it finds mapping intrinsic and returns 99 /// its ID, in case it does not found it return not_intrinsic. 100 Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI, 101 const TargetLibraryInfo *TLI) { 102 Intrinsic::ID ID = getIntrinsicForCallSite(CI, TLI); 103 if (ID == Intrinsic::not_intrinsic) 104 return Intrinsic::not_intrinsic; 105 106 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start || 107 ID == Intrinsic::lifetime_end || ID == Intrinsic::assume || 108 ID == Intrinsic::sideeffect) 109 return ID; 110 return Intrinsic::not_intrinsic; 111 } 112 113 /// Find the operand of the GEP that should be checked for consecutive 114 /// stores. This ignores trailing indices that have no effect on the final 115 /// pointer. 116 unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) { 117 const DataLayout &DL = Gep->getModule()->getDataLayout(); 118 unsigned LastOperand = Gep->getNumOperands() - 1; 119 unsigned GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType()); 120 121 // Walk backwards and try to peel off zeros. 122 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) { 123 // Find the type we're currently indexing into. 124 gep_type_iterator GEPTI = gep_type_begin(Gep); 125 std::advance(GEPTI, LastOperand - 2); 126 127 // If it's a type with the same allocation size as the result of the GEP we 128 // can peel off the zero index. 129 if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize) 130 break; 131 --LastOperand; 132 } 133 134 return LastOperand; 135 } 136 137 /// If the argument is a GEP, then returns the operand identified by 138 /// getGEPInductionOperand. However, if there is some other non-loop-invariant 139 /// operand, it returns that instead. 140 Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 141 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 142 if (!GEP) 143 return Ptr; 144 145 unsigned InductionOperand = getGEPInductionOperand(GEP); 146 147 // Check that all of the gep indices are uniform except for our induction 148 // operand. 149 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) 150 if (i != InductionOperand && 151 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp)) 152 return Ptr; 153 return GEP->getOperand(InductionOperand); 154 } 155 156 /// If a value has only one user that is a CastInst, return it. 157 Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) { 158 Value *UniqueCast = nullptr; 159 for (User *U : Ptr->users()) { 160 CastInst *CI = dyn_cast<CastInst>(U); 161 if (CI && CI->getType() == Ty) { 162 if (!UniqueCast) 163 UniqueCast = CI; 164 else 165 return nullptr; 166 } 167 } 168 return UniqueCast; 169 } 170 171 /// Get the stride of a pointer access in a loop. Looks for symbolic 172 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise. 173 Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 174 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 175 if (!PtrTy || PtrTy->isAggregateType()) 176 return nullptr; 177 178 // Try to remove a gep instruction to make the pointer (actually index at this 179 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the 180 // pointer, otherwise, we are analyzing the index. 181 Value *OrigPtr = Ptr; 182 183 // The size of the pointer access. 184 int64_t PtrAccessSize = 1; 185 186 Ptr = stripGetElementPtr(Ptr, SE, Lp); 187 const SCEV *V = SE->getSCEV(Ptr); 188 189 if (Ptr != OrigPtr) 190 // Strip off casts. 191 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) 192 V = C->getOperand(); 193 194 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V); 195 if (!S) 196 return nullptr; 197 198 V = S->getStepRecurrence(*SE); 199 if (!V) 200 return nullptr; 201 202 // Strip off the size of access multiplication if we are still analyzing the 203 // pointer. 204 if (OrigPtr == Ptr) { 205 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) { 206 if (M->getOperand(0)->getSCEVType() != scConstant) 207 return nullptr; 208 209 const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt(); 210 211 // Huge step value - give up. 212 if (APStepVal.getBitWidth() > 64) 213 return nullptr; 214 215 int64_t StepVal = APStepVal.getSExtValue(); 216 if (PtrAccessSize != StepVal) 217 return nullptr; 218 V = M->getOperand(1); 219 } 220 } 221 222 // Strip off casts. 223 Type *StripedOffRecurrenceCast = nullptr; 224 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) { 225 StripedOffRecurrenceCast = C->getType(); 226 V = C->getOperand(); 227 } 228 229 // Look for the loop invariant symbolic value. 230 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V); 231 if (!U) 232 return nullptr; 233 234 Value *Stride = U->getValue(); 235 if (!Lp->isLoopInvariant(Stride)) 236 return nullptr; 237 238 // If we have stripped off the recurrence cast we have to make sure that we 239 // return the value that is used in this loop so that we can replace it later. 240 if (StripedOffRecurrenceCast) 241 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast); 242 243 return Stride; 244 } 245 246 /// Given a vector and an element number, see if the scalar value is 247 /// already around as a register, for example if it were inserted then extracted 248 /// from the vector. 249 Value *llvm::findScalarElement(Value *V, unsigned EltNo) { 250 assert(V->getType()->isVectorTy() && "Not looking at a vector?"); 251 VectorType *VTy = cast<VectorType>(V->getType()); 252 unsigned Width = VTy->getNumElements(); 253 if (EltNo >= Width) // Out of range access. 254 return UndefValue::get(VTy->getElementType()); 255 256 if (Constant *C = dyn_cast<Constant>(V)) 257 return C->getAggregateElement(EltNo); 258 259 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) { 260 // If this is an insert to a variable element, we don't know what it is. 261 if (!isa<ConstantInt>(III->getOperand(2))) 262 return nullptr; 263 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue(); 264 265 // If this is an insert to the element we are looking for, return the 266 // inserted value. 267 if (EltNo == IIElt) 268 return III->getOperand(1); 269 270 // Otherwise, the insertelement doesn't modify the value, recurse on its 271 // vector input. 272 return findScalarElement(III->getOperand(0), EltNo); 273 } 274 275 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) { 276 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements(); 277 int InEl = SVI->getMaskValue(EltNo); 278 if (InEl < 0) 279 return UndefValue::get(VTy->getElementType()); 280 if (InEl < (int)LHSWidth) 281 return findScalarElement(SVI->getOperand(0), InEl); 282 return findScalarElement(SVI->getOperand(1), InEl - LHSWidth); 283 } 284 285 // Extract a value from a vector add operation with a constant zero. 286 // TODO: Use getBinOpIdentity() to generalize this. 287 Value *Val; Constant *C; 288 if (match(V, m_Add(m_Value(Val), m_Constant(C)))) 289 if (Constant *Elt = C->getAggregateElement(EltNo)) 290 if (Elt->isNullValue()) 291 return findScalarElement(Val, EltNo); 292 293 // Otherwise, we don't know. 294 return nullptr; 295 } 296 297 /// Get splat value if the input is a splat vector or return nullptr. 298 /// This function is not fully general. It checks only 2 cases: 299 /// the input value is (1) a splat constants vector or (2) a sequence 300 /// of instructions that broadcast a single value into a vector. 301 /// 302 const llvm::Value *llvm::getSplatValue(const Value *V) { 303 304 if (auto *C = dyn_cast<Constant>(V)) 305 if (isa<VectorType>(V->getType())) 306 return C->getSplatValue(); 307 308 auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V); 309 if (!ShuffleInst) 310 return nullptr; 311 // All-zero (or undef) shuffle mask elements. 312 for (int MaskElt : ShuffleInst->getShuffleMask()) 313 if (MaskElt != 0 && MaskElt != -1) 314 return nullptr; 315 // The first shuffle source is 'insertelement' with index 0. 316 auto *InsertEltInst = 317 dyn_cast<InsertElementInst>(ShuffleInst->getOperand(0)); 318 if (!InsertEltInst || !isa<ConstantInt>(InsertEltInst->getOperand(2)) || 319 !cast<ConstantInt>(InsertEltInst->getOperand(2))->isZero()) 320 return nullptr; 321 322 return InsertEltInst->getOperand(1); 323 } 324 325 MapVector<Instruction *, uint64_t> 326 llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB, 327 const TargetTransformInfo *TTI) { 328 329 // DemandedBits will give us every value's live-out bits. But we want 330 // to ensure no extra casts would need to be inserted, so every DAG 331 // of connected values must have the same minimum bitwidth. 332 EquivalenceClasses<Value *> ECs; 333 SmallVector<Value *, 16> Worklist; 334 SmallPtrSet<Value *, 4> Roots; 335 SmallPtrSet<Value *, 16> Visited; 336 DenseMap<Value *, uint64_t> DBits; 337 SmallPtrSet<Instruction *, 4> InstructionSet; 338 MapVector<Instruction *, uint64_t> MinBWs; 339 340 // Determine the roots. We work bottom-up, from truncs or icmps. 341 bool SeenExtFromIllegalType = false; 342 for (auto *BB : Blocks) 343 for (auto &I : *BB) { 344 InstructionSet.insert(&I); 345 346 if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) && 347 !TTI->isTypeLegal(I.getOperand(0)->getType())) 348 SeenExtFromIllegalType = true; 349 350 // Only deal with non-vector integers up to 64-bits wide. 351 if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) && 352 !I.getType()->isVectorTy() && 353 I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) { 354 // Don't make work for ourselves. If we know the loaded type is legal, 355 // don't add it to the worklist. 356 if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType())) 357 continue; 358 359 Worklist.push_back(&I); 360 Roots.insert(&I); 361 } 362 } 363 // Early exit. 364 if (Worklist.empty() || (TTI && !SeenExtFromIllegalType)) 365 return MinBWs; 366 367 // Now proceed breadth-first, unioning values together. 368 while (!Worklist.empty()) { 369 Value *Val = Worklist.pop_back_val(); 370 Value *Leader = ECs.getOrInsertLeaderValue(Val); 371 372 if (Visited.count(Val)) 373 continue; 374 Visited.insert(Val); 375 376 // Non-instructions terminate a chain successfully. 377 if (!isa<Instruction>(Val)) 378 continue; 379 Instruction *I = cast<Instruction>(Val); 380 381 // If we encounter a type that is larger than 64 bits, we can't represent 382 // it so bail out. 383 if (DB.getDemandedBits(I).getBitWidth() > 64) 384 return MapVector<Instruction *, uint64_t>(); 385 386 uint64_t V = DB.getDemandedBits(I).getZExtValue(); 387 DBits[Leader] |= V; 388 DBits[I] = V; 389 390 // Casts, loads and instructions outside of our range terminate a chain 391 // successfully. 392 if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) || 393 !InstructionSet.count(I)) 394 continue; 395 396 // Unsafe casts terminate a chain unsuccessfully. We can't do anything 397 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to 398 // transform anything that relies on them. 399 if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) || 400 !I->getType()->isIntegerTy()) { 401 DBits[Leader] |= ~0ULL; 402 continue; 403 } 404 405 // We don't modify the types of PHIs. Reductions will already have been 406 // truncated if possible, and inductions' sizes will have been chosen by 407 // indvars. 408 if (isa<PHINode>(I)) 409 continue; 410 411 if (DBits[Leader] == ~0ULL) 412 // All bits demanded, no point continuing. 413 continue; 414 415 for (Value *O : cast<User>(I)->operands()) { 416 ECs.unionSets(Leader, O); 417 Worklist.push_back(O); 418 } 419 } 420 421 // Now we've discovered all values, walk them to see if there are 422 // any users we didn't see. If there are, we can't optimize that 423 // chain. 424 for (auto &I : DBits) 425 for (auto *U : I.first->users()) 426 if (U->getType()->isIntegerTy() && DBits.count(U) == 0) 427 DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL; 428 429 for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) { 430 uint64_t LeaderDemandedBits = 0; 431 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) 432 LeaderDemandedBits |= DBits[*MI]; 433 434 uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) - 435 llvm::countLeadingZeros(LeaderDemandedBits); 436 // Round up to a power of 2 437 if (!isPowerOf2_64((uint64_t)MinBW)) 438 MinBW = NextPowerOf2(MinBW); 439 440 // We don't modify the types of PHIs. Reductions will already have been 441 // truncated if possible, and inductions' sizes will have been chosen by 442 // indvars. 443 // If we are required to shrink a PHI, abandon this entire equivalence class. 444 bool Abort = false; 445 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) 446 if (isa<PHINode>(*MI) && MinBW < (*MI)->getType()->getScalarSizeInBits()) { 447 Abort = true; 448 break; 449 } 450 if (Abort) 451 continue; 452 453 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) { 454 if (!isa<Instruction>(*MI)) 455 continue; 456 Type *Ty = (*MI)->getType(); 457 if (Roots.count(*MI)) 458 Ty = cast<Instruction>(*MI)->getOperand(0)->getType(); 459 if (MinBW < Ty->getScalarSizeInBits()) 460 MinBWs[cast<Instruction>(*MI)] = MinBW; 461 } 462 } 463 464 return MinBWs; 465 } 466 467 /// \returns \p I after propagating metadata from \p VL. 468 Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) { 469 Instruction *I0 = cast<Instruction>(VL[0]); 470 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; 471 I0->getAllMetadataOtherThanDebugLoc(Metadata); 472 473 for (auto Kind : 474 {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 475 LLVMContext::MD_noalias, LLVMContext::MD_fpmath, 476 LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load}) { 477 MDNode *MD = I0->getMetadata(Kind); 478 479 for (int J = 1, E = VL.size(); MD && J != E; ++J) { 480 const Instruction *IJ = cast<Instruction>(VL[J]); 481 MDNode *IMD = IJ->getMetadata(Kind); 482 switch (Kind) { 483 case LLVMContext::MD_tbaa: 484 MD = MDNode::getMostGenericTBAA(MD, IMD); 485 break; 486 case LLVMContext::MD_alias_scope: 487 MD = MDNode::getMostGenericAliasScope(MD, IMD); 488 break; 489 case LLVMContext::MD_fpmath: 490 MD = MDNode::getMostGenericFPMath(MD, IMD); 491 break; 492 case LLVMContext::MD_noalias: 493 case LLVMContext::MD_nontemporal: 494 case LLVMContext::MD_invariant_load: 495 MD = MDNode::intersect(MD, IMD); 496 break; 497 default: 498 llvm_unreachable("unhandled metadata"); 499 } 500 } 501 502 Inst->setMetadata(Kind, MD); 503 } 504 505 return Inst; 506 } 507 508 Constant *llvm::createBitMaskForGaps(IRBuilder<> &Builder, unsigned VF, 509 const InterleaveGroup &Group) { 510 // All 1's means mask is not needed. 511 if (Group.getNumMembers() == Group.getFactor()) 512 return nullptr; 513 514 // TODO: support reversed access. 515 assert(!Group.isReverse() && "Reversed group not supported."); 516 517 SmallVector<Constant *, 16> Mask; 518 for (unsigned i = 0; i < VF; i++) 519 for (unsigned j = 0; j < Group.getFactor(); ++j) { 520 unsigned HasMember = Group.getMember(j) ? 1 : 0; 521 Mask.push_back(Builder.getInt1(HasMember)); 522 } 523 524 return ConstantVector::get(Mask); 525 } 526 527 Constant *llvm::createReplicatedMask(IRBuilder<> &Builder, 528 unsigned ReplicationFactor, unsigned VF) { 529 SmallVector<Constant *, 16> MaskVec; 530 for (unsigned i = 0; i < VF; i++) 531 for (unsigned j = 0; j < ReplicationFactor; j++) 532 MaskVec.push_back(Builder.getInt32(i)); 533 534 return ConstantVector::get(MaskVec); 535 } 536 537 Constant *llvm::createInterleaveMask(IRBuilder<> &Builder, unsigned VF, 538 unsigned NumVecs) { 539 SmallVector<Constant *, 16> Mask; 540 for (unsigned i = 0; i < VF; i++) 541 for (unsigned j = 0; j < NumVecs; j++) 542 Mask.push_back(Builder.getInt32(j * VF + i)); 543 544 return ConstantVector::get(Mask); 545 } 546 547 Constant *llvm::createStrideMask(IRBuilder<> &Builder, unsigned Start, 548 unsigned Stride, unsigned VF) { 549 SmallVector<Constant *, 16> Mask; 550 for (unsigned i = 0; i < VF; i++) 551 Mask.push_back(Builder.getInt32(Start + i * Stride)); 552 553 return ConstantVector::get(Mask); 554 } 555 556 Constant *llvm::createSequentialMask(IRBuilder<> &Builder, unsigned Start, 557 unsigned NumInts, unsigned NumUndefs) { 558 SmallVector<Constant *, 16> Mask; 559 for (unsigned i = 0; i < NumInts; i++) 560 Mask.push_back(Builder.getInt32(Start + i)); 561 562 Constant *Undef = UndefValue::get(Builder.getInt32Ty()); 563 for (unsigned i = 0; i < NumUndefs; i++) 564 Mask.push_back(Undef); 565 566 return ConstantVector::get(Mask); 567 } 568 569 /// A helper function for concatenating vectors. This function concatenates two 570 /// vectors having the same element type. If the second vector has fewer 571 /// elements than the first, it is padded with undefs. 572 static Value *concatenateTwoVectors(IRBuilder<> &Builder, Value *V1, 573 Value *V2) { 574 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType()); 575 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType()); 576 assert(VecTy1 && VecTy2 && 577 VecTy1->getScalarType() == VecTy2->getScalarType() && 578 "Expect two vectors with the same element type"); 579 580 unsigned NumElts1 = VecTy1->getNumElements(); 581 unsigned NumElts2 = VecTy2->getNumElements(); 582 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements"); 583 584 if (NumElts1 > NumElts2) { 585 // Extend with UNDEFs. 586 Constant *ExtMask = 587 createSequentialMask(Builder, 0, NumElts2, NumElts1 - NumElts2); 588 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask); 589 } 590 591 Constant *Mask = createSequentialMask(Builder, 0, NumElts1 + NumElts2, 0); 592 return Builder.CreateShuffleVector(V1, V2, Mask); 593 } 594 595 Value *llvm::concatenateVectors(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) { 596 unsigned NumVecs = Vecs.size(); 597 assert(NumVecs > 1 && "Should be at least two vectors"); 598 599 SmallVector<Value *, 8> ResList; 600 ResList.append(Vecs.begin(), Vecs.end()); 601 do { 602 SmallVector<Value *, 8> TmpList; 603 for (unsigned i = 0; i < NumVecs - 1; i += 2) { 604 Value *V0 = ResList[i], *V1 = ResList[i + 1]; 605 assert((V0->getType() == V1->getType() || i == NumVecs - 2) && 606 "Only the last vector may have a different type"); 607 608 TmpList.push_back(concatenateTwoVectors(Builder, V0, V1)); 609 } 610 611 // Push the last vector if the total number of vectors is odd. 612 if (NumVecs % 2 != 0) 613 TmpList.push_back(ResList[NumVecs - 1]); 614 615 ResList = TmpList; 616 NumVecs = ResList.size(); 617 } while (NumVecs > 1); 618 619 return ResList[0]; 620 } 621 622 bool InterleavedAccessInfo::isStrided(int Stride) { 623 unsigned Factor = std::abs(Stride); 624 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor; 625 } 626 627 void InterleavedAccessInfo::collectConstStrideAccesses( 628 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, 629 const ValueToValueMap &Strides) { 630 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 631 632 // Since it's desired that the load/store instructions be maintained in 633 // "program order" for the interleaved access analysis, we have to visit the 634 // blocks in the loop in reverse postorder (i.e., in a topological order). 635 // Such an ordering will ensure that any load/store that may be executed 636 // before a second load/store will precede the second load/store in 637 // AccessStrideInfo. 638 LoopBlocksDFS DFS(TheLoop); 639 DFS.perform(LI); 640 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) 641 for (auto &I : *BB) { 642 auto *LI = dyn_cast<LoadInst>(&I); 643 auto *SI = dyn_cast<StoreInst>(&I); 644 if (!LI && !SI) 645 continue; 646 647 Value *Ptr = getLoadStorePointerOperand(&I); 648 // We don't check wrapping here because we don't know yet if Ptr will be 649 // part of a full group or a group with gaps. Checking wrapping for all 650 // pointers (even those that end up in groups with no gaps) will be overly 651 // conservative. For full groups, wrapping should be ok since if we would 652 // wrap around the address space we would do a memory access at nullptr 653 // even without the transformation. The wrapping checks are therefore 654 // deferred until after we've formed the interleaved groups. 655 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, 656 /*Assume=*/true, /*ShouldCheckWrap=*/false); 657 658 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr); 659 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 660 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType()); 661 662 // An alignment of 0 means target ABI alignment. 663 unsigned Align = getLoadStoreAlignment(&I); 664 if (!Align) 665 Align = DL.getABITypeAlignment(PtrTy->getElementType()); 666 667 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align); 668 } 669 } 670 671 // Analyze interleaved accesses and collect them into interleaved load and 672 // store groups. 673 // 674 // When generating code for an interleaved load group, we effectively hoist all 675 // loads in the group to the location of the first load in program order. When 676 // generating code for an interleaved store group, we sink all stores to the 677 // location of the last store. This code motion can change the order of load 678 // and store instructions and may break dependences. 679 // 680 // The code generation strategy mentioned above ensures that we won't violate 681 // any write-after-read (WAR) dependences. 682 // 683 // E.g., for the WAR dependence: a = A[i]; // (1) 684 // A[i] = b; // (2) 685 // 686 // The store group of (2) is always inserted at or below (2), and the load 687 // group of (1) is always inserted at or above (1). Thus, the instructions will 688 // never be reordered. All other dependences are checked to ensure the 689 // correctness of the instruction reordering. 690 // 691 // The algorithm visits all memory accesses in the loop in bottom-up program 692 // order. Program order is established by traversing the blocks in the loop in 693 // reverse postorder when collecting the accesses. 694 // 695 // We visit the memory accesses in bottom-up order because it can simplify the 696 // construction of store groups in the presence of write-after-write (WAW) 697 // dependences. 698 // 699 // E.g., for the WAW dependence: A[i] = a; // (1) 700 // A[i] = b; // (2) 701 // A[i + 1] = c; // (3) 702 // 703 // We will first create a store group with (3) and (2). (1) can't be added to 704 // this group because it and (2) are dependent. However, (1) can be grouped 705 // with other accesses that may precede it in program order. Note that a 706 // bottom-up order does not imply that WAW dependences should not be checked. 707 void InterleavedAccessInfo::analyzeInterleaving( 708 bool EnablePredicatedInterleavedMemAccesses) { 709 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n"); 710 const ValueToValueMap &Strides = LAI->getSymbolicStrides(); 711 712 // Holds all accesses with a constant stride. 713 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo; 714 collectConstStrideAccesses(AccessStrideInfo, Strides); 715 716 if (AccessStrideInfo.empty()) 717 return; 718 719 // Collect the dependences in the loop. 720 collectDependences(); 721 722 // Holds all interleaved store groups temporarily. 723 SmallSetVector<InterleaveGroup *, 4> StoreGroups; 724 // Holds all interleaved load groups temporarily. 725 SmallSetVector<InterleaveGroup *, 4> LoadGroups; 726 727 // Search in bottom-up program order for pairs of accesses (A and B) that can 728 // form interleaved load or store groups. In the algorithm below, access A 729 // precedes access B in program order. We initialize a group for B in the 730 // outer loop of the algorithm, and then in the inner loop, we attempt to 731 // insert each A into B's group if: 732 // 733 // 1. A and B have the same stride, 734 // 2. A and B have the same memory object size, and 735 // 3. A belongs in B's group according to its distance from B. 736 // 737 // Special care is taken to ensure group formation will not break any 738 // dependences. 739 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend(); 740 BI != E; ++BI) { 741 Instruction *B = BI->first; 742 StrideDescriptor DesB = BI->second; 743 744 // Initialize a group for B if it has an allowable stride. Even if we don't 745 // create a group for B, we continue with the bottom-up algorithm to ensure 746 // we don't break any of B's dependences. 747 InterleaveGroup *Group = nullptr; 748 if (isStrided(DesB.Stride) && 749 (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) { 750 Group = getInterleaveGroup(B); 751 if (!Group) { 752 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B 753 << '\n'); 754 Group = createInterleaveGroup(B, DesB.Stride, DesB.Align); 755 } 756 if (B->mayWriteToMemory()) 757 StoreGroups.insert(Group); 758 else 759 LoadGroups.insert(Group); 760 } 761 762 for (auto AI = std::next(BI); AI != E; ++AI) { 763 Instruction *A = AI->first; 764 StrideDescriptor DesA = AI->second; 765 766 // Our code motion strategy implies that we can't have dependences 767 // between accesses in an interleaved group and other accesses located 768 // between the first and last member of the group. Note that this also 769 // means that a group can't have more than one member at a given offset. 770 // The accesses in a group can have dependences with other accesses, but 771 // we must ensure we don't extend the boundaries of the group such that 772 // we encompass those dependent accesses. 773 // 774 // For example, assume we have the sequence of accesses shown below in a 775 // stride-2 loop: 776 // 777 // (1, 2) is a group | A[i] = a; // (1) 778 // | A[i-1] = b; // (2) | 779 // A[i-3] = c; // (3) 780 // A[i] = d; // (4) | (2, 4) is not a group 781 // 782 // Because accesses (2) and (3) are dependent, we can group (2) with (1) 783 // but not with (4). If we did, the dependent access (3) would be within 784 // the boundaries of the (2, 4) group. 785 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) { 786 // If a dependence exists and A is already in a group, we know that A 787 // must be a store since A precedes B and WAR dependences are allowed. 788 // Thus, A would be sunk below B. We release A's group to prevent this 789 // illegal code motion. A will then be free to form another group with 790 // instructions that precede it. 791 if (isInterleaved(A)) { 792 InterleaveGroup *StoreGroup = getInterleaveGroup(A); 793 StoreGroups.remove(StoreGroup); 794 releaseGroup(StoreGroup); 795 } 796 797 // If a dependence exists and A is not already in a group (or it was 798 // and we just released it), B might be hoisted above A (if B is a 799 // load) or another store might be sunk below A (if B is a store). In 800 // either case, we can't add additional instructions to B's group. B 801 // will only form a group with instructions that it precedes. 802 break; 803 } 804 805 // At this point, we've checked for illegal code motion. If either A or B 806 // isn't strided, there's nothing left to do. 807 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride)) 808 continue; 809 810 // Ignore A if it's already in a group or isn't the same kind of memory 811 // operation as B. 812 // Note that mayReadFromMemory() isn't mutually exclusive to 813 // mayWriteToMemory in the case of atomic loads. We shouldn't see those 814 // here, canVectorizeMemory() should have returned false - except for the 815 // case we asked for optimization remarks. 816 if (isInterleaved(A) || 817 (A->mayReadFromMemory() != B->mayReadFromMemory()) || 818 (A->mayWriteToMemory() != B->mayWriteToMemory())) 819 continue; 820 821 // Check rules 1 and 2. Ignore A if its stride or size is different from 822 // that of B. 823 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size) 824 continue; 825 826 // Ignore A if the memory object of A and B don't belong to the same 827 // address space 828 if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B)) 829 continue; 830 831 // Calculate the distance from A to B. 832 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>( 833 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev)); 834 if (!DistToB) 835 continue; 836 int64_t DistanceToB = DistToB->getAPInt().getSExtValue(); 837 838 // Check rule 3. Ignore A if its distance to B is not a multiple of the 839 // size. 840 if (DistanceToB % static_cast<int64_t>(DesB.Size)) 841 continue; 842 843 // All members of a predicated interleave-group must have the same predicate, 844 // and currently must reside in the same BB. 845 BasicBlock *BlockA = A->getParent(); 846 BasicBlock *BlockB = B->getParent(); 847 if ((isPredicated(BlockA) || isPredicated(BlockB)) && 848 (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB)) 849 continue; 850 851 // The index of A is the index of B plus A's distance to B in multiples 852 // of the size. 853 int IndexA = 854 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size); 855 856 // Try to insert A into B's group. 857 if (Group->insertMember(A, IndexA, DesA.Align)) { 858 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n' 859 << " into the interleave group with" << *B 860 << '\n'); 861 InterleaveGroupMap[A] = Group; 862 863 // Set the first load in program order as the insert position. 864 if (A->mayReadFromMemory()) 865 Group->setInsertPos(A); 866 } 867 } // Iteration over A accesses. 868 } // Iteration over B accesses. 869 870 // Remove interleaved store groups with gaps. 871 for (InterleaveGroup *Group : StoreGroups) 872 if (Group->getNumMembers() != Group->getFactor()) { 873 LLVM_DEBUG( 874 dbgs() << "LV: Invalidate candidate interleaved store group due " 875 "to gaps.\n"); 876 releaseGroup(Group); 877 } 878 // Remove interleaved groups with gaps (currently only loads) whose memory 879 // accesses may wrap around. We have to revisit the getPtrStride analysis, 880 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does 881 // not check wrapping (see documentation there). 882 // FORNOW we use Assume=false; 883 // TODO: Change to Assume=true but making sure we don't exceed the threshold 884 // of runtime SCEV assumptions checks (thereby potentially failing to 885 // vectorize altogether). 886 // Additional optional optimizations: 887 // TODO: If we are peeling the loop and we know that the first pointer doesn't 888 // wrap then we can deduce that all pointers in the group don't wrap. 889 // This means that we can forcefully peel the loop in order to only have to 890 // check the first pointer for no-wrap. When we'll change to use Assume=true 891 // we'll only need at most one runtime check per interleaved group. 892 for (InterleaveGroup *Group : LoadGroups) { 893 // Case 1: A full group. Can Skip the checks; For full groups, if the wide 894 // load would wrap around the address space we would do a memory access at 895 // nullptr even without the transformation. 896 if (Group->getNumMembers() == Group->getFactor()) 897 continue; 898 899 // Case 2: If first and last members of the group don't wrap this implies 900 // that all the pointers in the group don't wrap. 901 // So we check only group member 0 (which is always guaranteed to exist), 902 // and group member Factor - 1; If the latter doesn't exist we rely on 903 // peeling (if it is a non-reveresed accsess -- see Case 3). 904 Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0)); 905 if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false, 906 /*ShouldCheckWrap=*/true)) { 907 LLVM_DEBUG( 908 dbgs() << "LV: Invalidate candidate interleaved group due to " 909 "first group member potentially pointer-wrapping.\n"); 910 releaseGroup(Group); 911 continue; 912 } 913 Instruction *LastMember = Group->getMember(Group->getFactor() - 1); 914 if (LastMember) { 915 Value *LastMemberPtr = getLoadStorePointerOperand(LastMember); 916 if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false, 917 /*ShouldCheckWrap=*/true)) { 918 LLVM_DEBUG( 919 dbgs() << "LV: Invalidate candidate interleaved group due to " 920 "last group member potentially pointer-wrapping.\n"); 921 releaseGroup(Group); 922 } 923 } else { 924 // Case 3: A non-reversed interleaved load group with gaps: We need 925 // to execute at least one scalar epilogue iteration. This will ensure 926 // we don't speculatively access memory out-of-bounds. We only need 927 // to look for a member at index factor - 1, since every group must have 928 // a member at index zero. 929 if (Group->isReverse()) { 930 LLVM_DEBUG( 931 dbgs() << "LV: Invalidate candidate interleaved group due to " 932 "a reverse access with gaps.\n"); 933 releaseGroup(Group); 934 continue; 935 } 936 LLVM_DEBUG( 937 dbgs() << "LV: Interleaved group requires epilogue iteration.\n"); 938 RequiresScalarEpilogue = true; 939 } 940 } 941 } 942 943 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() { 944 // If no group had triggered the requirement to create an epilogue loop, 945 // there is nothing to do. 946 if (!requiresScalarEpilogue()) 947 return; 948 949 // Avoid releasing a Group twice. 950 SmallPtrSet<InterleaveGroup *, 4> DelSet; 951 for (auto &I : InterleaveGroupMap) { 952 InterleaveGroup *Group = I.second; 953 if (Group->requiresScalarEpilogue()) 954 DelSet.insert(Group); 955 } 956 for (auto *Ptr : DelSet) { 957 LLVM_DEBUG( 958 dbgs() 959 << "LV: Invalidate candidate interleaved group due to gaps that " 960 "require a scalar epilogue (not allowed under optsize) and cannot " 961 "be masked (not enabled). \n"); 962 releaseGroup(Ptr); 963 } 964 965 RequiresScalarEpilogue = false; 966 } 967