1 //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===// 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 file defines vectorizer utilities. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Analysis/VectorUtils.h" 14 #include "llvm/ADT/EquivalenceClasses.h" 15 #include "llvm/Analysis/DemandedBits.h" 16 #include "llvm/Analysis/LoopInfo.h" 17 #include "llvm/Analysis/LoopIterator.h" 18 #include "llvm/Analysis/ScalarEvolution.h" 19 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 20 #include "llvm/Analysis/TargetTransformInfo.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/GetElementPtrTypeIterator.h" 24 #include "llvm/IR/IRBuilder.h" 25 #include "llvm/IR/PatternMatch.h" 26 #include "llvm/IR/Value.h" 27 #include "llvm/Support/CommandLine.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 (except operands that are marked as always being scalar by 43 /// hasVectorInstrinsicScalarOpd). 44 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) { 45 switch (ID) { 46 case Intrinsic::abs: // Begin integer bit-manipulation. 47 case Intrinsic::bswap: 48 case Intrinsic::bitreverse: 49 case Intrinsic::ctpop: 50 case Intrinsic::ctlz: 51 case Intrinsic::cttz: 52 case Intrinsic::fshl: 53 case Intrinsic::fshr: 54 case Intrinsic::smax: 55 case Intrinsic::smin: 56 case Intrinsic::umax: 57 case Intrinsic::umin: 58 case Intrinsic::sadd_sat: 59 case Intrinsic::ssub_sat: 60 case Intrinsic::uadd_sat: 61 case Intrinsic::usub_sat: 62 case Intrinsic::smul_fix: 63 case Intrinsic::smul_fix_sat: 64 case Intrinsic::umul_fix: 65 case Intrinsic::umul_fix_sat: 66 case Intrinsic::sqrt: // Begin floating-point. 67 case Intrinsic::sin: 68 case Intrinsic::cos: 69 case Intrinsic::exp: 70 case Intrinsic::exp2: 71 case Intrinsic::log: 72 case Intrinsic::log10: 73 case Intrinsic::log2: 74 case Intrinsic::fabs: 75 case Intrinsic::minnum: 76 case Intrinsic::maxnum: 77 case Intrinsic::minimum: 78 case Intrinsic::maximum: 79 case Intrinsic::copysign: 80 case Intrinsic::floor: 81 case Intrinsic::ceil: 82 case Intrinsic::trunc: 83 case Intrinsic::rint: 84 case Intrinsic::nearbyint: 85 case Intrinsic::round: 86 case Intrinsic::roundeven: 87 case Intrinsic::pow: 88 case Intrinsic::fma: 89 case Intrinsic::fmuladd: 90 case Intrinsic::powi: 91 case Intrinsic::canonicalize: 92 return true; 93 default: 94 return false; 95 } 96 } 97 98 /// Identifies if the vector form of the intrinsic has a scalar operand. 99 bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, 100 unsigned ScalarOpdIdx) { 101 switch (ID) { 102 case Intrinsic::abs: 103 case Intrinsic::ctlz: 104 case Intrinsic::cttz: 105 case Intrinsic::powi: 106 return (ScalarOpdIdx == 1); 107 case Intrinsic::smul_fix: 108 case Intrinsic::smul_fix_sat: 109 case Intrinsic::umul_fix: 110 case Intrinsic::umul_fix_sat: 111 return (ScalarOpdIdx == 2); 112 default: 113 return false; 114 } 115 } 116 117 /// Returns intrinsic ID for call. 118 /// For the input call instruction it finds mapping intrinsic and returns 119 /// its ID, in case it does not found it return not_intrinsic. 120 Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI, 121 const TargetLibraryInfo *TLI) { 122 Intrinsic::ID ID = getIntrinsicForCallSite(*CI, TLI); 123 if (ID == Intrinsic::not_intrinsic) 124 return Intrinsic::not_intrinsic; 125 126 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start || 127 ID == Intrinsic::lifetime_end || ID == Intrinsic::assume || 128 ID == Intrinsic::sideeffect) 129 return ID; 130 return Intrinsic::not_intrinsic; 131 } 132 133 /// Find the operand of the GEP that should be checked for consecutive 134 /// stores. This ignores trailing indices that have no effect on the final 135 /// pointer. 136 unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) { 137 const DataLayout &DL = Gep->getModule()->getDataLayout(); 138 unsigned LastOperand = Gep->getNumOperands() - 1; 139 unsigned GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType()); 140 141 // Walk backwards and try to peel off zeros. 142 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) { 143 // Find the type we're currently indexing into. 144 gep_type_iterator GEPTI = gep_type_begin(Gep); 145 std::advance(GEPTI, LastOperand - 2); 146 147 // If it's a type with the same allocation size as the result of the GEP we 148 // can peel off the zero index. 149 if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize) 150 break; 151 --LastOperand; 152 } 153 154 return LastOperand; 155 } 156 157 /// If the argument is a GEP, then returns the operand identified by 158 /// getGEPInductionOperand. However, if there is some other non-loop-invariant 159 /// operand, it returns that instead. 160 Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 161 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 162 if (!GEP) 163 return Ptr; 164 165 unsigned InductionOperand = getGEPInductionOperand(GEP); 166 167 // Check that all of the gep indices are uniform except for our induction 168 // operand. 169 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) 170 if (i != InductionOperand && 171 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp)) 172 return Ptr; 173 return GEP->getOperand(InductionOperand); 174 } 175 176 /// If a value has only one user that is a CastInst, return it. 177 Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) { 178 Value *UniqueCast = nullptr; 179 for (User *U : Ptr->users()) { 180 CastInst *CI = dyn_cast<CastInst>(U); 181 if (CI && CI->getType() == Ty) { 182 if (!UniqueCast) 183 UniqueCast = CI; 184 else 185 return nullptr; 186 } 187 } 188 return UniqueCast; 189 } 190 191 /// Get the stride of a pointer access in a loop. Looks for symbolic 192 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise. 193 Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) { 194 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 195 if (!PtrTy || PtrTy->isAggregateType()) 196 return nullptr; 197 198 // Try to remove a gep instruction to make the pointer (actually index at this 199 // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the 200 // pointer, otherwise, we are analyzing the index. 201 Value *OrigPtr = Ptr; 202 203 // The size of the pointer access. 204 int64_t PtrAccessSize = 1; 205 206 Ptr = stripGetElementPtr(Ptr, SE, Lp); 207 const SCEV *V = SE->getSCEV(Ptr); 208 209 if (Ptr != OrigPtr) 210 // Strip off casts. 211 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) 212 V = C->getOperand(); 213 214 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V); 215 if (!S) 216 return nullptr; 217 218 V = S->getStepRecurrence(*SE); 219 if (!V) 220 return nullptr; 221 222 // Strip off the size of access multiplication if we are still analyzing the 223 // pointer. 224 if (OrigPtr == Ptr) { 225 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) { 226 if (M->getOperand(0)->getSCEVType() != scConstant) 227 return nullptr; 228 229 const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt(); 230 231 // Huge step value - give up. 232 if (APStepVal.getBitWidth() > 64) 233 return nullptr; 234 235 int64_t StepVal = APStepVal.getSExtValue(); 236 if (PtrAccessSize != StepVal) 237 return nullptr; 238 V = M->getOperand(1); 239 } 240 } 241 242 // Strip off casts. 243 Type *StripedOffRecurrenceCast = nullptr; 244 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) { 245 StripedOffRecurrenceCast = C->getType(); 246 V = C->getOperand(); 247 } 248 249 // Look for the loop invariant symbolic value. 250 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V); 251 if (!U) 252 return nullptr; 253 254 Value *Stride = U->getValue(); 255 if (!Lp->isLoopInvariant(Stride)) 256 return nullptr; 257 258 // If we have stripped off the recurrence cast we have to make sure that we 259 // return the value that is used in this loop so that we can replace it later. 260 if (StripedOffRecurrenceCast) 261 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast); 262 263 return Stride; 264 } 265 266 /// Given a vector and an element number, see if the scalar value is 267 /// already around as a register, for example if it were inserted then extracted 268 /// from the vector. 269 Value *llvm::findScalarElement(Value *V, unsigned EltNo) { 270 assert(V->getType()->isVectorTy() && "Not looking at a vector?"); 271 VectorType *VTy = cast<VectorType>(V->getType()); 272 // For fixed-length vector, return undef for out of range access. 273 if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) { 274 unsigned Width = FVTy->getNumElements(); 275 if (EltNo >= Width) 276 return UndefValue::get(FVTy->getElementType()); 277 } 278 279 if (Constant *C = dyn_cast<Constant>(V)) 280 return C->getAggregateElement(EltNo); 281 282 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) { 283 // If this is an insert to a variable element, we don't know what it is. 284 if (!isa<ConstantInt>(III->getOperand(2))) 285 return nullptr; 286 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue(); 287 288 // If this is an insert to the element we are looking for, return the 289 // inserted value. 290 if (EltNo == IIElt) 291 return III->getOperand(1); 292 293 // Otherwise, the insertelement doesn't modify the value, recurse on its 294 // vector input. 295 return findScalarElement(III->getOperand(0), EltNo); 296 } 297 298 ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V); 299 // Restrict the following transformation to fixed-length vector. 300 if (SVI && isa<FixedVectorType>(SVI->getType())) { 301 unsigned LHSWidth = 302 cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements(); 303 int InEl = SVI->getMaskValue(EltNo); 304 if (InEl < 0) 305 return UndefValue::get(VTy->getElementType()); 306 if (InEl < (int)LHSWidth) 307 return findScalarElement(SVI->getOperand(0), InEl); 308 return findScalarElement(SVI->getOperand(1), InEl - LHSWidth); 309 } 310 311 // Extract a value from a vector add operation with a constant zero. 312 // TODO: Use getBinOpIdentity() to generalize this. 313 Value *Val; Constant *C; 314 if (match(V, m_Add(m_Value(Val), m_Constant(C)))) 315 if (Constant *Elt = C->getAggregateElement(EltNo)) 316 if (Elt->isNullValue()) 317 return findScalarElement(Val, EltNo); 318 319 // Otherwise, we don't know. 320 return nullptr; 321 } 322 323 int llvm::getSplatIndex(ArrayRef<int> Mask) { 324 int SplatIndex = -1; 325 for (int M : Mask) { 326 // Ignore invalid (undefined) mask elements. 327 if (M < 0) 328 continue; 329 330 // There can be only 1 non-negative mask element value if this is a splat. 331 if (SplatIndex != -1 && SplatIndex != M) 332 return -1; 333 334 // Initialize the splat index to the 1st non-negative mask element. 335 SplatIndex = M; 336 } 337 assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?"); 338 return SplatIndex; 339 } 340 341 /// Get splat value if the input is a splat vector or return nullptr. 342 /// This function is not fully general. It checks only 2 cases: 343 /// the input value is (1) a splat constant vector or (2) a sequence 344 /// of instructions that broadcasts a scalar at element 0. 345 const llvm::Value *llvm::getSplatValue(const Value *V) { 346 if (isa<VectorType>(V->getType())) 347 if (auto *C = dyn_cast<Constant>(V)) 348 return C->getSplatValue(); 349 350 // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...> 351 Value *Splat; 352 if (match(V, 353 m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat), m_ZeroInt()), 354 m_Value(), m_ZeroMask()))) 355 return Splat; 356 357 return nullptr; 358 } 359 360 // This setting is based on its counterpart in value tracking, but it could be 361 // adjusted if needed. 362 const unsigned MaxDepth = 6; 363 364 bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) { 365 assert(Depth <= MaxDepth && "Limit Search Depth"); 366 367 if (isa<VectorType>(V->getType())) { 368 if (isa<UndefValue>(V)) 369 return true; 370 // FIXME: We can allow undefs, but if Index was specified, we may want to 371 // check that the constant is defined at that index. 372 if (auto *C = dyn_cast<Constant>(V)) 373 return C->getSplatValue() != nullptr; 374 } 375 376 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) { 377 // FIXME: We can safely allow undefs here. If Index was specified, we will 378 // check that the mask elt is defined at the required index. 379 if (!is_splat(Shuf->getShuffleMask())) 380 return false; 381 382 // Match any index. 383 if (Index == -1) 384 return true; 385 386 // Match a specific element. The mask should be defined at and match the 387 // specified index. 388 return Shuf->getMaskValue(Index) == Index; 389 } 390 391 // The remaining tests are all recursive, so bail out if we hit the limit. 392 if (Depth++ == MaxDepth) 393 return false; 394 395 // If both operands of a binop are splats, the result is a splat. 396 Value *X, *Y, *Z; 397 if (match(V, m_BinOp(m_Value(X), m_Value(Y)))) 398 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth); 399 400 // If all operands of a select are splats, the result is a splat. 401 if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z)))) 402 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) && 403 isSplatValue(Z, Index, Depth); 404 405 // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops). 406 407 return false; 408 } 409 410 void llvm::narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask, 411 SmallVectorImpl<int> &ScaledMask) { 412 assert(Scale > 0 && "Unexpected scaling factor"); 413 414 // Fast-path: if no scaling, then it is just a copy. 415 if (Scale == 1) { 416 ScaledMask.assign(Mask.begin(), Mask.end()); 417 return; 418 } 419 420 ScaledMask.clear(); 421 for (int MaskElt : Mask) { 422 if (MaskElt >= 0) { 423 assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= 424 std::numeric_limits<int32_t>::max() && 425 "Overflowed 32-bits"); 426 } 427 for (int SliceElt = 0; SliceElt != Scale; ++SliceElt) 428 ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt); 429 } 430 } 431 432 bool llvm::widenShuffleMaskElts(int Scale, ArrayRef<int> Mask, 433 SmallVectorImpl<int> &ScaledMask) { 434 assert(Scale > 0 && "Unexpected scaling factor"); 435 436 // Fast-path: if no scaling, then it is just a copy. 437 if (Scale == 1) { 438 ScaledMask.assign(Mask.begin(), Mask.end()); 439 return true; 440 } 441 442 // We must map the original elements down evenly to a type with less elements. 443 int NumElts = Mask.size(); 444 if (NumElts % Scale != 0) 445 return false; 446 447 ScaledMask.clear(); 448 ScaledMask.reserve(NumElts / Scale); 449 450 // Step through the input mask by splitting into Scale-sized slices. 451 do { 452 ArrayRef<int> MaskSlice = Mask.take_front(Scale); 453 assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice."); 454 455 // The first element of the slice determines how we evaluate this slice. 456 int SliceFront = MaskSlice.front(); 457 if (SliceFront < 0) { 458 // Negative values (undef or other "sentinel" values) must be equal across 459 // the entire slice. 460 if (!is_splat(MaskSlice)) 461 return false; 462 ScaledMask.push_back(SliceFront); 463 } else { 464 // A positive mask element must be cleanly divisible. 465 if (SliceFront % Scale != 0) 466 return false; 467 // Elements of the slice must be consecutive. 468 for (int i = 1; i < Scale; ++i) 469 if (MaskSlice[i] != SliceFront + i) 470 return false; 471 ScaledMask.push_back(SliceFront / Scale); 472 } 473 Mask = Mask.drop_front(Scale); 474 } while (!Mask.empty()); 475 476 assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask"); 477 478 // All elements of the original mask can be scaled down to map to the elements 479 // of a mask with wider elements. 480 return true; 481 } 482 483 MapVector<Instruction *, uint64_t> 484 llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB, 485 const TargetTransformInfo *TTI) { 486 487 // DemandedBits will give us every value's live-out bits. But we want 488 // to ensure no extra casts would need to be inserted, so every DAG 489 // of connected values must have the same minimum bitwidth. 490 EquivalenceClasses<Value *> ECs; 491 SmallVector<Value *, 16> Worklist; 492 SmallPtrSet<Value *, 4> Roots; 493 SmallPtrSet<Value *, 16> Visited; 494 DenseMap<Value *, uint64_t> DBits; 495 SmallPtrSet<Instruction *, 4> InstructionSet; 496 MapVector<Instruction *, uint64_t> MinBWs; 497 498 // Determine the roots. We work bottom-up, from truncs or icmps. 499 bool SeenExtFromIllegalType = false; 500 for (auto *BB : Blocks) 501 for (auto &I : *BB) { 502 InstructionSet.insert(&I); 503 504 if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) && 505 !TTI->isTypeLegal(I.getOperand(0)->getType())) 506 SeenExtFromIllegalType = true; 507 508 // Only deal with non-vector integers up to 64-bits wide. 509 if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) && 510 !I.getType()->isVectorTy() && 511 I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) { 512 // Don't make work for ourselves. If we know the loaded type is legal, 513 // don't add it to the worklist. 514 if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType())) 515 continue; 516 517 Worklist.push_back(&I); 518 Roots.insert(&I); 519 } 520 } 521 // Early exit. 522 if (Worklist.empty() || (TTI && !SeenExtFromIllegalType)) 523 return MinBWs; 524 525 // Now proceed breadth-first, unioning values together. 526 while (!Worklist.empty()) { 527 Value *Val = Worklist.pop_back_val(); 528 Value *Leader = ECs.getOrInsertLeaderValue(Val); 529 530 if (Visited.count(Val)) 531 continue; 532 Visited.insert(Val); 533 534 // Non-instructions terminate a chain successfully. 535 if (!isa<Instruction>(Val)) 536 continue; 537 Instruction *I = cast<Instruction>(Val); 538 539 // If we encounter a type that is larger than 64 bits, we can't represent 540 // it so bail out. 541 if (DB.getDemandedBits(I).getBitWidth() > 64) 542 return MapVector<Instruction *, uint64_t>(); 543 544 uint64_t V = DB.getDemandedBits(I).getZExtValue(); 545 DBits[Leader] |= V; 546 DBits[I] = V; 547 548 // Casts, loads and instructions outside of our range terminate a chain 549 // successfully. 550 if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) || 551 !InstructionSet.count(I)) 552 continue; 553 554 // Unsafe casts terminate a chain unsuccessfully. We can't do anything 555 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to 556 // transform anything that relies on them. 557 if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) || 558 !I->getType()->isIntegerTy()) { 559 DBits[Leader] |= ~0ULL; 560 continue; 561 } 562 563 // We don't modify the types of PHIs. Reductions will already have been 564 // truncated if possible, and inductions' sizes will have been chosen by 565 // indvars. 566 if (isa<PHINode>(I)) 567 continue; 568 569 if (DBits[Leader] == ~0ULL) 570 // All bits demanded, no point continuing. 571 continue; 572 573 for (Value *O : cast<User>(I)->operands()) { 574 ECs.unionSets(Leader, O); 575 Worklist.push_back(O); 576 } 577 } 578 579 // Now we've discovered all values, walk them to see if there are 580 // any users we didn't see. If there are, we can't optimize that 581 // chain. 582 for (auto &I : DBits) 583 for (auto *U : I.first->users()) 584 if (U->getType()->isIntegerTy() && DBits.count(U) == 0) 585 DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL; 586 587 for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) { 588 uint64_t LeaderDemandedBits = 0; 589 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) 590 LeaderDemandedBits |= DBits[*MI]; 591 592 uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) - 593 llvm::countLeadingZeros(LeaderDemandedBits); 594 // Round up to a power of 2 595 if (!isPowerOf2_64((uint64_t)MinBW)) 596 MinBW = NextPowerOf2(MinBW); 597 598 // We don't modify the types of PHIs. Reductions will already have been 599 // truncated if possible, and inductions' sizes will have been chosen by 600 // indvars. 601 // If we are required to shrink a PHI, abandon this entire equivalence class. 602 bool Abort = false; 603 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) 604 if (isa<PHINode>(*MI) && MinBW < (*MI)->getType()->getScalarSizeInBits()) { 605 Abort = true; 606 break; 607 } 608 if (Abort) 609 continue; 610 611 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) { 612 if (!isa<Instruction>(*MI)) 613 continue; 614 Type *Ty = (*MI)->getType(); 615 if (Roots.count(*MI)) 616 Ty = cast<Instruction>(*MI)->getOperand(0)->getType(); 617 if (MinBW < Ty->getScalarSizeInBits()) 618 MinBWs[cast<Instruction>(*MI)] = MinBW; 619 } 620 } 621 622 return MinBWs; 623 } 624 625 /// Add all access groups in @p AccGroups to @p List. 626 template <typename ListT> 627 static void addToAccessGroupList(ListT &List, MDNode *AccGroups) { 628 // Interpret an access group as a list containing itself. 629 if (AccGroups->getNumOperands() == 0) { 630 assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group"); 631 List.insert(AccGroups); 632 return; 633 } 634 635 for (auto &AccGroupListOp : AccGroups->operands()) { 636 auto *Item = cast<MDNode>(AccGroupListOp.get()); 637 assert(isValidAsAccessGroup(Item) && "List item must be an access group"); 638 List.insert(Item); 639 } 640 } 641 642 MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) { 643 if (!AccGroups1) 644 return AccGroups2; 645 if (!AccGroups2) 646 return AccGroups1; 647 if (AccGroups1 == AccGroups2) 648 return AccGroups1; 649 650 SmallSetVector<Metadata *, 4> Union; 651 addToAccessGroupList(Union, AccGroups1); 652 addToAccessGroupList(Union, AccGroups2); 653 654 if (Union.size() == 0) 655 return nullptr; 656 if (Union.size() == 1) 657 return cast<MDNode>(Union.front()); 658 659 LLVMContext &Ctx = AccGroups1->getContext(); 660 return MDNode::get(Ctx, Union.getArrayRef()); 661 } 662 663 MDNode *llvm::intersectAccessGroups(const Instruction *Inst1, 664 const Instruction *Inst2) { 665 bool MayAccessMem1 = Inst1->mayReadOrWriteMemory(); 666 bool MayAccessMem2 = Inst2->mayReadOrWriteMemory(); 667 668 if (!MayAccessMem1 && !MayAccessMem2) 669 return nullptr; 670 if (!MayAccessMem1) 671 return Inst2->getMetadata(LLVMContext::MD_access_group); 672 if (!MayAccessMem2) 673 return Inst1->getMetadata(LLVMContext::MD_access_group); 674 675 MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group); 676 MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group); 677 if (!MD1 || !MD2) 678 return nullptr; 679 if (MD1 == MD2) 680 return MD1; 681 682 // Use set for scalable 'contains' check. 683 SmallPtrSet<Metadata *, 4> AccGroupSet2; 684 addToAccessGroupList(AccGroupSet2, MD2); 685 686 SmallVector<Metadata *, 4> Intersection; 687 if (MD1->getNumOperands() == 0) { 688 assert(isValidAsAccessGroup(MD1) && "Node must be an access group"); 689 if (AccGroupSet2.count(MD1)) 690 Intersection.push_back(MD1); 691 } else { 692 for (const MDOperand &Node : MD1->operands()) { 693 auto *Item = cast<MDNode>(Node.get()); 694 assert(isValidAsAccessGroup(Item) && "List item must be an access group"); 695 if (AccGroupSet2.count(Item)) 696 Intersection.push_back(Item); 697 } 698 } 699 700 if (Intersection.size() == 0) 701 return nullptr; 702 if (Intersection.size() == 1) 703 return cast<MDNode>(Intersection.front()); 704 705 LLVMContext &Ctx = Inst1->getContext(); 706 return MDNode::get(Ctx, Intersection); 707 } 708 709 /// \returns \p I after propagating metadata from \p VL. 710 Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) { 711 Instruction *I0 = cast<Instruction>(VL[0]); 712 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; 713 I0->getAllMetadataOtherThanDebugLoc(Metadata); 714 715 for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, 716 LLVMContext::MD_noalias, LLVMContext::MD_fpmath, 717 LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load, 718 LLVMContext::MD_access_group}) { 719 MDNode *MD = I0->getMetadata(Kind); 720 721 for (int J = 1, E = VL.size(); MD && J != E; ++J) { 722 const Instruction *IJ = cast<Instruction>(VL[J]); 723 MDNode *IMD = IJ->getMetadata(Kind); 724 switch (Kind) { 725 case LLVMContext::MD_tbaa: 726 MD = MDNode::getMostGenericTBAA(MD, IMD); 727 break; 728 case LLVMContext::MD_alias_scope: 729 MD = MDNode::getMostGenericAliasScope(MD, IMD); 730 break; 731 case LLVMContext::MD_fpmath: 732 MD = MDNode::getMostGenericFPMath(MD, IMD); 733 break; 734 case LLVMContext::MD_noalias: 735 case LLVMContext::MD_nontemporal: 736 case LLVMContext::MD_invariant_load: 737 MD = MDNode::intersect(MD, IMD); 738 break; 739 case LLVMContext::MD_access_group: 740 MD = intersectAccessGroups(Inst, IJ); 741 break; 742 default: 743 llvm_unreachable("unhandled metadata"); 744 } 745 } 746 747 Inst->setMetadata(Kind, MD); 748 } 749 750 return Inst; 751 } 752 753 Constant * 754 llvm::createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, 755 const InterleaveGroup<Instruction> &Group) { 756 // All 1's means mask is not needed. 757 if (Group.getNumMembers() == Group.getFactor()) 758 return nullptr; 759 760 // TODO: support reversed access. 761 assert(!Group.isReverse() && "Reversed group not supported."); 762 763 SmallVector<Constant *, 16> Mask; 764 for (unsigned i = 0; i < VF; i++) 765 for (unsigned j = 0; j < Group.getFactor(); ++j) { 766 unsigned HasMember = Group.getMember(j) ? 1 : 0; 767 Mask.push_back(Builder.getInt1(HasMember)); 768 } 769 770 return ConstantVector::get(Mask); 771 } 772 773 llvm::SmallVector<int, 16> 774 llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) { 775 SmallVector<int, 16> MaskVec; 776 for (unsigned i = 0; i < VF; i++) 777 for (unsigned j = 0; j < ReplicationFactor; j++) 778 MaskVec.push_back(i); 779 780 return MaskVec; 781 } 782 783 llvm::SmallVector<int, 16> llvm::createInterleaveMask(unsigned VF, 784 unsigned NumVecs) { 785 SmallVector<int, 16> Mask; 786 for (unsigned i = 0; i < VF; i++) 787 for (unsigned j = 0; j < NumVecs; j++) 788 Mask.push_back(j * VF + i); 789 790 return Mask; 791 } 792 793 llvm::SmallVector<int, 16> 794 llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) { 795 SmallVector<int, 16> Mask; 796 for (unsigned i = 0; i < VF; i++) 797 Mask.push_back(Start + i * Stride); 798 799 return Mask; 800 } 801 802 llvm::SmallVector<int, 16> llvm::createSequentialMask(unsigned Start, 803 unsigned NumInts, 804 unsigned NumUndefs) { 805 SmallVector<int, 16> Mask; 806 for (unsigned i = 0; i < NumInts; i++) 807 Mask.push_back(Start + i); 808 809 for (unsigned i = 0; i < NumUndefs; i++) 810 Mask.push_back(-1); 811 812 return Mask; 813 } 814 815 /// A helper function for concatenating vectors. This function concatenates two 816 /// vectors having the same element type. If the second vector has fewer 817 /// elements than the first, it is padded with undefs. 818 static Value *concatenateTwoVectors(IRBuilderBase &Builder, Value *V1, 819 Value *V2) { 820 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType()); 821 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType()); 822 assert(VecTy1 && VecTy2 && 823 VecTy1->getScalarType() == VecTy2->getScalarType() && 824 "Expect two vectors with the same element type"); 825 826 unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements(); 827 unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements(); 828 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements"); 829 830 if (NumElts1 > NumElts2) { 831 // Extend with UNDEFs. 832 V2 = Builder.CreateShuffleVector( 833 V2, UndefValue::get(VecTy2), 834 createSequentialMask(0, NumElts2, NumElts1 - NumElts2)); 835 } 836 837 return Builder.CreateShuffleVector( 838 V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0)); 839 } 840 841 Value *llvm::concatenateVectors(IRBuilderBase &Builder, 842 ArrayRef<Value *> Vecs) { 843 unsigned NumVecs = Vecs.size(); 844 assert(NumVecs > 1 && "Should be at least two vectors"); 845 846 SmallVector<Value *, 8> ResList; 847 ResList.append(Vecs.begin(), Vecs.end()); 848 do { 849 SmallVector<Value *, 8> TmpList; 850 for (unsigned i = 0; i < NumVecs - 1; i += 2) { 851 Value *V0 = ResList[i], *V1 = ResList[i + 1]; 852 assert((V0->getType() == V1->getType() || i == NumVecs - 2) && 853 "Only the last vector may have a different type"); 854 855 TmpList.push_back(concatenateTwoVectors(Builder, V0, V1)); 856 } 857 858 // Push the last vector if the total number of vectors is odd. 859 if (NumVecs % 2 != 0) 860 TmpList.push_back(ResList[NumVecs - 1]); 861 862 ResList = TmpList; 863 NumVecs = ResList.size(); 864 } while (NumVecs > 1); 865 866 return ResList[0]; 867 } 868 869 bool llvm::maskIsAllZeroOrUndef(Value *Mask) { 870 auto *ConstMask = dyn_cast<Constant>(Mask); 871 if (!ConstMask) 872 return false; 873 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask)) 874 return true; 875 for (unsigned 876 I = 0, 877 E = cast<FixedVectorType>(ConstMask->getType())->getNumElements(); 878 I != E; ++I) { 879 if (auto *MaskElt = ConstMask->getAggregateElement(I)) 880 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt)) 881 continue; 882 return false; 883 } 884 return true; 885 } 886 887 888 bool llvm::maskIsAllOneOrUndef(Value *Mask) { 889 auto *ConstMask = dyn_cast<Constant>(Mask); 890 if (!ConstMask) 891 return false; 892 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask)) 893 return true; 894 for (unsigned 895 I = 0, 896 E = cast<FixedVectorType>(ConstMask->getType())->getNumElements(); 897 I != E; ++I) { 898 if (auto *MaskElt = ConstMask->getAggregateElement(I)) 899 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt)) 900 continue; 901 return false; 902 } 903 return true; 904 } 905 906 /// TODO: This is a lot like known bits, but for 907 /// vectors. Is there something we can common this with? 908 APInt llvm::possiblyDemandedEltsInMask(Value *Mask) { 909 910 const unsigned VWidth = 911 cast<FixedVectorType>(Mask->getType())->getNumElements(); 912 APInt DemandedElts = APInt::getAllOnesValue(VWidth); 913 if (auto *CV = dyn_cast<ConstantVector>(Mask)) 914 for (unsigned i = 0; i < VWidth; i++) 915 if (CV->getAggregateElement(i)->isNullValue()) 916 DemandedElts.clearBit(i); 917 return DemandedElts; 918 } 919 920 bool InterleavedAccessInfo::isStrided(int Stride) { 921 unsigned Factor = std::abs(Stride); 922 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor; 923 } 924 925 void InterleavedAccessInfo::collectConstStrideAccesses( 926 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, 927 const ValueToValueMap &Strides) { 928 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 929 930 // Since it's desired that the load/store instructions be maintained in 931 // "program order" for the interleaved access analysis, we have to visit the 932 // blocks in the loop in reverse postorder (i.e., in a topological order). 933 // Such an ordering will ensure that any load/store that may be executed 934 // before a second load/store will precede the second load/store in 935 // AccessStrideInfo. 936 LoopBlocksDFS DFS(TheLoop); 937 DFS.perform(LI); 938 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) 939 for (auto &I : *BB) { 940 auto *LI = dyn_cast<LoadInst>(&I); 941 auto *SI = dyn_cast<StoreInst>(&I); 942 if (!LI && !SI) 943 continue; 944 945 Value *Ptr = getLoadStorePointerOperand(&I); 946 // We don't check wrapping here because we don't know yet if Ptr will be 947 // part of a full group or a group with gaps. Checking wrapping for all 948 // pointers (even those that end up in groups with no gaps) will be overly 949 // conservative. For full groups, wrapping should be ok since if we would 950 // wrap around the address space we would do a memory access at nullptr 951 // even without the transformation. The wrapping checks are therefore 952 // deferred until after we've formed the interleaved groups. 953 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, 954 /*Assume=*/true, /*ShouldCheckWrap=*/false); 955 956 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr); 957 PointerType *PtrTy = cast<PointerType>(Ptr->getType()); 958 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType()); 959 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, 960 getLoadStoreAlignment(&I)); 961 } 962 } 963 964 // Analyze interleaved accesses and collect them into interleaved load and 965 // store groups. 966 // 967 // When generating code for an interleaved load group, we effectively hoist all 968 // loads in the group to the location of the first load in program order. When 969 // generating code for an interleaved store group, we sink all stores to the 970 // location of the last store. This code motion can change the order of load 971 // and store instructions and may break dependences. 972 // 973 // The code generation strategy mentioned above ensures that we won't violate 974 // any write-after-read (WAR) dependences. 975 // 976 // E.g., for the WAR dependence: a = A[i]; // (1) 977 // A[i] = b; // (2) 978 // 979 // The store group of (2) is always inserted at or below (2), and the load 980 // group of (1) is always inserted at or above (1). Thus, the instructions will 981 // never be reordered. All other dependences are checked to ensure the 982 // correctness of the instruction reordering. 983 // 984 // The algorithm visits all memory accesses in the loop in bottom-up program 985 // order. Program order is established by traversing the blocks in the loop in 986 // reverse postorder when collecting the accesses. 987 // 988 // We visit the memory accesses in bottom-up order because it can simplify the 989 // construction of store groups in the presence of write-after-write (WAW) 990 // dependences. 991 // 992 // E.g., for the WAW dependence: A[i] = a; // (1) 993 // A[i] = b; // (2) 994 // A[i + 1] = c; // (3) 995 // 996 // We will first create a store group with (3) and (2). (1) can't be added to 997 // this group because it and (2) are dependent. However, (1) can be grouped 998 // with other accesses that may precede it in program order. Note that a 999 // bottom-up order does not imply that WAW dependences should not be checked. 1000 void InterleavedAccessInfo::analyzeInterleaving( 1001 bool EnablePredicatedInterleavedMemAccesses) { 1002 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n"); 1003 const ValueToValueMap &Strides = LAI->getSymbolicStrides(); 1004 1005 // Holds all accesses with a constant stride. 1006 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo; 1007 collectConstStrideAccesses(AccessStrideInfo, Strides); 1008 1009 if (AccessStrideInfo.empty()) 1010 return; 1011 1012 // Collect the dependences in the loop. 1013 collectDependences(); 1014 1015 // Holds all interleaved store groups temporarily. 1016 SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups; 1017 // Holds all interleaved load groups temporarily. 1018 SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups; 1019 1020 // Search in bottom-up program order for pairs of accesses (A and B) that can 1021 // form interleaved load or store groups. In the algorithm below, access A 1022 // precedes access B in program order. We initialize a group for B in the 1023 // outer loop of the algorithm, and then in the inner loop, we attempt to 1024 // insert each A into B's group if: 1025 // 1026 // 1. A and B have the same stride, 1027 // 2. A and B have the same memory object size, and 1028 // 3. A belongs in B's group according to its distance from B. 1029 // 1030 // Special care is taken to ensure group formation will not break any 1031 // dependences. 1032 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend(); 1033 BI != E; ++BI) { 1034 Instruction *B = BI->first; 1035 StrideDescriptor DesB = BI->second; 1036 1037 // Initialize a group for B if it has an allowable stride. Even if we don't 1038 // create a group for B, we continue with the bottom-up algorithm to ensure 1039 // we don't break any of B's dependences. 1040 InterleaveGroup<Instruction> *Group = nullptr; 1041 if (isStrided(DesB.Stride) && 1042 (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) { 1043 Group = getInterleaveGroup(B); 1044 if (!Group) { 1045 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B 1046 << '\n'); 1047 Group = createInterleaveGroup(B, DesB.Stride, DesB.Alignment); 1048 } 1049 if (B->mayWriteToMemory()) 1050 StoreGroups.insert(Group); 1051 else 1052 LoadGroups.insert(Group); 1053 } 1054 1055 for (auto AI = std::next(BI); AI != E; ++AI) { 1056 Instruction *A = AI->first; 1057 StrideDescriptor DesA = AI->second; 1058 1059 // Our code motion strategy implies that we can't have dependences 1060 // between accesses in an interleaved group and other accesses located 1061 // between the first and last member of the group. Note that this also 1062 // means that a group can't have more than one member at a given offset. 1063 // The accesses in a group can have dependences with other accesses, but 1064 // we must ensure we don't extend the boundaries of the group such that 1065 // we encompass those dependent accesses. 1066 // 1067 // For example, assume we have the sequence of accesses shown below in a 1068 // stride-2 loop: 1069 // 1070 // (1, 2) is a group | A[i] = a; // (1) 1071 // | A[i-1] = b; // (2) | 1072 // A[i-3] = c; // (3) 1073 // A[i] = d; // (4) | (2, 4) is not a group 1074 // 1075 // Because accesses (2) and (3) are dependent, we can group (2) with (1) 1076 // but not with (4). If we did, the dependent access (3) would be within 1077 // the boundaries of the (2, 4) group. 1078 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) { 1079 // If a dependence exists and A is already in a group, we know that A 1080 // must be a store since A precedes B and WAR dependences are allowed. 1081 // Thus, A would be sunk below B. We release A's group to prevent this 1082 // illegal code motion. A will then be free to form another group with 1083 // instructions that precede it. 1084 if (isInterleaved(A)) { 1085 InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A); 1086 1087 LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to " 1088 "dependence between " << *A << " and "<< *B << '\n'); 1089 1090 StoreGroups.remove(StoreGroup); 1091 releaseGroup(StoreGroup); 1092 } 1093 1094 // If a dependence exists and A is not already in a group (or it was 1095 // and we just released it), B might be hoisted above A (if B is a 1096 // load) or another store might be sunk below A (if B is a store). In 1097 // either case, we can't add additional instructions to B's group. B 1098 // will only form a group with instructions that it precedes. 1099 break; 1100 } 1101 1102 // At this point, we've checked for illegal code motion. If either A or B 1103 // isn't strided, there's nothing left to do. 1104 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride)) 1105 continue; 1106 1107 // Ignore A if it's already in a group or isn't the same kind of memory 1108 // operation as B. 1109 // Note that mayReadFromMemory() isn't mutually exclusive to 1110 // mayWriteToMemory in the case of atomic loads. We shouldn't see those 1111 // here, canVectorizeMemory() should have returned false - except for the 1112 // case we asked for optimization remarks. 1113 if (isInterleaved(A) || 1114 (A->mayReadFromMemory() != B->mayReadFromMemory()) || 1115 (A->mayWriteToMemory() != B->mayWriteToMemory())) 1116 continue; 1117 1118 // Check rules 1 and 2. Ignore A if its stride or size is different from 1119 // that of B. 1120 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size) 1121 continue; 1122 1123 // Ignore A if the memory object of A and B don't belong to the same 1124 // address space 1125 if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B)) 1126 continue; 1127 1128 // Calculate the distance from A to B. 1129 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>( 1130 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev)); 1131 if (!DistToB) 1132 continue; 1133 int64_t DistanceToB = DistToB->getAPInt().getSExtValue(); 1134 1135 // Check rule 3. Ignore A if its distance to B is not a multiple of the 1136 // size. 1137 if (DistanceToB % static_cast<int64_t>(DesB.Size)) 1138 continue; 1139 1140 // All members of a predicated interleave-group must have the same predicate, 1141 // and currently must reside in the same BB. 1142 BasicBlock *BlockA = A->getParent(); 1143 BasicBlock *BlockB = B->getParent(); 1144 if ((isPredicated(BlockA) || isPredicated(BlockB)) && 1145 (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB)) 1146 continue; 1147 1148 // The index of A is the index of B plus A's distance to B in multiples 1149 // of the size. 1150 int IndexA = 1151 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size); 1152 1153 // Try to insert A into B's group. 1154 if (Group->insertMember(A, IndexA, DesA.Alignment)) { 1155 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n' 1156 << " into the interleave group with" << *B 1157 << '\n'); 1158 InterleaveGroupMap[A] = Group; 1159 1160 // Set the first load in program order as the insert position. 1161 if (A->mayReadFromMemory()) 1162 Group->setInsertPos(A); 1163 } 1164 } // Iteration over A accesses. 1165 } // Iteration over B accesses. 1166 1167 // Remove interleaved store groups with gaps. 1168 for (auto *Group : StoreGroups) 1169 if (Group->getNumMembers() != Group->getFactor()) { 1170 LLVM_DEBUG( 1171 dbgs() << "LV: Invalidate candidate interleaved store group due " 1172 "to gaps.\n"); 1173 releaseGroup(Group); 1174 } 1175 // Remove interleaved groups with gaps (currently only loads) whose memory 1176 // accesses may wrap around. We have to revisit the getPtrStride analysis, 1177 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does 1178 // not check wrapping (see documentation there). 1179 // FORNOW we use Assume=false; 1180 // TODO: Change to Assume=true but making sure we don't exceed the threshold 1181 // of runtime SCEV assumptions checks (thereby potentially failing to 1182 // vectorize altogether). 1183 // Additional optional optimizations: 1184 // TODO: If we are peeling the loop and we know that the first pointer doesn't 1185 // wrap then we can deduce that all pointers in the group don't wrap. 1186 // This means that we can forcefully peel the loop in order to only have to 1187 // check the first pointer for no-wrap. When we'll change to use Assume=true 1188 // we'll only need at most one runtime check per interleaved group. 1189 for (auto *Group : LoadGroups) { 1190 // Case 1: A full group. Can Skip the checks; For full groups, if the wide 1191 // load would wrap around the address space we would do a memory access at 1192 // nullptr even without the transformation. 1193 if (Group->getNumMembers() == Group->getFactor()) 1194 continue; 1195 1196 // Case 2: If first and last members of the group don't wrap this implies 1197 // that all the pointers in the group don't wrap. 1198 // So we check only group member 0 (which is always guaranteed to exist), 1199 // and group member Factor - 1; If the latter doesn't exist we rely on 1200 // peeling (if it is a non-reversed accsess -- see Case 3). 1201 Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0)); 1202 if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false, 1203 /*ShouldCheckWrap=*/true)) { 1204 LLVM_DEBUG( 1205 dbgs() << "LV: Invalidate candidate interleaved group due to " 1206 "first group member potentially pointer-wrapping.\n"); 1207 releaseGroup(Group); 1208 continue; 1209 } 1210 Instruction *LastMember = Group->getMember(Group->getFactor() - 1); 1211 if (LastMember) { 1212 Value *LastMemberPtr = getLoadStorePointerOperand(LastMember); 1213 if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false, 1214 /*ShouldCheckWrap=*/true)) { 1215 LLVM_DEBUG( 1216 dbgs() << "LV: Invalidate candidate interleaved group due to " 1217 "last group member potentially pointer-wrapping.\n"); 1218 releaseGroup(Group); 1219 } 1220 } else { 1221 // Case 3: A non-reversed interleaved load group with gaps: We need 1222 // to execute at least one scalar epilogue iteration. This will ensure 1223 // we don't speculatively access memory out-of-bounds. We only need 1224 // to look for a member at index factor - 1, since every group must have 1225 // a member at index zero. 1226 if (Group->isReverse()) { 1227 LLVM_DEBUG( 1228 dbgs() << "LV: Invalidate candidate interleaved group due to " 1229 "a reverse access with gaps.\n"); 1230 releaseGroup(Group); 1231 continue; 1232 } 1233 LLVM_DEBUG( 1234 dbgs() << "LV: Interleaved group requires epilogue iteration.\n"); 1235 RequiresScalarEpilogue = true; 1236 } 1237 } 1238 } 1239 1240 void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() { 1241 // If no group had triggered the requirement to create an epilogue loop, 1242 // there is nothing to do. 1243 if (!requiresScalarEpilogue()) 1244 return; 1245 1246 bool ReleasedGroup = false; 1247 // Release groups requiring scalar epilogues. Note that this also removes them 1248 // from InterleaveGroups. 1249 for (auto *Group : make_early_inc_range(InterleaveGroups)) { 1250 if (!Group->requiresScalarEpilogue()) 1251 continue; 1252 LLVM_DEBUG( 1253 dbgs() 1254 << "LV: Invalidate candidate interleaved group due to gaps that " 1255 "require a scalar epilogue (not allowed under optsize) and cannot " 1256 "be masked (not enabled). \n"); 1257 releaseGroup(Group); 1258 ReleasedGroup = true; 1259 } 1260 assert(ReleasedGroup && "At least one group must be invalidated, as a " 1261 "scalar epilogue was required"); 1262 (void)ReleasedGroup; 1263 RequiresScalarEpilogue = false; 1264 } 1265 1266 template <typename InstT> 1267 void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const { 1268 llvm_unreachable("addMetadata can only be used for Instruction"); 1269 } 1270 1271 namespace llvm { 1272 template <> 1273 void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const { 1274 SmallVector<Value *, 4> VL; 1275 std::transform(Members.begin(), Members.end(), std::back_inserter(VL), 1276 [](std::pair<int, Instruction *> p) { return p.second; }); 1277 propagateMetadata(NewInst, VL); 1278 } 1279 } 1280 1281 std::string VFABI::mangleTLIVectorName(StringRef VectorName, 1282 StringRef ScalarName, unsigned numArgs, 1283 unsigned VF) { 1284 SmallString<256> Buffer; 1285 llvm::raw_svector_ostream Out(Buffer); 1286 Out << "_ZGV" << VFABI::_LLVM_ << "N" << VF; 1287 for (unsigned I = 0; I < numArgs; ++I) 1288 Out << "v"; 1289 Out << "_" << ScalarName << "(" << VectorName << ")"; 1290 return std::string(Out.str()); 1291 } 1292 1293 void VFABI::getVectorVariantNames( 1294 const CallInst &CI, SmallVectorImpl<std::string> &VariantMappings) { 1295 const StringRef S = 1296 CI.getAttribute(AttributeList::FunctionIndex, VFABI::MappingsAttrName) 1297 .getValueAsString(); 1298 if (S.empty()) 1299 return; 1300 1301 SmallVector<StringRef, 8> ListAttr; 1302 S.split(ListAttr, ","); 1303 1304 for (auto &S : SetVector<StringRef>(ListAttr.begin(), ListAttr.end())) { 1305 #ifndef NDEBUG 1306 LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n"); 1307 Optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, *(CI.getModule())); 1308 assert(Info.hasValue() && "Invalid name for a VFABI variant."); 1309 assert(CI.getModule()->getFunction(Info.getValue().VectorName) && 1310 "Vector function is missing."); 1311 #endif 1312 VariantMappings.push_back(std::string(S)); 1313 } 1314 } 1315 1316 bool VFShape::hasValidParameterList() const { 1317 for (unsigned Pos = 0, NumParams = Parameters.size(); Pos < NumParams; 1318 ++Pos) { 1319 assert(Parameters[Pos].ParamPos == Pos && "Broken parameter list."); 1320 1321 switch (Parameters[Pos].ParamKind) { 1322 default: // Nothing to check. 1323 break; 1324 case VFParamKind::OMP_Linear: 1325 case VFParamKind::OMP_LinearRef: 1326 case VFParamKind::OMP_LinearVal: 1327 case VFParamKind::OMP_LinearUVal: 1328 // Compile time linear steps must be non-zero. 1329 if (Parameters[Pos].LinearStepOrPos == 0) 1330 return false; 1331 break; 1332 case VFParamKind::OMP_LinearPos: 1333 case VFParamKind::OMP_LinearRefPos: 1334 case VFParamKind::OMP_LinearValPos: 1335 case VFParamKind::OMP_LinearUValPos: 1336 // The runtime linear step must be referring to some other 1337 // parameters in the signature. 1338 if (Parameters[Pos].LinearStepOrPos >= int(NumParams)) 1339 return false; 1340 // The linear step parameter must be marked as uniform. 1341 if (Parameters[Parameters[Pos].LinearStepOrPos].ParamKind != 1342 VFParamKind::OMP_Uniform) 1343 return false; 1344 // The linear step parameter can't point at itself. 1345 if (Parameters[Pos].LinearStepOrPos == int(Pos)) 1346 return false; 1347 break; 1348 case VFParamKind::GlobalPredicate: 1349 // The global predicate must be the unique. Can be placed anywhere in the 1350 // signature. 1351 for (unsigned NextPos = Pos + 1; NextPos < NumParams; ++NextPos) 1352 if (Parameters[NextPos].ParamKind == VFParamKind::GlobalPredicate) 1353 return false; 1354 break; 1355 } 1356 } 1357 return true; 1358 } 1359