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