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