1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===// 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 pass implements the Bottom Up SLP vectorizer. It detects consecutive 10 // stores that can be put together into vector-stores. Next, it attempts to 11 // construct vectorizable tree using the use-def chains. If a profitable tree 12 // was found, the SLP vectorizer performs vectorization on the tree. 13 // 14 // The pass is inspired by the work described in the paper: 15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/DenseSet.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/PriorityQueue.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SetOperations.h" 27 #include "llvm/ADT/SetVector.h" 28 #include "llvm/ADT/SmallBitVector.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/ADT/SmallSet.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/ADT/iterator.h" 34 #include "llvm/ADT/iterator_range.h" 35 #include "llvm/Analysis/AliasAnalysis.h" 36 #include "llvm/Analysis/AssumptionCache.h" 37 #include "llvm/Analysis/CodeMetrics.h" 38 #include "llvm/Analysis/DemandedBits.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/IVDescriptors.h" 41 #include "llvm/Analysis/LoopAccessAnalysis.h" 42 #include "llvm/Analysis/LoopInfo.h" 43 #include "llvm/Analysis/MemoryLocation.h" 44 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 45 #include "llvm/Analysis/ScalarEvolution.h" 46 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 47 #include "llvm/Analysis/TargetLibraryInfo.h" 48 #include "llvm/Analysis/TargetTransformInfo.h" 49 #include "llvm/Analysis/ValueTracking.h" 50 #include "llvm/Analysis/VectorUtils.h" 51 #include "llvm/IR/Attributes.h" 52 #include "llvm/IR/BasicBlock.h" 53 #include "llvm/IR/Constant.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/DebugLoc.h" 57 #include "llvm/IR/DerivedTypes.h" 58 #include "llvm/IR/Dominators.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/IRBuilder.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Intrinsics.h" 66 #include "llvm/IR/Module.h" 67 #include "llvm/IR/NoFolder.h" 68 #include "llvm/IR/Operator.h" 69 #include "llvm/IR/PatternMatch.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/User.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/IR/ValueHandle.h" 75 #include "llvm/IR/Verifier.h" 76 #include "llvm/InitializePasses.h" 77 #include "llvm/Pass.h" 78 #include "llvm/Support/Casting.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/Compiler.h" 81 #include "llvm/Support/DOTGraphTraits.h" 82 #include "llvm/Support/Debug.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/GraphWriter.h" 85 #include "llvm/Support/InstructionCost.h" 86 #include "llvm/Support/KnownBits.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 90 #include "llvm/Transforms/Utils/LoopUtils.h" 91 #include "llvm/Transforms/Vectorize.h" 92 #include <algorithm> 93 #include <cassert> 94 #include <cstdint> 95 #include <iterator> 96 #include <memory> 97 #include <set> 98 #include <string> 99 #include <tuple> 100 #include <utility> 101 #include <vector> 102 103 using namespace llvm; 104 using namespace llvm::PatternMatch; 105 using namespace slpvectorizer; 106 107 #define SV_NAME "slp-vectorizer" 108 #define DEBUG_TYPE "SLP" 109 110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated"); 111 112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden, 113 cl::desc("Run the SLP vectorization passes")); 114 115 static cl::opt<int> 116 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, 117 cl::desc("Only vectorize if you gain more than this " 118 "number ")); 119 120 static cl::opt<bool> 121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, 122 cl::desc("Attempt to vectorize horizontal reductions")); 123 124 static cl::opt<bool> ShouldStartVectorizeHorAtStore( 125 "slp-vectorize-hor-store", cl::init(false), cl::Hidden, 126 cl::desc( 127 "Attempt to vectorize horizontal reductions feeding into a store")); 128 129 static cl::opt<int> 130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, 131 cl::desc("Attempt to vectorize for this register size in bits")); 132 133 static cl::opt<unsigned> 134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden, 135 cl::desc("Maximum SLP vectorization factor (0=unlimited)")); 136 137 static cl::opt<int> 138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden, 139 cl::desc("Maximum depth of the lookup for consecutive stores.")); 140 141 /// Limits the size of scheduling regions in a block. 142 /// It avoid long compile times for _very_ large blocks where vector 143 /// instructions are spread over a wide range. 144 /// This limit is way higher than needed by real-world functions. 145 static cl::opt<int> 146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, 147 cl::desc("Limit the size of the SLP scheduling region per block")); 148 149 static cl::opt<int> MinVectorRegSizeOption( 150 "slp-min-reg-size", cl::init(128), cl::Hidden, 151 cl::desc("Attempt to vectorize for this register size in bits")); 152 153 static cl::opt<unsigned> RecursionMaxDepth( 154 "slp-recursion-max-depth", cl::init(12), cl::Hidden, 155 cl::desc("Limit the recursion depth when building a vectorizable tree")); 156 157 static cl::opt<unsigned> MinTreeSize( 158 "slp-min-tree-size", cl::init(3), cl::Hidden, 159 cl::desc("Only vectorize small trees if they are fully vectorizable")); 160 161 // The maximum depth that the look-ahead score heuristic will explore. 162 // The higher this value, the higher the compilation time overhead. 163 static cl::opt<int> LookAheadMaxDepth( 164 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden, 165 cl::desc("The maximum look-ahead depth for operand reordering scores")); 166 167 static cl::opt<bool> 168 ViewSLPTree("view-slp-tree", cl::Hidden, 169 cl::desc("Display the SLP trees with Graphviz")); 170 171 // Limit the number of alias checks. The limit is chosen so that 172 // it has no negative effect on the llvm benchmarks. 173 static const unsigned AliasedCheckLimit = 10; 174 175 // Another limit for the alias checks: The maximum distance between load/store 176 // instructions where alias checks are done. 177 // This limit is useful for very large basic blocks. 178 static const unsigned MaxMemDepDistance = 160; 179 180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling 181 /// regions to be handled. 182 static const int MinScheduleRegionSize = 16; 183 184 /// Predicate for the element types that the SLP vectorizer supports. 185 /// 186 /// The most important thing to filter here are types which are invalid in LLVM 187 /// vectors. We also filter target specific types which have absolutely no 188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just 189 /// avoids spending time checking the cost model and realizing that they will 190 /// be inevitably scalarized. 191 static bool isValidElementType(Type *Ty) { 192 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && 193 !Ty->isPPC_FP128Ty(); 194 } 195 196 /// \returns True if the value is a constant (but not globals/constant 197 /// expressions). 198 static bool isConstant(Value *V) { 199 return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V); 200 } 201 202 /// Checks if \p V is one of vector-like instructions, i.e. undef, 203 /// insertelement/extractelement with constant indices for fixed vector type or 204 /// extractvalue instruction. 205 static bool isVectorLikeInstWithConstOps(Value *V) { 206 if (!isa<InsertElementInst, ExtractElementInst>(V) && 207 !isa<ExtractValueInst, UndefValue>(V)) 208 return false; 209 auto *I = dyn_cast<Instruction>(V); 210 if (!I || isa<ExtractValueInst>(I)) 211 return true; 212 if (!isa<FixedVectorType>(I->getOperand(0)->getType())) 213 return false; 214 if (isa<ExtractElementInst>(I)) 215 return isConstant(I->getOperand(1)); 216 assert(isa<InsertElementInst>(V) && "Expected only insertelement."); 217 return isConstant(I->getOperand(2)); 218 } 219 220 /// \returns true if all of the instructions in \p VL are in the same block or 221 /// false otherwise. 222 static bool allSameBlock(ArrayRef<Value *> VL) { 223 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 224 if (!I0) 225 return false; 226 if (all_of(VL, isVectorLikeInstWithConstOps)) 227 return true; 228 229 BasicBlock *BB = I0->getParent(); 230 for (int I = 1, E = VL.size(); I < E; I++) { 231 auto *II = dyn_cast<Instruction>(VL[I]); 232 if (!II) 233 return false; 234 235 if (BB != II->getParent()) 236 return false; 237 } 238 return true; 239 } 240 241 /// \returns True if all of the values in \p VL are constants (but not 242 /// globals/constant expressions). 243 static bool allConstant(ArrayRef<Value *> VL) { 244 // Constant expressions and globals can't be vectorized like normal integer/FP 245 // constants. 246 return all_of(VL, isConstant); 247 } 248 249 /// \returns True if all of the values in \p VL are identical or some of them 250 /// are UndefValue. 251 static bool isSplat(ArrayRef<Value *> VL) { 252 Value *FirstNonUndef = nullptr; 253 for (Value *V : VL) { 254 if (isa<UndefValue>(V)) 255 continue; 256 if (!FirstNonUndef) { 257 FirstNonUndef = V; 258 continue; 259 } 260 if (V != FirstNonUndef) 261 return false; 262 } 263 return FirstNonUndef != nullptr; 264 } 265 266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator. 267 static bool isCommutative(Instruction *I) { 268 if (auto *Cmp = dyn_cast<CmpInst>(I)) 269 return Cmp->isCommutative(); 270 if (auto *BO = dyn_cast<BinaryOperator>(I)) 271 return BO->isCommutative(); 272 // TODO: This should check for generic Instruction::isCommutative(), but 273 // we need to confirm that the caller code correctly handles Intrinsics 274 // for example (does not have 2 operands). 275 return false; 276 } 277 278 /// Checks if the given value is actually an undefined constant vector. 279 static bool isUndefVector(const Value *V) { 280 if (isa<UndefValue>(V)) 281 return true; 282 auto *C = dyn_cast<Constant>(V); 283 if (!C) 284 return false; 285 if (!C->containsUndefOrPoisonElement()) 286 return false; 287 auto *VecTy = dyn_cast<FixedVectorType>(C->getType()); 288 if (!VecTy) 289 return false; 290 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) { 291 if (Constant *Elem = C->getAggregateElement(I)) 292 if (!isa<UndefValue>(Elem)) 293 return false; 294 } 295 return true; 296 } 297 298 /// Checks if the vector of instructions can be represented as a shuffle, like: 299 /// %x0 = extractelement <4 x i8> %x, i32 0 300 /// %x3 = extractelement <4 x i8> %x, i32 3 301 /// %y1 = extractelement <4 x i8> %y, i32 1 302 /// %y2 = extractelement <4 x i8> %y, i32 2 303 /// %x0x0 = mul i8 %x0, %x0 304 /// %x3x3 = mul i8 %x3, %x3 305 /// %y1y1 = mul i8 %y1, %y1 306 /// %y2y2 = mul i8 %y2, %y2 307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0 308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1 309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2 310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3 311 /// ret <4 x i8> %ins4 312 /// can be transformed into: 313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5, 314 /// i32 6> 315 /// %2 = mul <4 x i8> %1, %1 316 /// ret <4 x i8> %2 317 /// We convert this initially to something like: 318 /// %x0 = extractelement <4 x i8> %x, i32 0 319 /// %x3 = extractelement <4 x i8> %x, i32 3 320 /// %y1 = extractelement <4 x i8> %y, i32 1 321 /// %y2 = extractelement <4 x i8> %y, i32 2 322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0 323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1 324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2 325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3 326 /// %5 = mul <4 x i8> %4, %4 327 /// %6 = extractelement <4 x i8> %5, i32 0 328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0 329 /// %7 = extractelement <4 x i8> %5, i32 1 330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1 331 /// %8 = extractelement <4 x i8> %5, i32 2 332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2 333 /// %9 = extractelement <4 x i8> %5, i32 3 334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3 335 /// ret <4 x i8> %ins4 336 /// InstCombiner transforms this into a shuffle and vector mul 337 /// Mask will return the Shuffle Mask equivalent to the extracted elements. 338 /// TODO: Can we split off and reuse the shuffle mask detection from 339 /// TargetTransformInfo::getInstructionThroughput? 340 static Optional<TargetTransformInfo::ShuffleKind> 341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) { 342 const auto *It = 343 find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); }); 344 if (It == VL.end()) 345 return None; 346 auto *EI0 = cast<ExtractElementInst>(*It); 347 if (isa<ScalableVectorType>(EI0->getVectorOperandType())) 348 return None; 349 unsigned Size = 350 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements(); 351 Value *Vec1 = nullptr; 352 Value *Vec2 = nullptr; 353 enum ShuffleMode { Unknown, Select, Permute }; 354 ShuffleMode CommonShuffleMode = Unknown; 355 Mask.assign(VL.size(), UndefMaskElem); 356 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 357 // Undef can be represented as an undef element in a vector. 358 if (isa<UndefValue>(VL[I])) 359 continue; 360 auto *EI = cast<ExtractElementInst>(VL[I]); 361 if (isa<ScalableVectorType>(EI->getVectorOperandType())) 362 return None; 363 auto *Vec = EI->getVectorOperand(); 364 // We can extractelement from undef or poison vector. 365 if (isUndefVector(Vec)) 366 continue; 367 // All vector operands must have the same number of vector elements. 368 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size) 369 return None; 370 if (isa<UndefValue>(EI->getIndexOperand())) 371 continue; 372 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand()); 373 if (!Idx) 374 return None; 375 // Undefined behavior if Idx is negative or >= Size. 376 if (Idx->getValue().uge(Size)) 377 continue; 378 unsigned IntIdx = Idx->getValue().getZExtValue(); 379 Mask[I] = IntIdx; 380 // For correct shuffling we have to have at most 2 different vector operands 381 // in all extractelement instructions. 382 if (!Vec1 || Vec1 == Vec) { 383 Vec1 = Vec; 384 } else if (!Vec2 || Vec2 == Vec) { 385 Vec2 = Vec; 386 Mask[I] += Size; 387 } else { 388 return None; 389 } 390 if (CommonShuffleMode == Permute) 391 continue; 392 // If the extract index is not the same as the operation number, it is a 393 // permutation. 394 if (IntIdx != I) { 395 CommonShuffleMode = Permute; 396 continue; 397 } 398 CommonShuffleMode = Select; 399 } 400 // If we're not crossing lanes in different vectors, consider it as blending. 401 if (CommonShuffleMode == Select && Vec2) 402 return TargetTransformInfo::SK_Select; 403 // If Vec2 was never used, we have a permutation of a single vector, otherwise 404 // we have permutation of 2 vectors. 405 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc 406 : TargetTransformInfo::SK_PermuteSingleSrc; 407 } 408 409 namespace { 410 411 /// Main data required for vectorization of instructions. 412 struct InstructionsState { 413 /// The very first instruction in the list with the main opcode. 414 Value *OpValue = nullptr; 415 416 /// The main/alternate instruction. 417 Instruction *MainOp = nullptr; 418 Instruction *AltOp = nullptr; 419 420 /// The main/alternate opcodes for the list of instructions. 421 unsigned getOpcode() const { 422 return MainOp ? MainOp->getOpcode() : 0; 423 } 424 425 unsigned getAltOpcode() const { 426 return AltOp ? AltOp->getOpcode() : 0; 427 } 428 429 /// Some of the instructions in the list have alternate opcodes. 430 bool isAltShuffle() const { return AltOp != MainOp; } 431 432 bool isOpcodeOrAlt(Instruction *I) const { 433 unsigned CheckedOpcode = I->getOpcode(); 434 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode; 435 } 436 437 InstructionsState() = delete; 438 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp) 439 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {} 440 }; 441 442 } // end anonymous namespace 443 444 /// Chooses the correct key for scheduling data. If \p Op has the same (or 445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p 446 /// OpValue. 447 static Value *isOneOf(const InstructionsState &S, Value *Op) { 448 auto *I = dyn_cast<Instruction>(Op); 449 if (I && S.isOpcodeOrAlt(I)) 450 return Op; 451 return S.OpValue; 452 } 453 454 /// \returns true if \p Opcode is allowed as part of of the main/alternate 455 /// instruction for SLP vectorization. 456 /// 457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the 458 /// "shuffled out" lane would result in division by zero. 459 static bool isValidForAlternation(unsigned Opcode) { 460 if (Instruction::isIntDivRem(Opcode)) 461 return false; 462 463 return true; 464 } 465 466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 467 unsigned BaseIndex = 0); 468 469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e. 470 /// compatible instructions or constants, or just some other regular values. 471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0, 472 Value *Op1) { 473 return (isConstant(BaseOp0) && isConstant(Op0)) || 474 (isConstant(BaseOp1) && isConstant(Op1)) || 475 (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) && 476 !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) || 477 getSameOpcode({BaseOp0, Op0}).getOpcode() || 478 getSameOpcode({BaseOp1, Op1}).getOpcode(); 479 } 480 481 /// \returns analysis of the Instructions in \p VL described in 482 /// InstructionsState, the Opcode that we suppose the whole list 483 /// could be vectorized even if its structure is diverse. 484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 485 unsigned BaseIndex) { 486 // Make sure these are all Instructions. 487 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); })) 488 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 489 490 bool IsCastOp = isa<CastInst>(VL[BaseIndex]); 491 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]); 492 bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]); 493 CmpInst::Predicate BasePred = 494 IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate() 495 : CmpInst::BAD_ICMP_PREDICATE; 496 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode(); 497 unsigned AltOpcode = Opcode; 498 unsigned AltIndex = BaseIndex; 499 500 // Check for one alternate opcode from another BinaryOperator. 501 // TODO - generalize to support all operators (types, calls etc.). 502 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) { 503 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode(); 504 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) { 505 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 506 continue; 507 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) && 508 isValidForAlternation(Opcode)) { 509 AltOpcode = InstOpcode; 510 AltIndex = Cnt; 511 continue; 512 } 513 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) { 514 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType(); 515 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType(); 516 if (Ty0 == Ty1) { 517 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 518 continue; 519 if (Opcode == AltOpcode) { 520 assert(isValidForAlternation(Opcode) && 521 isValidForAlternation(InstOpcode) && 522 "Cast isn't safe for alternation, logic needs to be updated!"); 523 AltOpcode = InstOpcode; 524 AltIndex = Cnt; 525 continue; 526 } 527 } 528 } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) { 529 auto *BaseInst = cast<Instruction>(VL[BaseIndex]); 530 auto *Inst = cast<Instruction>(VL[Cnt]); 531 Type *Ty0 = BaseInst->getOperand(0)->getType(); 532 Type *Ty1 = Inst->getOperand(0)->getType(); 533 if (Ty0 == Ty1) { 534 Value *BaseOp0 = BaseInst->getOperand(0); 535 Value *BaseOp1 = BaseInst->getOperand(1); 536 Value *Op0 = Inst->getOperand(0); 537 Value *Op1 = Inst->getOperand(1); 538 CmpInst::Predicate CurrentPred = 539 cast<CmpInst>(VL[Cnt])->getPredicate(); 540 CmpInst::Predicate SwappedCurrentPred = 541 CmpInst::getSwappedPredicate(CurrentPred); 542 // Check for compatible operands. If the corresponding operands are not 543 // compatible - need to perform alternate vectorization. 544 if (InstOpcode == Opcode) { 545 if (BasePred == CurrentPred && 546 areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1)) 547 continue; 548 if (BasePred == SwappedCurrentPred && 549 areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0)) 550 continue; 551 if (E == 2 && 552 (BasePred == CurrentPred || BasePred == SwappedCurrentPred)) 553 continue; 554 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 555 CmpInst::Predicate AltPred = AltInst->getPredicate(); 556 Value *AltOp0 = AltInst->getOperand(0); 557 Value *AltOp1 = AltInst->getOperand(1); 558 // Check if operands are compatible with alternate operands. 559 if (AltPred == CurrentPred && 560 areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1)) 561 continue; 562 if (AltPred == SwappedCurrentPred && 563 areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0)) 564 continue; 565 } 566 if (BaseIndex == AltIndex && BasePred != CurrentPred) { 567 assert(isValidForAlternation(Opcode) && 568 isValidForAlternation(InstOpcode) && 569 "Cast isn't safe for alternation, logic needs to be updated!"); 570 AltIndex = Cnt; 571 continue; 572 } 573 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 574 CmpInst::Predicate AltPred = AltInst->getPredicate(); 575 if (BasePred == CurrentPred || BasePred == SwappedCurrentPred || 576 AltPred == CurrentPred || AltPred == SwappedCurrentPred) 577 continue; 578 } 579 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) 580 continue; 581 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 582 } 583 584 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]), 585 cast<Instruction>(VL[AltIndex])); 586 } 587 588 /// \returns true if all of the values in \p VL have the same type or false 589 /// otherwise. 590 static bool allSameType(ArrayRef<Value *> VL) { 591 Type *Ty = VL[0]->getType(); 592 for (int i = 1, e = VL.size(); i < e; i++) 593 if (VL[i]->getType() != Ty) 594 return false; 595 596 return true; 597 } 598 599 /// \returns True if Extract{Value,Element} instruction extracts element Idx. 600 static Optional<unsigned> getExtractIndex(Instruction *E) { 601 unsigned Opcode = E->getOpcode(); 602 assert((Opcode == Instruction::ExtractElement || 603 Opcode == Instruction::ExtractValue) && 604 "Expected extractelement or extractvalue instruction."); 605 if (Opcode == Instruction::ExtractElement) { 606 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 607 if (!CI) 608 return None; 609 return CI->getZExtValue(); 610 } 611 ExtractValueInst *EI = cast<ExtractValueInst>(E); 612 if (EI->getNumIndices() != 1) 613 return None; 614 return *EI->idx_begin(); 615 } 616 617 /// \returns True if in-tree use also needs extract. This refers to 618 /// possible scalar operand in vectorized instruction. 619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, 620 TargetLibraryInfo *TLI) { 621 unsigned Opcode = UserInst->getOpcode(); 622 switch (Opcode) { 623 case Instruction::Load: { 624 LoadInst *LI = cast<LoadInst>(UserInst); 625 return (LI->getPointerOperand() == Scalar); 626 } 627 case Instruction::Store: { 628 StoreInst *SI = cast<StoreInst>(UserInst); 629 return (SI->getPointerOperand() == Scalar); 630 } 631 case Instruction::Call: { 632 CallInst *CI = cast<CallInst>(UserInst); 633 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 634 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 635 if (hasVectorInstrinsicScalarOpd(ID, i)) 636 return (CI->getArgOperand(i) == Scalar); 637 } 638 LLVM_FALLTHROUGH; 639 } 640 default: 641 return false; 642 } 643 } 644 645 /// \returns the AA location that is being access by the instruction. 646 static MemoryLocation getLocation(Instruction *I) { 647 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 648 return MemoryLocation::get(SI); 649 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 650 return MemoryLocation::get(LI); 651 return MemoryLocation(); 652 } 653 654 /// \returns True if the instruction is not a volatile or atomic load/store. 655 static bool isSimple(Instruction *I) { 656 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 657 return LI->isSimple(); 658 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 659 return SI->isSimple(); 660 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 661 return !MI->isVolatile(); 662 return true; 663 } 664 665 /// Shuffles \p Mask in accordance with the given \p SubMask. 666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) { 667 if (SubMask.empty()) 668 return; 669 if (Mask.empty()) { 670 Mask.append(SubMask.begin(), SubMask.end()); 671 return; 672 } 673 SmallVector<int> NewMask(SubMask.size(), UndefMaskElem); 674 int TermValue = std::min(Mask.size(), SubMask.size()); 675 for (int I = 0, E = SubMask.size(); I < E; ++I) { 676 if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem || 677 Mask[SubMask[I]] >= TermValue) 678 continue; 679 NewMask[I] = Mask[SubMask[I]]; 680 } 681 Mask.swap(NewMask); 682 } 683 684 /// Order may have elements assigned special value (size) which is out of 685 /// bounds. Such indices only appear on places which correspond to undef values 686 /// (see canReuseExtract for details) and used in order to avoid undef values 687 /// have effect on operands ordering. 688 /// The first loop below simply finds all unused indices and then the next loop 689 /// nest assigns these indices for undef values positions. 690 /// As an example below Order has two undef positions and they have assigned 691 /// values 3 and 7 respectively: 692 /// before: 6 9 5 4 9 2 1 0 693 /// after: 6 3 5 4 7 2 1 0 694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) { 695 const unsigned Sz = Order.size(); 696 SmallBitVector UnusedIndices(Sz, /*t=*/true); 697 SmallBitVector MaskedIndices(Sz); 698 for (unsigned I = 0; I < Sz; ++I) { 699 if (Order[I] < Sz) 700 UnusedIndices.reset(Order[I]); 701 else 702 MaskedIndices.set(I); 703 } 704 if (MaskedIndices.none()) 705 return; 706 assert(UnusedIndices.count() == MaskedIndices.count() && 707 "Non-synced masked/available indices."); 708 int Idx = UnusedIndices.find_first(); 709 int MIdx = MaskedIndices.find_first(); 710 while (MIdx >= 0) { 711 assert(Idx >= 0 && "Indices must be synced."); 712 Order[MIdx] = Idx; 713 Idx = UnusedIndices.find_next(Idx); 714 MIdx = MaskedIndices.find_next(MIdx); 715 } 716 } 717 718 namespace llvm { 719 720 static void inversePermutation(ArrayRef<unsigned> Indices, 721 SmallVectorImpl<int> &Mask) { 722 Mask.clear(); 723 const unsigned E = Indices.size(); 724 Mask.resize(E, UndefMaskElem); 725 for (unsigned I = 0; I < E; ++I) 726 Mask[Indices[I]] = I; 727 } 728 729 /// \returns inserting index of InsertElement or InsertValue instruction, 730 /// using Offset as base offset for index. 731 static Optional<unsigned> getInsertIndex(Value *InsertInst, 732 unsigned Offset = 0) { 733 int Index = Offset; 734 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) { 735 if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) { 736 auto *VT = cast<FixedVectorType>(IE->getType()); 737 if (CI->getValue().uge(VT->getNumElements())) 738 return None; 739 Index *= VT->getNumElements(); 740 Index += CI->getZExtValue(); 741 return Index; 742 } 743 return None; 744 } 745 746 auto *IV = cast<InsertValueInst>(InsertInst); 747 Type *CurrentType = IV->getType(); 748 for (unsigned I : IV->indices()) { 749 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 750 Index *= ST->getNumElements(); 751 CurrentType = ST->getElementType(I); 752 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 753 Index *= AT->getNumElements(); 754 CurrentType = AT->getElementType(); 755 } else { 756 return None; 757 } 758 Index += I; 759 } 760 return Index; 761 } 762 763 /// Reorders the list of scalars in accordance with the given \p Mask. 764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars, 765 ArrayRef<int> Mask) { 766 assert(!Mask.empty() && "Expected non-empty mask."); 767 SmallVector<Value *> Prev(Scalars.size(), 768 UndefValue::get(Scalars.front()->getType())); 769 Prev.swap(Scalars); 770 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 771 if (Mask[I] != UndefMaskElem) 772 Scalars[Mask[I]] = Prev[I]; 773 } 774 775 namespace slpvectorizer { 776 777 /// Bottom Up SLP Vectorizer. 778 class BoUpSLP { 779 struct TreeEntry; 780 struct ScheduleData; 781 782 public: 783 using ValueList = SmallVector<Value *, 8>; 784 using InstrList = SmallVector<Instruction *, 16>; 785 using ValueSet = SmallPtrSet<Value *, 16>; 786 using StoreList = SmallVector<StoreInst *, 8>; 787 using ExtraValueToDebugLocsMap = 788 MapVector<Value *, SmallVector<Instruction *, 2>>; 789 using OrdersType = SmallVector<unsigned, 4>; 790 791 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, 792 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li, 793 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, 794 const DataLayout *DL, OptimizationRemarkEmitter *ORE) 795 : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), 796 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) { 797 CodeMetrics::collectEphemeralValues(F, AC, EphValues); 798 // Use the vector register size specified by the target unless overridden 799 // by a command-line option. 800 // TODO: It would be better to limit the vectorization factor based on 801 // data type rather than just register size. For example, x86 AVX has 802 // 256-bit registers, but it does not support integer operations 803 // at that width (that requires AVX2). 804 if (MaxVectorRegSizeOption.getNumOccurrences()) 805 MaxVecRegSize = MaxVectorRegSizeOption; 806 else 807 MaxVecRegSize = 808 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) 809 .getFixedSize(); 810 811 if (MinVectorRegSizeOption.getNumOccurrences()) 812 MinVecRegSize = MinVectorRegSizeOption; 813 else 814 MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); 815 } 816 817 /// Vectorize the tree that starts with the elements in \p VL. 818 /// Returns the vectorized root. 819 Value *vectorizeTree(); 820 821 /// Vectorize the tree but with the list of externally used values \p 822 /// ExternallyUsedValues. Values in this MapVector can be replaced but the 823 /// generated extractvalue instructions. 824 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues); 825 826 /// \returns the cost incurred by unwanted spills and fills, caused by 827 /// holding live values over call sites. 828 InstructionCost getSpillCost() const; 829 830 /// \returns the vectorization cost of the subtree that starts at \p VL. 831 /// A negative number means that this is profitable. 832 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None); 833 834 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 835 /// the purpose of scheduling and extraction in the \p UserIgnoreLst. 836 void buildTree(ArrayRef<Value *> Roots, 837 ArrayRef<Value *> UserIgnoreLst = None); 838 839 /// Builds external uses of the vectorized scalars, i.e. the list of 840 /// vectorized scalars to be extracted, their lanes and their scalar users. \p 841 /// ExternallyUsedValues contains additional list of external uses to handle 842 /// vectorization of reductions. 843 void 844 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {}); 845 846 /// Clear the internal data structures that are created by 'buildTree'. 847 void deleteTree() { 848 VectorizableTree.clear(); 849 ScalarToTreeEntry.clear(); 850 MustGather.clear(); 851 ExternalUses.clear(); 852 for (auto &Iter : BlocksSchedules) { 853 BlockScheduling *BS = Iter.second.get(); 854 BS->clear(); 855 } 856 MinBWs.clear(); 857 InstrElementSize.clear(); 858 } 859 860 unsigned getTreeSize() const { return VectorizableTree.size(); } 861 862 /// Perform LICM and CSE on the newly generated gather sequences. 863 void optimizeGatherSequence(); 864 865 /// Checks if the specified gather tree entry \p TE can be represented as a 866 /// shuffled vector entry + (possibly) permutation with other gathers. It 867 /// implements the checks only for possibly ordered scalars (Loads, 868 /// ExtractElement, ExtractValue), which can be part of the graph. 869 Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE); 870 871 /// Gets reordering data for the given tree entry. If the entry is vectorized 872 /// - just return ReorderIndices, otherwise check if the scalars can be 873 /// reordered and return the most optimal order. 874 /// \param TopToBottom If true, include the order of vectorized stores and 875 /// insertelement nodes, otherwise skip them. 876 Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom); 877 878 /// Reorders the current graph to the most profitable order starting from the 879 /// root node to the leaf nodes. The best order is chosen only from the nodes 880 /// of the same size (vectorization factor). Smaller nodes are considered 881 /// parts of subgraph with smaller VF and they are reordered independently. We 882 /// can make it because we still need to extend smaller nodes to the wider VF 883 /// and we can merge reordering shuffles with the widening shuffles. 884 void reorderTopToBottom(); 885 886 /// Reorders the current graph to the most profitable order starting from 887 /// leaves to the root. It allows to rotate small subgraphs and reduce the 888 /// number of reshuffles if the leaf nodes use the same order. In this case we 889 /// can merge the orders and just shuffle user node instead of shuffling its 890 /// operands. Plus, even the leaf nodes have different orders, it allows to 891 /// sink reordering in the graph closer to the root node and merge it later 892 /// during analysis. 893 void reorderBottomToTop(bool IgnoreReorder = false); 894 895 /// \return The vector element size in bits to use when vectorizing the 896 /// expression tree ending at \p V. If V is a store, the size is the width of 897 /// the stored value. Otherwise, the size is the width of the largest loaded 898 /// value reaching V. This method is used by the vectorizer to calculate 899 /// vectorization factors. 900 unsigned getVectorElementSize(Value *V); 901 902 /// Compute the minimum type sizes required to represent the entries in a 903 /// vectorizable tree. 904 void computeMinimumValueSizes(); 905 906 // \returns maximum vector register size as set by TTI or overridden by cl::opt. 907 unsigned getMaxVecRegSize() const { 908 return MaxVecRegSize; 909 } 910 911 // \returns minimum vector register size as set by cl::opt. 912 unsigned getMinVecRegSize() const { 913 return MinVecRegSize; 914 } 915 916 unsigned getMinVF(unsigned Sz) const { 917 return std::max(2U, getMinVecRegSize() / Sz); 918 } 919 920 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 921 unsigned MaxVF = MaxVFOption.getNumOccurrences() ? 922 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode); 923 return MaxVF ? MaxVF : UINT_MAX; 924 } 925 926 /// Check if homogeneous aggregate is isomorphic to some VectorType. 927 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like 928 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> }, 929 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on. 930 /// 931 /// \returns number of elements in vector if isomorphism exists, 0 otherwise. 932 unsigned canMapToVector(Type *T, const DataLayout &DL) const; 933 934 /// \returns True if the VectorizableTree is both tiny and not fully 935 /// vectorizable. We do not vectorize such trees. 936 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const; 937 938 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values 939 /// can be load combined in the backend. Load combining may not be allowed in 940 /// the IR optimizer, so we do not want to alter the pattern. For example, 941 /// partially transforming a scalar bswap() pattern into vector code is 942 /// effectively impossible for the backend to undo. 943 /// TODO: If load combining is allowed in the IR optimizer, this analysis 944 /// may not be necessary. 945 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const; 946 947 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values 948 /// can be load combined in the backend. Load combining may not be allowed in 949 /// the IR optimizer, so we do not want to alter the pattern. For example, 950 /// partially transforming a scalar bswap() pattern into vector code is 951 /// effectively impossible for the backend to undo. 952 /// TODO: If load combining is allowed in the IR optimizer, this analysis 953 /// may not be necessary. 954 bool isLoadCombineCandidate() const; 955 956 OptimizationRemarkEmitter *getORE() { return ORE; } 957 958 /// This structure holds any data we need about the edges being traversed 959 /// during buildTree_rec(). We keep track of: 960 /// (i) the user TreeEntry index, and 961 /// (ii) the index of the edge. 962 struct EdgeInfo { 963 EdgeInfo() = default; 964 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx) 965 : UserTE(UserTE), EdgeIdx(EdgeIdx) {} 966 /// The user TreeEntry. 967 TreeEntry *UserTE = nullptr; 968 /// The operand index of the use. 969 unsigned EdgeIdx = UINT_MAX; 970 #ifndef NDEBUG 971 friend inline raw_ostream &operator<<(raw_ostream &OS, 972 const BoUpSLP::EdgeInfo &EI) { 973 EI.dump(OS); 974 return OS; 975 } 976 /// Debug print. 977 void dump(raw_ostream &OS) const { 978 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null") 979 << " EdgeIdx:" << EdgeIdx << "}"; 980 } 981 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); } 982 #endif 983 }; 984 985 /// A helper data structure to hold the operands of a vector of instructions. 986 /// This supports a fixed vector length for all operand vectors. 987 class VLOperands { 988 /// For each operand we need (i) the value, and (ii) the opcode that it 989 /// would be attached to if the expression was in a left-linearized form. 990 /// This is required to avoid illegal operand reordering. 991 /// For example: 992 /// \verbatim 993 /// 0 Op1 994 /// |/ 995 /// Op1 Op2 Linearized + Op2 996 /// \ / ----------> |/ 997 /// - - 998 /// 999 /// Op1 - Op2 (0 + Op1) - Op2 1000 /// \endverbatim 1001 /// 1002 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'. 1003 /// 1004 /// Another way to think of this is to track all the operations across the 1005 /// path from the operand all the way to the root of the tree and to 1006 /// calculate the operation that corresponds to this path. For example, the 1007 /// path from Op2 to the root crosses the RHS of the '-', therefore the 1008 /// corresponding operation is a '-' (which matches the one in the 1009 /// linearized tree, as shown above). 1010 /// 1011 /// For lack of a better term, we refer to this operation as Accumulated 1012 /// Path Operation (APO). 1013 struct OperandData { 1014 OperandData() = default; 1015 OperandData(Value *V, bool APO, bool IsUsed) 1016 : V(V), APO(APO), IsUsed(IsUsed) {} 1017 /// The operand value. 1018 Value *V = nullptr; 1019 /// TreeEntries only allow a single opcode, or an alternate sequence of 1020 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the 1021 /// APO. It is set to 'true' if 'V' is attached to an inverse operation 1022 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise 1023 /// (e.g., Add/Mul) 1024 bool APO = false; 1025 /// Helper data for the reordering function. 1026 bool IsUsed = false; 1027 }; 1028 1029 /// During operand reordering, we are trying to select the operand at lane 1030 /// that matches best with the operand at the neighboring lane. Our 1031 /// selection is based on the type of value we are looking for. For example, 1032 /// if the neighboring lane has a load, we need to look for a load that is 1033 /// accessing a consecutive address. These strategies are summarized in the 1034 /// 'ReorderingMode' enumerator. 1035 enum class ReorderingMode { 1036 Load, ///< Matching loads to consecutive memory addresses 1037 Opcode, ///< Matching instructions based on opcode (same or alternate) 1038 Constant, ///< Matching constants 1039 Splat, ///< Matching the same instruction multiple times (broadcast) 1040 Failed, ///< We failed to create a vectorizable group 1041 }; 1042 1043 using OperandDataVec = SmallVector<OperandData, 2>; 1044 1045 /// A vector of operand vectors. 1046 SmallVector<OperandDataVec, 4> OpsVec; 1047 1048 const DataLayout &DL; 1049 ScalarEvolution &SE; 1050 const BoUpSLP &R; 1051 1052 /// \returns the operand data at \p OpIdx and \p Lane. 1053 OperandData &getData(unsigned OpIdx, unsigned Lane) { 1054 return OpsVec[OpIdx][Lane]; 1055 } 1056 1057 /// \returns the operand data at \p OpIdx and \p Lane. Const version. 1058 const OperandData &getData(unsigned OpIdx, unsigned Lane) const { 1059 return OpsVec[OpIdx][Lane]; 1060 } 1061 1062 /// Clears the used flag for all entries. 1063 void clearUsed() { 1064 for (unsigned OpIdx = 0, NumOperands = getNumOperands(); 1065 OpIdx != NumOperands; ++OpIdx) 1066 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 1067 ++Lane) 1068 OpsVec[OpIdx][Lane].IsUsed = false; 1069 } 1070 1071 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2. 1072 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) { 1073 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]); 1074 } 1075 1076 // The hard-coded scores listed here are not very important, though it shall 1077 // be higher for better matches to improve the resulting cost. When 1078 // computing the scores of matching one sub-tree with another, we are 1079 // basically counting the number of values that are matching. So even if all 1080 // scores are set to 1, we would still get a decent matching result. 1081 // However, sometimes we have to break ties. For example we may have to 1082 // choose between matching loads vs matching opcodes. This is what these 1083 // scores are helping us with: they provide the order of preference. Also, 1084 // this is important if the scalar is externally used or used in another 1085 // tree entry node in the different lane. 1086 1087 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]). 1088 static const int ScoreConsecutiveLoads = 4; 1089 /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]). 1090 static const int ScoreReversedLoads = 3; 1091 /// ExtractElementInst from same vector and consecutive indexes. 1092 static const int ScoreConsecutiveExtracts = 4; 1093 /// ExtractElementInst from same vector and reversed indices. 1094 static const int ScoreReversedExtracts = 3; 1095 /// Constants. 1096 static const int ScoreConstants = 2; 1097 /// Instructions with the same opcode. 1098 static const int ScoreSameOpcode = 2; 1099 /// Instructions with alt opcodes (e.g, add + sub). 1100 static const int ScoreAltOpcodes = 1; 1101 /// Identical instructions (a.k.a. splat or broadcast). 1102 static const int ScoreSplat = 1; 1103 /// Matching with an undef is preferable to failing. 1104 static const int ScoreUndef = 1; 1105 /// Score for failing to find a decent match. 1106 static const int ScoreFail = 0; 1107 /// Score if all users are vectorized. 1108 static const int ScoreAllUserVectorized = 1; 1109 1110 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes. 1111 /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p 1112 /// MainAltOps. 1113 static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL, 1114 ScalarEvolution &SE, int NumLanes, 1115 ArrayRef<Value *> MainAltOps) { 1116 if (V1 == V2) 1117 return VLOperands::ScoreSplat; 1118 1119 auto *LI1 = dyn_cast<LoadInst>(V1); 1120 auto *LI2 = dyn_cast<LoadInst>(V2); 1121 if (LI1 && LI2) { 1122 if (LI1->getParent() != LI2->getParent()) 1123 return VLOperands::ScoreFail; 1124 1125 Optional<int> Dist = getPointersDiff( 1126 LI1->getType(), LI1->getPointerOperand(), LI2->getType(), 1127 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true); 1128 if (!Dist || *Dist == 0) 1129 return VLOperands::ScoreFail; 1130 // The distance is too large - still may be profitable to use masked 1131 // loads/gathers. 1132 if (std::abs(*Dist) > NumLanes / 2) 1133 return VLOperands::ScoreAltOpcodes; 1134 // This still will detect consecutive loads, but we might have "holes" 1135 // in some cases. It is ok for non-power-2 vectorization and may produce 1136 // better results. It should not affect current vectorization. 1137 return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads 1138 : VLOperands::ScoreReversedLoads; 1139 } 1140 1141 auto *C1 = dyn_cast<Constant>(V1); 1142 auto *C2 = dyn_cast<Constant>(V2); 1143 if (C1 && C2) 1144 return VLOperands::ScoreConstants; 1145 1146 // Extracts from consecutive indexes of the same vector better score as 1147 // the extracts could be optimized away. 1148 Value *EV1; 1149 ConstantInt *Ex1Idx; 1150 if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) { 1151 // Undefs are always profitable for extractelements. 1152 if (isa<UndefValue>(V2)) 1153 return VLOperands::ScoreConsecutiveExtracts; 1154 Value *EV2 = nullptr; 1155 ConstantInt *Ex2Idx = nullptr; 1156 if (match(V2, 1157 m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx), 1158 m_Undef())))) { 1159 // Undefs are always profitable for extractelements. 1160 if (!Ex2Idx) 1161 return VLOperands::ScoreConsecutiveExtracts; 1162 if (isUndefVector(EV2) && EV2->getType() == EV1->getType()) 1163 return VLOperands::ScoreConsecutiveExtracts; 1164 if (EV2 == EV1) { 1165 int Idx1 = Ex1Idx->getZExtValue(); 1166 int Idx2 = Ex2Idx->getZExtValue(); 1167 int Dist = Idx2 - Idx1; 1168 // The distance is too large - still may be profitable to use 1169 // shuffles. 1170 if (std::abs(Dist) == 0) 1171 return VLOperands::ScoreSplat; 1172 if (std::abs(Dist) > NumLanes / 2) 1173 return VLOperands::ScoreSameOpcode; 1174 return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts 1175 : VLOperands::ScoreReversedExtracts; 1176 } 1177 return VLOperands::ScoreAltOpcodes; 1178 } 1179 return VLOperands::ScoreFail; 1180 } 1181 1182 auto *I1 = dyn_cast<Instruction>(V1); 1183 auto *I2 = dyn_cast<Instruction>(V2); 1184 if (I1 && I2) { 1185 if (I1->getParent() != I2->getParent()) 1186 return VLOperands::ScoreFail; 1187 SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end()); 1188 Ops.push_back(I1); 1189 Ops.push_back(I2); 1190 InstructionsState S = getSameOpcode(Ops); 1191 // Note: Only consider instructions with <= 2 operands to avoid 1192 // complexity explosion. 1193 if (S.getOpcode() && 1194 (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() || 1195 !S.isAltShuffle()) && 1196 all_of(Ops, [&S](Value *V) { 1197 return cast<Instruction>(V)->getNumOperands() == 1198 S.MainOp->getNumOperands(); 1199 })) 1200 return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes 1201 : VLOperands::ScoreSameOpcode; 1202 } 1203 1204 if (isa<UndefValue>(V2)) 1205 return VLOperands::ScoreUndef; 1206 1207 return VLOperands::ScoreFail; 1208 } 1209 1210 /// \param Lane lane of the operands under analysis. 1211 /// \param OpIdx operand index in \p Lane lane we're looking the best 1212 /// candidate for. 1213 /// \param Idx operand index of the current candidate value. 1214 /// \returns The additional score due to possible broadcasting of the 1215 /// elements in the lane. It is more profitable to have power-of-2 unique 1216 /// elements in the lane, it will be vectorized with higher probability 1217 /// after removing duplicates. Currently the SLP vectorizer supports only 1218 /// vectorization of the power-of-2 number of unique scalars. 1219 int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1220 Value *IdxLaneV = getData(Idx, Lane).V; 1221 if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V) 1222 return 0; 1223 SmallPtrSet<Value *, 4> Uniques; 1224 for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) { 1225 if (Ln == Lane) 1226 continue; 1227 Value *OpIdxLnV = getData(OpIdx, Ln).V; 1228 if (!isa<Instruction>(OpIdxLnV)) 1229 return 0; 1230 Uniques.insert(OpIdxLnV); 1231 } 1232 int UniquesCount = Uniques.size(); 1233 int UniquesCntWithIdxLaneV = 1234 Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1; 1235 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1236 int UniquesCntWithOpIdxLaneV = 1237 Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1; 1238 if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV) 1239 return 0; 1240 return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) - 1241 UniquesCntWithOpIdxLaneV) - 1242 (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV); 1243 } 1244 1245 /// \param Lane lane of the operands under analysis. 1246 /// \param OpIdx operand index in \p Lane lane we're looking the best 1247 /// candidate for. 1248 /// \param Idx operand index of the current candidate value. 1249 /// \returns The additional score for the scalar which users are all 1250 /// vectorized. 1251 int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1252 Value *IdxLaneV = getData(Idx, Lane).V; 1253 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1254 // Do not care about number of uses for vector-like instructions 1255 // (extractelement/extractvalue with constant indices), they are extracts 1256 // themselves and already externally used. Vectorization of such 1257 // instructions does not add extra extractelement instruction, just may 1258 // remove it. 1259 if (isVectorLikeInstWithConstOps(IdxLaneV) && 1260 isVectorLikeInstWithConstOps(OpIdxLaneV)) 1261 return VLOperands::ScoreAllUserVectorized; 1262 auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV); 1263 if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV)) 1264 return 0; 1265 return R.areAllUsersVectorized(IdxLaneI, None) 1266 ? VLOperands::ScoreAllUserVectorized 1267 : 0; 1268 } 1269 1270 /// Go through the operands of \p LHS and \p RHS recursively until \p 1271 /// MaxLevel, and return the cummulative score. For example: 1272 /// \verbatim 1273 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1] 1274 /// \ / \ / \ / \ / 1275 /// + + + + 1276 /// G1 G2 G3 G4 1277 /// \endverbatim 1278 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at 1279 /// each level recursively, accumulating the score. It starts from matching 1280 /// the additions at level 0, then moves on to the loads (level 1). The 1281 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and 1282 /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while 1283 /// {A[0],C[0]} has a score of VLOperands::ScoreFail. 1284 /// Please note that the order of the operands does not matter, as we 1285 /// evaluate the score of all profitable combinations of operands. In 1286 /// other words the score of G1 and G4 is the same as G1 and G2. This 1287 /// heuristic is based on ideas described in: 1288 /// Look-ahead SLP: Auto-vectorization in the presence of commutative 1289 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha, 1290 /// Luís F. W. Góes 1291 int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel, 1292 ArrayRef<Value *> MainAltOps) { 1293 1294 // Get the shallow score of V1 and V2. 1295 int ShallowScoreAtThisLevel = 1296 getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps); 1297 1298 // If reached MaxLevel, 1299 // or if V1 and V2 are not instructions, 1300 // or if they are SPLAT, 1301 // or if they are not consecutive, 1302 // or if profitable to vectorize loads or extractelements, early return 1303 // the current cost. 1304 auto *I1 = dyn_cast<Instruction>(LHS); 1305 auto *I2 = dyn_cast<Instruction>(RHS); 1306 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 || 1307 ShallowScoreAtThisLevel == VLOperands::ScoreFail || 1308 (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) || 1309 (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) || 1310 (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) && 1311 ShallowScoreAtThisLevel)) 1312 return ShallowScoreAtThisLevel; 1313 assert(I1 && I2 && "Should have early exited."); 1314 1315 // Contains the I2 operand indexes that got matched with I1 operands. 1316 SmallSet<unsigned, 4> Op2Used; 1317 1318 // Recursion towards the operands of I1 and I2. We are trying all possible 1319 // operand pairs, and keeping track of the best score. 1320 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands(); 1321 OpIdx1 != NumOperands1; ++OpIdx1) { 1322 // Try to pair op1I with the best operand of I2. 1323 int MaxTmpScore = 0; 1324 unsigned MaxOpIdx2 = 0; 1325 bool FoundBest = false; 1326 // If I2 is commutative try all combinations. 1327 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1; 1328 unsigned ToIdx = isCommutative(I2) 1329 ? I2->getNumOperands() 1330 : std::min(I2->getNumOperands(), OpIdx1 + 1); 1331 assert(FromIdx <= ToIdx && "Bad index"); 1332 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) { 1333 // Skip operands already paired with OpIdx1. 1334 if (Op2Used.count(OpIdx2)) 1335 continue; 1336 // Recursively calculate the cost at each level 1337 int TmpScore = 1338 getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2), 1339 CurrLevel + 1, MaxLevel, None); 1340 // Look for the best score. 1341 if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) { 1342 MaxTmpScore = TmpScore; 1343 MaxOpIdx2 = OpIdx2; 1344 FoundBest = true; 1345 } 1346 } 1347 if (FoundBest) { 1348 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it. 1349 Op2Used.insert(MaxOpIdx2); 1350 ShallowScoreAtThisLevel += MaxTmpScore; 1351 } 1352 } 1353 return ShallowScoreAtThisLevel; 1354 } 1355 1356 /// Score scaling factor for fully compatible instructions but with 1357 /// different number of external uses. Allows better selection of the 1358 /// instructions with less external uses. 1359 static const int ScoreScaleFactor = 10; 1360 1361 /// \Returns the look-ahead score, which tells us how much the sub-trees 1362 /// rooted at \p LHS and \p RHS match, the more they match the higher the 1363 /// score. This helps break ties in an informed way when we cannot decide on 1364 /// the order of the operands by just considering the immediate 1365 /// predecessors. 1366 int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps, 1367 int Lane, unsigned OpIdx, unsigned Idx, 1368 bool &IsUsed) { 1369 int Score = 1370 getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps); 1371 if (Score) { 1372 int SplatScore = getSplatScore(Lane, OpIdx, Idx); 1373 if (Score <= -SplatScore) { 1374 // Set the minimum score for splat-like sequence to avoid setting 1375 // failed state. 1376 Score = 1; 1377 } else { 1378 Score += SplatScore; 1379 // Scale score to see the difference between different operands 1380 // and similar operands but all vectorized/not all vectorized 1381 // uses. It does not affect actual selection of the best 1382 // compatible operand in general, just allows to select the 1383 // operand with all vectorized uses. 1384 Score *= ScoreScaleFactor; 1385 Score += getExternalUseScore(Lane, OpIdx, Idx); 1386 IsUsed = true; 1387 } 1388 } 1389 return Score; 1390 } 1391 1392 /// Best defined scores per lanes between the passes. Used to choose the 1393 /// best operand (with the highest score) between the passes. 1394 /// The key - {Operand Index, Lane}. 1395 /// The value - the best score between the passes for the lane and the 1396 /// operand. 1397 SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8> 1398 BestScoresPerLanes; 1399 1400 // Search all operands in Ops[*][Lane] for the one that matches best 1401 // Ops[OpIdx][LastLane] and return its opreand index. 1402 // If no good match can be found, return None. 1403 Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane, 1404 ArrayRef<ReorderingMode> ReorderingModes, 1405 ArrayRef<Value *> MainAltOps) { 1406 unsigned NumOperands = getNumOperands(); 1407 1408 // The operand of the previous lane at OpIdx. 1409 Value *OpLastLane = getData(OpIdx, LastLane).V; 1410 1411 // Our strategy mode for OpIdx. 1412 ReorderingMode RMode = ReorderingModes[OpIdx]; 1413 if (RMode == ReorderingMode::Failed) 1414 return None; 1415 1416 // The linearized opcode of the operand at OpIdx, Lane. 1417 bool OpIdxAPO = getData(OpIdx, Lane).APO; 1418 1419 // The best operand index and its score. 1420 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we 1421 // are using the score to differentiate between the two. 1422 struct BestOpData { 1423 Optional<unsigned> Idx = None; 1424 unsigned Score = 0; 1425 } BestOp; 1426 BestOp.Score = 1427 BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0) 1428 .first->second; 1429 1430 // Track if the operand must be marked as used. If the operand is set to 1431 // Score 1 explicitly (because of non power-of-2 unique scalars, we may 1432 // want to reestimate the operands again on the following iterations). 1433 bool IsUsed = 1434 RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant; 1435 // Iterate through all unused operands and look for the best. 1436 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) { 1437 // Get the operand at Idx and Lane. 1438 OperandData &OpData = getData(Idx, Lane); 1439 Value *Op = OpData.V; 1440 bool OpAPO = OpData.APO; 1441 1442 // Skip already selected operands. 1443 if (OpData.IsUsed) 1444 continue; 1445 1446 // Skip if we are trying to move the operand to a position with a 1447 // different opcode in the linearized tree form. This would break the 1448 // semantics. 1449 if (OpAPO != OpIdxAPO) 1450 continue; 1451 1452 // Look for an operand that matches the current mode. 1453 switch (RMode) { 1454 case ReorderingMode::Load: 1455 case ReorderingMode::Constant: 1456 case ReorderingMode::Opcode: { 1457 bool LeftToRight = Lane > LastLane; 1458 Value *OpLeft = (LeftToRight) ? OpLastLane : Op; 1459 Value *OpRight = (LeftToRight) ? Op : OpLastLane; 1460 int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane, 1461 OpIdx, Idx, IsUsed); 1462 if (Score > static_cast<int>(BestOp.Score)) { 1463 BestOp.Idx = Idx; 1464 BestOp.Score = Score; 1465 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score; 1466 } 1467 break; 1468 } 1469 case ReorderingMode::Splat: 1470 if (Op == OpLastLane) 1471 BestOp.Idx = Idx; 1472 break; 1473 case ReorderingMode::Failed: 1474 llvm_unreachable("Not expected Failed reordering mode."); 1475 } 1476 } 1477 1478 if (BestOp.Idx) { 1479 getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed; 1480 return BestOp.Idx; 1481 } 1482 // If we could not find a good match return None. 1483 return None; 1484 } 1485 1486 /// Helper for reorderOperandVecs. 1487 /// \returns the lane that we should start reordering from. This is the one 1488 /// which has the least number of operands that can freely move about or 1489 /// less profitable because it already has the most optimal set of operands. 1490 unsigned getBestLaneToStartReordering() const { 1491 unsigned Min = UINT_MAX; 1492 unsigned SameOpNumber = 0; 1493 // std::pair<unsigned, unsigned> is used to implement a simple voting 1494 // algorithm and choose the lane with the least number of operands that 1495 // can freely move about or less profitable because it already has the 1496 // most optimal set of operands. The first unsigned is a counter for 1497 // voting, the second unsigned is the counter of lanes with instructions 1498 // with same/alternate opcodes and same parent basic block. 1499 MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap; 1500 // Try to be closer to the original results, if we have multiple lanes 1501 // with same cost. If 2 lanes have the same cost, use the one with the 1502 // lowest index. 1503 for (int I = getNumLanes(); I > 0; --I) { 1504 unsigned Lane = I - 1; 1505 OperandsOrderData NumFreeOpsHash = 1506 getMaxNumOperandsThatCanBeReordered(Lane); 1507 // Compare the number of operands that can move and choose the one with 1508 // the least number. 1509 if (NumFreeOpsHash.NumOfAPOs < Min) { 1510 Min = NumFreeOpsHash.NumOfAPOs; 1511 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1512 HashMap.clear(); 1513 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1514 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1515 NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) { 1516 // Select the most optimal lane in terms of number of operands that 1517 // should be moved around. 1518 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1519 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1520 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1521 NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) { 1522 auto It = HashMap.find(NumFreeOpsHash.Hash); 1523 if (It == HashMap.end()) 1524 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1525 else 1526 ++It->second.first; 1527 } 1528 } 1529 // Select the lane with the minimum counter. 1530 unsigned BestLane = 0; 1531 unsigned CntMin = UINT_MAX; 1532 for (const auto &Data : reverse(HashMap)) { 1533 if (Data.second.first < CntMin) { 1534 CntMin = Data.second.first; 1535 BestLane = Data.second.second; 1536 } 1537 } 1538 return BestLane; 1539 } 1540 1541 /// Data structure that helps to reorder operands. 1542 struct OperandsOrderData { 1543 /// The best number of operands with the same APOs, which can be 1544 /// reordered. 1545 unsigned NumOfAPOs = UINT_MAX; 1546 /// Number of operands with the same/alternate instruction opcode and 1547 /// parent. 1548 unsigned NumOpsWithSameOpcodeParent = 0; 1549 /// Hash for the actual operands ordering. 1550 /// Used to count operands, actually their position id and opcode 1551 /// value. It is used in the voting mechanism to find the lane with the 1552 /// least number of operands that can freely move about or less profitable 1553 /// because it already has the most optimal set of operands. Can be 1554 /// replaced with SmallVector<unsigned> instead but hash code is faster 1555 /// and requires less memory. 1556 unsigned Hash = 0; 1557 }; 1558 /// \returns the maximum number of operands that are allowed to be reordered 1559 /// for \p Lane and the number of compatible instructions(with the same 1560 /// parent/opcode). This is used as a heuristic for selecting the first lane 1561 /// to start operand reordering. 1562 OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const { 1563 unsigned CntTrue = 0; 1564 unsigned NumOperands = getNumOperands(); 1565 // Operands with the same APO can be reordered. We therefore need to count 1566 // how many of them we have for each APO, like this: Cnt[APO] = x. 1567 // Since we only have two APOs, namely true and false, we can avoid using 1568 // a map. Instead we can simply count the number of operands that 1569 // correspond to one of them (in this case the 'true' APO), and calculate 1570 // the other by subtracting it from the total number of operands. 1571 // Operands with the same instruction opcode and parent are more 1572 // profitable since we don't need to move them in many cases, with a high 1573 // probability such lane already can be vectorized effectively. 1574 bool AllUndefs = true; 1575 unsigned NumOpsWithSameOpcodeParent = 0; 1576 Instruction *OpcodeI = nullptr; 1577 BasicBlock *Parent = nullptr; 1578 unsigned Hash = 0; 1579 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1580 const OperandData &OpData = getData(OpIdx, Lane); 1581 if (OpData.APO) 1582 ++CntTrue; 1583 // Use Boyer-Moore majority voting for finding the majority opcode and 1584 // the number of times it occurs. 1585 if (auto *I = dyn_cast<Instruction>(OpData.V)) { 1586 if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() || 1587 I->getParent() != Parent) { 1588 if (NumOpsWithSameOpcodeParent == 0) { 1589 NumOpsWithSameOpcodeParent = 1; 1590 OpcodeI = I; 1591 Parent = I->getParent(); 1592 } else { 1593 --NumOpsWithSameOpcodeParent; 1594 } 1595 } else { 1596 ++NumOpsWithSameOpcodeParent; 1597 } 1598 } 1599 Hash = hash_combine( 1600 Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1))); 1601 AllUndefs = AllUndefs && isa<UndefValue>(OpData.V); 1602 } 1603 if (AllUndefs) 1604 return {}; 1605 OperandsOrderData Data; 1606 Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue); 1607 Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent; 1608 Data.Hash = Hash; 1609 return Data; 1610 } 1611 1612 /// Go through the instructions in VL and append their operands. 1613 void appendOperandsOfVL(ArrayRef<Value *> VL) { 1614 assert(!VL.empty() && "Bad VL"); 1615 assert((empty() || VL.size() == getNumLanes()) && 1616 "Expected same number of lanes"); 1617 assert(isa<Instruction>(VL[0]) && "Expected instruction"); 1618 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands(); 1619 OpsVec.resize(NumOperands); 1620 unsigned NumLanes = VL.size(); 1621 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1622 OpsVec[OpIdx].resize(NumLanes); 1623 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1624 assert(isa<Instruction>(VL[Lane]) && "Expected instruction"); 1625 // Our tree has just 3 nodes: the root and two operands. 1626 // It is therefore trivial to get the APO. We only need to check the 1627 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or 1628 // RHS operand. The LHS operand of both add and sub is never attached 1629 // to an inversese operation in the linearized form, therefore its APO 1630 // is false. The RHS is true only if VL[Lane] is an inverse operation. 1631 1632 // Since operand reordering is performed on groups of commutative 1633 // operations or alternating sequences (e.g., +, -), we can safely 1634 // tell the inverse operations by checking commutativity. 1635 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane])); 1636 bool APO = (OpIdx == 0) ? false : IsInverseOperation; 1637 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx), 1638 APO, false}; 1639 } 1640 } 1641 } 1642 1643 /// \returns the number of operands. 1644 unsigned getNumOperands() const { return OpsVec.size(); } 1645 1646 /// \returns the number of lanes. 1647 unsigned getNumLanes() const { return OpsVec[0].size(); } 1648 1649 /// \returns the operand value at \p OpIdx and \p Lane. 1650 Value *getValue(unsigned OpIdx, unsigned Lane) const { 1651 return getData(OpIdx, Lane).V; 1652 } 1653 1654 /// \returns true if the data structure is empty. 1655 bool empty() const { return OpsVec.empty(); } 1656 1657 /// Clears the data. 1658 void clear() { OpsVec.clear(); } 1659 1660 /// \Returns true if there are enough operands identical to \p Op to fill 1661 /// the whole vector. 1662 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow. 1663 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) { 1664 bool OpAPO = getData(OpIdx, Lane).APO; 1665 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) { 1666 if (Ln == Lane) 1667 continue; 1668 // This is set to true if we found a candidate for broadcast at Lane. 1669 bool FoundCandidate = false; 1670 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) { 1671 OperandData &Data = getData(OpI, Ln); 1672 if (Data.APO != OpAPO || Data.IsUsed) 1673 continue; 1674 if (Data.V == Op) { 1675 FoundCandidate = true; 1676 Data.IsUsed = true; 1677 break; 1678 } 1679 } 1680 if (!FoundCandidate) 1681 return false; 1682 } 1683 return true; 1684 } 1685 1686 public: 1687 /// Initialize with all the operands of the instruction vector \p RootVL. 1688 VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL, 1689 ScalarEvolution &SE, const BoUpSLP &R) 1690 : DL(DL), SE(SE), R(R) { 1691 // Append all the operands of RootVL. 1692 appendOperandsOfVL(RootVL); 1693 } 1694 1695 /// \Returns a value vector with the operands across all lanes for the 1696 /// opearnd at \p OpIdx. 1697 ValueList getVL(unsigned OpIdx) const { 1698 ValueList OpVL(OpsVec[OpIdx].size()); 1699 assert(OpsVec[OpIdx].size() == getNumLanes() && 1700 "Expected same num of lanes across all operands"); 1701 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane) 1702 OpVL[Lane] = OpsVec[OpIdx][Lane].V; 1703 return OpVL; 1704 } 1705 1706 // Performs operand reordering for 2 or more operands. 1707 // The original operands are in OrigOps[OpIdx][Lane]. 1708 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'. 1709 void reorder() { 1710 unsigned NumOperands = getNumOperands(); 1711 unsigned NumLanes = getNumLanes(); 1712 // Each operand has its own mode. We are using this mode to help us select 1713 // the instructions for each lane, so that they match best with the ones 1714 // we have selected so far. 1715 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands); 1716 1717 // This is a greedy single-pass algorithm. We are going over each lane 1718 // once and deciding on the best order right away with no back-tracking. 1719 // However, in order to increase its effectiveness, we start with the lane 1720 // that has operands that can move the least. For example, given the 1721 // following lanes: 1722 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd 1723 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st 1724 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd 1725 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th 1726 // we will start at Lane 1, since the operands of the subtraction cannot 1727 // be reordered. Then we will visit the rest of the lanes in a circular 1728 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3. 1729 1730 // Find the first lane that we will start our search from. 1731 unsigned FirstLane = getBestLaneToStartReordering(); 1732 1733 // Initialize the modes. 1734 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1735 Value *OpLane0 = getValue(OpIdx, FirstLane); 1736 // Keep track if we have instructions with all the same opcode on one 1737 // side. 1738 if (isa<LoadInst>(OpLane0)) 1739 ReorderingModes[OpIdx] = ReorderingMode::Load; 1740 else if (isa<Instruction>(OpLane0)) { 1741 // Check if OpLane0 should be broadcast. 1742 if (shouldBroadcast(OpLane0, OpIdx, FirstLane)) 1743 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1744 else 1745 ReorderingModes[OpIdx] = ReorderingMode::Opcode; 1746 } 1747 else if (isa<Constant>(OpLane0)) 1748 ReorderingModes[OpIdx] = ReorderingMode::Constant; 1749 else if (isa<Argument>(OpLane0)) 1750 // Our best hope is a Splat. It may save some cost in some cases. 1751 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1752 else 1753 // NOTE: This should be unreachable. 1754 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1755 } 1756 1757 // Check that we don't have same operands. No need to reorder if operands 1758 // are just perfect diamond or shuffled diamond match. Do not do it only 1759 // for possible broadcasts or non-power of 2 number of scalars (just for 1760 // now). 1761 auto &&SkipReordering = [this]() { 1762 SmallPtrSet<Value *, 4> UniqueValues; 1763 ArrayRef<OperandData> Op0 = OpsVec.front(); 1764 for (const OperandData &Data : Op0) 1765 UniqueValues.insert(Data.V); 1766 for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) { 1767 if (any_of(Op, [&UniqueValues](const OperandData &Data) { 1768 return !UniqueValues.contains(Data.V); 1769 })) 1770 return false; 1771 } 1772 // TODO: Check if we can remove a check for non-power-2 number of 1773 // scalars after full support of non-power-2 vectorization. 1774 return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size()); 1775 }; 1776 1777 // If the initial strategy fails for any of the operand indexes, then we 1778 // perform reordering again in a second pass. This helps avoid assigning 1779 // high priority to the failed strategy, and should improve reordering for 1780 // the non-failed operand indexes. 1781 for (int Pass = 0; Pass != 2; ++Pass) { 1782 // Check if no need to reorder operands since they're are perfect or 1783 // shuffled diamond match. 1784 // Need to to do it to avoid extra external use cost counting for 1785 // shuffled matches, which may cause regressions. 1786 if (SkipReordering()) 1787 break; 1788 // Skip the second pass if the first pass did not fail. 1789 bool StrategyFailed = false; 1790 // Mark all operand data as free to use. 1791 clearUsed(); 1792 // We keep the original operand order for the FirstLane, so reorder the 1793 // rest of the lanes. We are visiting the nodes in a circular fashion, 1794 // using FirstLane as the center point and increasing the radius 1795 // distance. 1796 SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands); 1797 for (unsigned I = 0; I < NumOperands; ++I) 1798 MainAltOps[I].push_back(getData(I, FirstLane).V); 1799 1800 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) { 1801 // Visit the lane on the right and then the lane on the left. 1802 for (int Direction : {+1, -1}) { 1803 int Lane = FirstLane + Direction * Distance; 1804 if (Lane < 0 || Lane >= (int)NumLanes) 1805 continue; 1806 int LastLane = Lane - Direction; 1807 assert(LastLane >= 0 && LastLane < (int)NumLanes && 1808 "Out of bounds"); 1809 // Look for a good match for each operand. 1810 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1811 // Search for the operand that matches SortedOps[OpIdx][Lane-1]. 1812 Optional<unsigned> BestIdx = getBestOperand( 1813 OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]); 1814 // By not selecting a value, we allow the operands that follow to 1815 // select a better matching value. We will get a non-null value in 1816 // the next run of getBestOperand(). 1817 if (BestIdx) { 1818 // Swap the current operand with the one returned by 1819 // getBestOperand(). 1820 swap(OpIdx, BestIdx.getValue(), Lane); 1821 } else { 1822 // We failed to find a best operand, set mode to 'Failed'. 1823 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1824 // Enable the second pass. 1825 StrategyFailed = true; 1826 } 1827 // Try to get the alternate opcode and follow it during analysis. 1828 if (MainAltOps[OpIdx].size() != 2) { 1829 OperandData &AltOp = getData(OpIdx, Lane); 1830 InstructionsState OpS = 1831 getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}); 1832 if (OpS.getOpcode() && OpS.isAltShuffle()) 1833 MainAltOps[OpIdx].push_back(AltOp.V); 1834 } 1835 } 1836 } 1837 } 1838 // Skip second pass if the strategy did not fail. 1839 if (!StrategyFailed) 1840 break; 1841 } 1842 } 1843 1844 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1845 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) { 1846 switch (RMode) { 1847 case ReorderingMode::Load: 1848 return "Load"; 1849 case ReorderingMode::Opcode: 1850 return "Opcode"; 1851 case ReorderingMode::Constant: 1852 return "Constant"; 1853 case ReorderingMode::Splat: 1854 return "Splat"; 1855 case ReorderingMode::Failed: 1856 return "Failed"; 1857 } 1858 llvm_unreachable("Unimplemented Reordering Type"); 1859 } 1860 1861 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode, 1862 raw_ostream &OS) { 1863 return OS << getModeStr(RMode); 1864 } 1865 1866 /// Debug print. 1867 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) { 1868 printMode(RMode, dbgs()); 1869 } 1870 1871 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) { 1872 return printMode(RMode, OS); 1873 } 1874 1875 LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const { 1876 const unsigned Indent = 2; 1877 unsigned Cnt = 0; 1878 for (const OperandDataVec &OpDataVec : OpsVec) { 1879 OS << "Operand " << Cnt++ << "\n"; 1880 for (const OperandData &OpData : OpDataVec) { 1881 OS.indent(Indent) << "{"; 1882 if (Value *V = OpData.V) 1883 OS << *V; 1884 else 1885 OS << "null"; 1886 OS << ", APO:" << OpData.APO << "}\n"; 1887 } 1888 OS << "\n"; 1889 } 1890 return OS; 1891 } 1892 1893 /// Debug print. 1894 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 1895 #endif 1896 }; 1897 1898 /// Checks if the instruction is marked for deletion. 1899 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); } 1900 1901 /// Marks values operands for later deletion by replacing them with Undefs. 1902 void eraseInstructions(ArrayRef<Value *> AV); 1903 1904 ~BoUpSLP(); 1905 1906 private: 1907 /// Checks if all users of \p I are the part of the vectorization tree. 1908 bool areAllUsersVectorized(Instruction *I, 1909 ArrayRef<Value *> VectorizedVals) const; 1910 1911 /// \returns the cost of the vectorizable entry. 1912 InstructionCost getEntryCost(const TreeEntry *E, 1913 ArrayRef<Value *> VectorizedVals); 1914 1915 /// This is the recursive part of buildTree. 1916 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, 1917 const EdgeInfo &EI); 1918 1919 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can 1920 /// be vectorized to use the original vector (or aggregate "bitcast" to a 1921 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise 1922 /// returns false, setting \p CurrentOrder to either an empty vector or a 1923 /// non-identity permutation that allows to reuse extract instructions. 1924 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 1925 SmallVectorImpl<unsigned> &CurrentOrder) const; 1926 1927 /// Vectorize a single entry in the tree. 1928 Value *vectorizeTree(TreeEntry *E); 1929 1930 /// Vectorize a single entry in the tree, starting in \p VL. 1931 Value *vectorizeTree(ArrayRef<Value *> VL); 1932 1933 /// \returns the scalarization cost for this type. Scalarization in this 1934 /// context means the creation of vectors from a group of scalars. If \p 1935 /// NeedToShuffle is true, need to add a cost of reshuffling some of the 1936 /// vector elements. 1937 InstructionCost getGatherCost(FixedVectorType *Ty, 1938 const APInt &ShuffledIndices, 1939 bool NeedToShuffle) const; 1940 1941 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous 1942 /// tree entries. 1943 /// \returns ShuffleKind, if gathered values can be represented as shuffles of 1944 /// previous tree entries. \p Mask is filled with the shuffle mask. 1945 Optional<TargetTransformInfo::ShuffleKind> 1946 isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 1947 SmallVectorImpl<const TreeEntry *> &Entries); 1948 1949 /// \returns the scalarization cost for this list of values. Assuming that 1950 /// this subtree gets vectorized, we may need to extract the values from the 1951 /// roots. This method calculates the cost of extracting the values. 1952 InstructionCost getGatherCost(ArrayRef<Value *> VL) const; 1953 1954 /// Set the Builder insert point to one after the last instruction in 1955 /// the bundle 1956 void setInsertPointAfterBundle(const TreeEntry *E); 1957 1958 /// \returns a vector from a collection of scalars in \p VL. 1959 Value *gather(ArrayRef<Value *> VL); 1960 1961 /// \returns whether the VectorizableTree is fully vectorizable and will 1962 /// be beneficial even the tree height is tiny. 1963 bool isFullyVectorizableTinyTree(bool ForReduction) const; 1964 1965 /// Reorder commutative or alt operands to get better probability of 1966 /// generating vectorized code. 1967 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 1968 SmallVectorImpl<Value *> &Left, 1969 SmallVectorImpl<Value *> &Right, 1970 const DataLayout &DL, 1971 ScalarEvolution &SE, 1972 const BoUpSLP &R); 1973 struct TreeEntry { 1974 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>; 1975 TreeEntry(VecTreeTy &Container) : Container(Container) {} 1976 1977 /// \returns true if the scalars in VL are equal to this entry. 1978 bool isSame(ArrayRef<Value *> VL) const { 1979 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) { 1980 if (Mask.size() != VL.size() && VL.size() == Scalars.size()) 1981 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 1982 return VL.size() == Mask.size() && 1983 std::equal(VL.begin(), VL.end(), Mask.begin(), 1984 [Scalars](Value *V, int Idx) { 1985 return (isa<UndefValue>(V) && 1986 Idx == UndefMaskElem) || 1987 (Idx != UndefMaskElem && V == Scalars[Idx]); 1988 }); 1989 }; 1990 if (!ReorderIndices.empty()) { 1991 // TODO: implement matching if the nodes are just reordered, still can 1992 // treat the vector as the same if the list of scalars matches VL 1993 // directly, without reordering. 1994 SmallVector<int> Mask; 1995 inversePermutation(ReorderIndices, Mask); 1996 if (VL.size() == Scalars.size()) 1997 return IsSame(Scalars, Mask); 1998 if (VL.size() == ReuseShuffleIndices.size()) { 1999 ::addMask(Mask, ReuseShuffleIndices); 2000 return IsSame(Scalars, Mask); 2001 } 2002 return false; 2003 } 2004 return IsSame(Scalars, ReuseShuffleIndices); 2005 } 2006 2007 /// \returns true if current entry has same operands as \p TE. 2008 bool hasEqualOperands(const TreeEntry &TE) const { 2009 if (TE.getNumOperands() != getNumOperands()) 2010 return false; 2011 SmallBitVector Used(getNumOperands()); 2012 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 2013 unsigned PrevCount = Used.count(); 2014 for (unsigned K = 0; K < E; ++K) { 2015 if (Used.test(K)) 2016 continue; 2017 if (getOperand(K) == TE.getOperand(I)) { 2018 Used.set(K); 2019 break; 2020 } 2021 } 2022 // Check if we actually found the matching operand. 2023 if (PrevCount == Used.count()) 2024 return false; 2025 } 2026 return true; 2027 } 2028 2029 /// \return Final vectorization factor for the node. Defined by the total 2030 /// number of vectorized scalars, including those, used several times in the 2031 /// entry and counted in the \a ReuseShuffleIndices, if any. 2032 unsigned getVectorFactor() const { 2033 if (!ReuseShuffleIndices.empty()) 2034 return ReuseShuffleIndices.size(); 2035 return Scalars.size(); 2036 }; 2037 2038 /// A vector of scalars. 2039 ValueList Scalars; 2040 2041 /// The Scalars are vectorized into this value. It is initialized to Null. 2042 Value *VectorizedValue = nullptr; 2043 2044 /// Do we need to gather this sequence or vectorize it 2045 /// (either with vector instruction or with scatter/gather 2046 /// intrinsics for store/load)? 2047 enum EntryState { Vectorize, ScatterVectorize, NeedToGather }; 2048 EntryState State; 2049 2050 /// Does this sequence require some shuffling? 2051 SmallVector<int, 4> ReuseShuffleIndices; 2052 2053 /// Does this entry require reordering? 2054 SmallVector<unsigned, 4> ReorderIndices; 2055 2056 /// Points back to the VectorizableTree. 2057 /// 2058 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has 2059 /// to be a pointer and needs to be able to initialize the child iterator. 2060 /// Thus we need a reference back to the container to translate the indices 2061 /// to entries. 2062 VecTreeTy &Container; 2063 2064 /// The TreeEntry index containing the user of this entry. We can actually 2065 /// have multiple users so the data structure is not truly a tree. 2066 SmallVector<EdgeInfo, 1> UserTreeIndices; 2067 2068 /// The index of this treeEntry in VectorizableTree. 2069 int Idx = -1; 2070 2071 private: 2072 /// The operands of each instruction in each lane Operands[op_index][lane]. 2073 /// Note: This helps avoid the replication of the code that performs the 2074 /// reordering of operands during buildTree_rec() and vectorizeTree(). 2075 SmallVector<ValueList, 2> Operands; 2076 2077 /// The main/alternate instruction. 2078 Instruction *MainOp = nullptr; 2079 Instruction *AltOp = nullptr; 2080 2081 public: 2082 /// Set this bundle's \p OpIdx'th operand to \p OpVL. 2083 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) { 2084 if (Operands.size() < OpIdx + 1) 2085 Operands.resize(OpIdx + 1); 2086 assert(Operands[OpIdx].empty() && "Already resized?"); 2087 assert(OpVL.size() <= Scalars.size() && 2088 "Number of operands is greater than the number of scalars."); 2089 Operands[OpIdx].resize(OpVL.size()); 2090 copy(OpVL, Operands[OpIdx].begin()); 2091 } 2092 2093 /// Set the operands of this bundle in their original order. 2094 void setOperandsInOrder() { 2095 assert(Operands.empty() && "Already initialized?"); 2096 auto *I0 = cast<Instruction>(Scalars[0]); 2097 Operands.resize(I0->getNumOperands()); 2098 unsigned NumLanes = Scalars.size(); 2099 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands(); 2100 OpIdx != NumOperands; ++OpIdx) { 2101 Operands[OpIdx].resize(NumLanes); 2102 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 2103 auto *I = cast<Instruction>(Scalars[Lane]); 2104 assert(I->getNumOperands() == NumOperands && 2105 "Expected same number of operands"); 2106 Operands[OpIdx][Lane] = I->getOperand(OpIdx); 2107 } 2108 } 2109 } 2110 2111 /// Reorders operands of the node to the given mask \p Mask. 2112 void reorderOperands(ArrayRef<int> Mask) { 2113 for (ValueList &Operand : Operands) 2114 reorderScalars(Operand, Mask); 2115 } 2116 2117 /// \returns the \p OpIdx operand of this TreeEntry. 2118 ValueList &getOperand(unsigned OpIdx) { 2119 assert(OpIdx < Operands.size() && "Off bounds"); 2120 return Operands[OpIdx]; 2121 } 2122 2123 /// \returns the \p OpIdx operand of this TreeEntry. 2124 ArrayRef<Value *> getOperand(unsigned OpIdx) const { 2125 assert(OpIdx < Operands.size() && "Off bounds"); 2126 return Operands[OpIdx]; 2127 } 2128 2129 /// \returns the number of operands. 2130 unsigned getNumOperands() const { return Operands.size(); } 2131 2132 /// \return the single \p OpIdx operand. 2133 Value *getSingleOperand(unsigned OpIdx) const { 2134 assert(OpIdx < Operands.size() && "Off bounds"); 2135 assert(!Operands[OpIdx].empty() && "No operand available"); 2136 return Operands[OpIdx][0]; 2137 } 2138 2139 /// Some of the instructions in the list have alternate opcodes. 2140 bool isAltShuffle() const { return MainOp != AltOp; } 2141 2142 bool isOpcodeOrAlt(Instruction *I) const { 2143 unsigned CheckedOpcode = I->getOpcode(); 2144 return (getOpcode() == CheckedOpcode || 2145 getAltOpcode() == CheckedOpcode); 2146 } 2147 2148 /// Chooses the correct key for scheduling data. If \p Op has the same (or 2149 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is 2150 /// \p OpValue. 2151 Value *isOneOf(Value *Op) const { 2152 auto *I = dyn_cast<Instruction>(Op); 2153 if (I && isOpcodeOrAlt(I)) 2154 return Op; 2155 return MainOp; 2156 } 2157 2158 void setOperations(const InstructionsState &S) { 2159 MainOp = S.MainOp; 2160 AltOp = S.AltOp; 2161 } 2162 2163 Instruction *getMainOp() const { 2164 return MainOp; 2165 } 2166 2167 Instruction *getAltOp() const { 2168 return AltOp; 2169 } 2170 2171 /// The main/alternate opcodes for the list of instructions. 2172 unsigned getOpcode() const { 2173 return MainOp ? MainOp->getOpcode() : 0; 2174 } 2175 2176 unsigned getAltOpcode() const { 2177 return AltOp ? AltOp->getOpcode() : 0; 2178 } 2179 2180 /// When ReuseReorderShuffleIndices is empty it just returns position of \p 2181 /// V within vector of Scalars. Otherwise, try to remap on its reuse index. 2182 int findLaneForValue(Value *V) const { 2183 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V)); 2184 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2185 if (!ReorderIndices.empty()) 2186 FoundLane = ReorderIndices[FoundLane]; 2187 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2188 if (!ReuseShuffleIndices.empty()) { 2189 FoundLane = std::distance(ReuseShuffleIndices.begin(), 2190 find(ReuseShuffleIndices, FoundLane)); 2191 } 2192 return FoundLane; 2193 } 2194 2195 #ifndef NDEBUG 2196 /// Debug printer. 2197 LLVM_DUMP_METHOD void dump() const { 2198 dbgs() << Idx << ".\n"; 2199 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) { 2200 dbgs() << "Operand " << OpI << ":\n"; 2201 for (const Value *V : Operands[OpI]) 2202 dbgs().indent(2) << *V << "\n"; 2203 } 2204 dbgs() << "Scalars: \n"; 2205 for (Value *V : Scalars) 2206 dbgs().indent(2) << *V << "\n"; 2207 dbgs() << "State: "; 2208 switch (State) { 2209 case Vectorize: 2210 dbgs() << "Vectorize\n"; 2211 break; 2212 case ScatterVectorize: 2213 dbgs() << "ScatterVectorize\n"; 2214 break; 2215 case NeedToGather: 2216 dbgs() << "NeedToGather\n"; 2217 break; 2218 } 2219 dbgs() << "MainOp: "; 2220 if (MainOp) 2221 dbgs() << *MainOp << "\n"; 2222 else 2223 dbgs() << "NULL\n"; 2224 dbgs() << "AltOp: "; 2225 if (AltOp) 2226 dbgs() << *AltOp << "\n"; 2227 else 2228 dbgs() << "NULL\n"; 2229 dbgs() << "VectorizedValue: "; 2230 if (VectorizedValue) 2231 dbgs() << *VectorizedValue << "\n"; 2232 else 2233 dbgs() << "NULL\n"; 2234 dbgs() << "ReuseShuffleIndices: "; 2235 if (ReuseShuffleIndices.empty()) 2236 dbgs() << "Empty"; 2237 else 2238 for (int ReuseIdx : ReuseShuffleIndices) 2239 dbgs() << ReuseIdx << ", "; 2240 dbgs() << "\n"; 2241 dbgs() << "ReorderIndices: "; 2242 for (unsigned ReorderIdx : ReorderIndices) 2243 dbgs() << ReorderIdx << ", "; 2244 dbgs() << "\n"; 2245 dbgs() << "UserTreeIndices: "; 2246 for (const auto &EInfo : UserTreeIndices) 2247 dbgs() << EInfo << ", "; 2248 dbgs() << "\n"; 2249 } 2250 #endif 2251 }; 2252 2253 #ifndef NDEBUG 2254 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost, 2255 InstructionCost VecCost, 2256 InstructionCost ScalarCost) const { 2257 dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump(); 2258 dbgs() << "SLP: Costs:\n"; 2259 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n"; 2260 dbgs() << "SLP: VectorCost = " << VecCost << "\n"; 2261 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n"; 2262 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " << 2263 ReuseShuffleCost + VecCost - ScalarCost << "\n"; 2264 } 2265 #endif 2266 2267 /// Create a new VectorizableTree entry. 2268 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle, 2269 const InstructionsState &S, 2270 const EdgeInfo &UserTreeIdx, 2271 ArrayRef<int> ReuseShuffleIndices = None, 2272 ArrayRef<unsigned> ReorderIndices = None) { 2273 TreeEntry::EntryState EntryState = 2274 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather; 2275 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx, 2276 ReuseShuffleIndices, ReorderIndices); 2277 } 2278 2279 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, 2280 TreeEntry::EntryState EntryState, 2281 Optional<ScheduleData *> Bundle, 2282 const InstructionsState &S, 2283 const EdgeInfo &UserTreeIdx, 2284 ArrayRef<int> ReuseShuffleIndices = None, 2285 ArrayRef<unsigned> ReorderIndices = None) { 2286 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) || 2287 (Bundle && EntryState != TreeEntry::NeedToGather)) && 2288 "Need to vectorize gather entry?"); 2289 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree)); 2290 TreeEntry *Last = VectorizableTree.back().get(); 2291 Last->Idx = VectorizableTree.size() - 1; 2292 Last->State = EntryState; 2293 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), 2294 ReuseShuffleIndices.end()); 2295 if (ReorderIndices.empty()) { 2296 Last->Scalars.assign(VL.begin(), VL.end()); 2297 Last->setOperations(S); 2298 } else { 2299 // Reorder scalars and build final mask. 2300 Last->Scalars.assign(VL.size(), nullptr); 2301 transform(ReorderIndices, Last->Scalars.begin(), 2302 [VL](unsigned Idx) -> Value * { 2303 if (Idx >= VL.size()) 2304 return UndefValue::get(VL.front()->getType()); 2305 return VL[Idx]; 2306 }); 2307 InstructionsState S = getSameOpcode(Last->Scalars); 2308 Last->setOperations(S); 2309 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end()); 2310 } 2311 if (Last->State != TreeEntry::NeedToGather) { 2312 for (Value *V : VL) { 2313 assert(!getTreeEntry(V) && "Scalar already in tree!"); 2314 ScalarToTreeEntry[V] = Last; 2315 } 2316 // Update the scheduler bundle to point to this TreeEntry. 2317 unsigned Lane = 0; 2318 for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember; 2319 BundleMember = BundleMember->NextInBundle) { 2320 BundleMember->TE = Last; 2321 BundleMember->Lane = Lane; 2322 ++Lane; 2323 } 2324 assert((!Bundle.getValue() || Lane == VL.size()) && 2325 "Bundle and VL out of sync"); 2326 } else { 2327 MustGather.insert(VL.begin(), VL.end()); 2328 } 2329 2330 if (UserTreeIdx.UserTE) 2331 Last->UserTreeIndices.push_back(UserTreeIdx); 2332 2333 return Last; 2334 } 2335 2336 /// -- Vectorization State -- 2337 /// Holds all of the tree entries. 2338 TreeEntry::VecTreeTy VectorizableTree; 2339 2340 #ifndef NDEBUG 2341 /// Debug printer. 2342 LLVM_DUMP_METHOD void dumpVectorizableTree() const { 2343 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) { 2344 VectorizableTree[Id]->dump(); 2345 dbgs() << "\n"; 2346 } 2347 } 2348 #endif 2349 2350 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); } 2351 2352 const TreeEntry *getTreeEntry(Value *V) const { 2353 return ScalarToTreeEntry.lookup(V); 2354 } 2355 2356 /// Maps a specific scalar to its tree entry. 2357 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry; 2358 2359 /// Maps a value to the proposed vectorizable size. 2360 SmallDenseMap<Value *, unsigned> InstrElementSize; 2361 2362 /// A list of scalars that we found that we need to keep as scalars. 2363 ValueSet MustGather; 2364 2365 /// This POD struct describes one external user in the vectorized tree. 2366 struct ExternalUser { 2367 ExternalUser(Value *S, llvm::User *U, int L) 2368 : Scalar(S), User(U), Lane(L) {} 2369 2370 // Which scalar in our function. 2371 Value *Scalar; 2372 2373 // Which user that uses the scalar. 2374 llvm::User *User; 2375 2376 // Which lane does the scalar belong to. 2377 int Lane; 2378 }; 2379 using UserList = SmallVector<ExternalUser, 16>; 2380 2381 /// Checks if two instructions may access the same memory. 2382 /// 2383 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it 2384 /// is invariant in the calling loop. 2385 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, 2386 Instruction *Inst2) { 2387 // First check if the result is already in the cache. 2388 AliasCacheKey key = std::make_pair(Inst1, Inst2); 2389 Optional<bool> &result = AliasCache[key]; 2390 if (result.hasValue()) { 2391 return result.getValue(); 2392 } 2393 bool aliased = true; 2394 if (Loc1.Ptr && isSimple(Inst1)) 2395 aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1)); 2396 // Store the result in the cache. 2397 result = aliased; 2398 return aliased; 2399 } 2400 2401 using AliasCacheKey = std::pair<Instruction *, Instruction *>; 2402 2403 /// Cache for alias results. 2404 /// TODO: consider moving this to the AliasAnalysis itself. 2405 DenseMap<AliasCacheKey, Optional<bool>> AliasCache; 2406 2407 /// Removes an instruction from its block and eventually deletes it. 2408 /// It's like Instruction::eraseFromParent() except that the actual deletion 2409 /// is delayed until BoUpSLP is destructed. 2410 /// This is required to ensure that there are no incorrect collisions in the 2411 /// AliasCache, which can happen if a new instruction is allocated at the 2412 /// same address as a previously deleted instruction. 2413 void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) { 2414 auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first; 2415 It->getSecond() = It->getSecond() && ReplaceOpsWithUndef; 2416 } 2417 2418 /// Temporary store for deleted instructions. Instructions will be deleted 2419 /// eventually when the BoUpSLP is destructed. 2420 DenseMap<Instruction *, bool> DeletedInstructions; 2421 2422 /// A list of values that need to extracted out of the tree. 2423 /// This list holds pairs of (Internal Scalar : External User). External User 2424 /// can be nullptr, it means that this Internal Scalar will be used later, 2425 /// after vectorization. 2426 UserList ExternalUses; 2427 2428 /// Values used only by @llvm.assume calls. 2429 SmallPtrSet<const Value *, 32> EphValues; 2430 2431 /// Holds all of the instructions that we gathered. 2432 SetVector<Instruction *> GatherShuffleSeq; 2433 2434 /// A list of blocks that we are going to CSE. 2435 SetVector<BasicBlock *> CSEBlocks; 2436 2437 /// Contains all scheduling relevant data for an instruction. 2438 /// A ScheduleData either represents a single instruction or a member of an 2439 /// instruction bundle (= a group of instructions which is combined into a 2440 /// vector instruction). 2441 struct ScheduleData { 2442 // The initial value for the dependency counters. It means that the 2443 // dependencies are not calculated yet. 2444 enum { InvalidDeps = -1 }; 2445 2446 ScheduleData() = default; 2447 2448 void init(int BlockSchedulingRegionID, Value *OpVal) { 2449 FirstInBundle = this; 2450 NextInBundle = nullptr; 2451 NextLoadStore = nullptr; 2452 IsScheduled = false; 2453 SchedulingRegionID = BlockSchedulingRegionID; 2454 clearDependencies(); 2455 OpValue = OpVal; 2456 TE = nullptr; 2457 Lane = -1; 2458 } 2459 2460 /// Verify basic self consistency properties 2461 void verify() { 2462 if (hasValidDependencies()) { 2463 assert(UnscheduledDeps <= Dependencies && "invariant"); 2464 } else { 2465 assert(UnscheduledDeps == Dependencies && "invariant"); 2466 } 2467 2468 if (IsScheduled) { 2469 assert(isSchedulingEntity() && 2470 "unexpected scheduled state"); 2471 for (const ScheduleData *BundleMember = this; BundleMember; 2472 BundleMember = BundleMember->NextInBundle) { 2473 assert(BundleMember->hasValidDependencies() && 2474 BundleMember->UnscheduledDeps == 0 && 2475 "unexpected scheduled state"); 2476 assert((BundleMember == this || !BundleMember->IsScheduled) && 2477 "only bundle is marked scheduled"); 2478 } 2479 } 2480 } 2481 2482 /// Returns true if the dependency information has been calculated. 2483 /// Note that depenendency validity can vary between instructions within 2484 /// a single bundle. 2485 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 2486 2487 /// Returns true for single instructions and for bundle representatives 2488 /// (= the head of a bundle). 2489 bool isSchedulingEntity() const { return FirstInBundle == this; } 2490 2491 /// Returns true if it represents an instruction bundle and not only a 2492 /// single instruction. 2493 bool isPartOfBundle() const { 2494 return NextInBundle != nullptr || FirstInBundle != this; 2495 } 2496 2497 /// Returns true if it is ready for scheduling, i.e. it has no more 2498 /// unscheduled depending instructions/bundles. 2499 bool isReady() const { 2500 assert(isSchedulingEntity() && 2501 "can't consider non-scheduling entity for ready list"); 2502 return unscheduledDepsInBundle() == 0 && !IsScheduled; 2503 } 2504 2505 /// Modifies the number of unscheduled dependencies for this instruction, 2506 /// and returns the number of remaining dependencies for the containing 2507 /// bundle. 2508 int incrementUnscheduledDeps(int Incr) { 2509 assert(hasValidDependencies() && 2510 "increment of unscheduled deps would be meaningless"); 2511 UnscheduledDeps += Incr; 2512 return FirstInBundle->unscheduledDepsInBundle(); 2513 } 2514 2515 /// Sets the number of unscheduled dependencies to the number of 2516 /// dependencies. 2517 void resetUnscheduledDeps() { 2518 UnscheduledDeps = Dependencies; 2519 } 2520 2521 /// Clears all dependency information. 2522 void clearDependencies() { 2523 Dependencies = InvalidDeps; 2524 resetUnscheduledDeps(); 2525 MemoryDependencies.clear(); 2526 } 2527 2528 int unscheduledDepsInBundle() const { 2529 assert(isSchedulingEntity() && "only meaningful on the bundle"); 2530 int Sum = 0; 2531 for (const ScheduleData *BundleMember = this; BundleMember; 2532 BundleMember = BundleMember->NextInBundle) { 2533 if (BundleMember->UnscheduledDeps == InvalidDeps) 2534 return InvalidDeps; 2535 Sum += BundleMember->UnscheduledDeps; 2536 } 2537 return Sum; 2538 } 2539 2540 void dump(raw_ostream &os) const { 2541 if (!isSchedulingEntity()) { 2542 os << "/ " << *Inst; 2543 } else if (NextInBundle) { 2544 os << '[' << *Inst; 2545 ScheduleData *SD = NextInBundle; 2546 while (SD) { 2547 os << ';' << *SD->Inst; 2548 SD = SD->NextInBundle; 2549 } 2550 os << ']'; 2551 } else { 2552 os << *Inst; 2553 } 2554 } 2555 2556 Instruction *Inst = nullptr; 2557 2558 /// Points to the head in an instruction bundle (and always to this for 2559 /// single instructions). 2560 ScheduleData *FirstInBundle = nullptr; 2561 2562 /// Single linked list of all instructions in a bundle. Null if it is a 2563 /// single instruction. 2564 ScheduleData *NextInBundle = nullptr; 2565 2566 /// Single linked list of all memory instructions (e.g. load, store, call) 2567 /// in the block - until the end of the scheduling region. 2568 ScheduleData *NextLoadStore = nullptr; 2569 2570 /// The dependent memory instructions. 2571 /// This list is derived on demand in calculateDependencies(). 2572 SmallVector<ScheduleData *, 4> MemoryDependencies; 2573 2574 /// This ScheduleData is in the current scheduling region if this matches 2575 /// the current SchedulingRegionID of BlockScheduling. 2576 int SchedulingRegionID = 0; 2577 2578 /// Used for getting a "good" final ordering of instructions. 2579 int SchedulingPriority = 0; 2580 2581 /// The number of dependencies. Constitutes of the number of users of the 2582 /// instruction plus the number of dependent memory instructions (if any). 2583 /// This value is calculated on demand. 2584 /// If InvalidDeps, the number of dependencies is not calculated yet. 2585 int Dependencies = InvalidDeps; 2586 2587 /// The number of dependencies minus the number of dependencies of scheduled 2588 /// instructions. As soon as this is zero, the instruction/bundle gets ready 2589 /// for scheduling. 2590 /// Note that this is negative as long as Dependencies is not calculated. 2591 int UnscheduledDeps = InvalidDeps; 2592 2593 /// True if this instruction is scheduled (or considered as scheduled in the 2594 /// dry-run). 2595 bool IsScheduled = false; 2596 2597 /// Opcode of the current instruction in the schedule data. 2598 Value *OpValue = nullptr; 2599 2600 /// The TreeEntry that this instruction corresponds to. 2601 TreeEntry *TE = nullptr; 2602 2603 /// The lane of this node in the TreeEntry. 2604 int Lane = -1; 2605 }; 2606 2607 #ifndef NDEBUG 2608 friend inline raw_ostream &operator<<(raw_ostream &os, 2609 const BoUpSLP::ScheduleData &SD) { 2610 SD.dump(os); 2611 return os; 2612 } 2613 #endif 2614 2615 friend struct GraphTraits<BoUpSLP *>; 2616 friend struct DOTGraphTraits<BoUpSLP *>; 2617 2618 /// Contains all scheduling data for a basic block. 2619 struct BlockScheduling { 2620 BlockScheduling(BasicBlock *BB) 2621 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} 2622 2623 void clear() { 2624 ReadyInsts.clear(); 2625 ScheduleStart = nullptr; 2626 ScheduleEnd = nullptr; 2627 FirstLoadStoreInRegion = nullptr; 2628 LastLoadStoreInRegion = nullptr; 2629 2630 // Reduce the maximum schedule region size by the size of the 2631 // previous scheduling run. 2632 ScheduleRegionSizeLimit -= ScheduleRegionSize; 2633 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 2634 ScheduleRegionSizeLimit = MinScheduleRegionSize; 2635 ScheduleRegionSize = 0; 2636 2637 // Make a new scheduling region, i.e. all existing ScheduleData is not 2638 // in the new region yet. 2639 ++SchedulingRegionID; 2640 } 2641 2642 ScheduleData *getScheduleData(Value *V) { 2643 ScheduleData *SD = ScheduleDataMap[V]; 2644 if (SD && isInSchedulingRegion(SD)) 2645 return SD; 2646 return nullptr; 2647 } 2648 2649 ScheduleData *getScheduleData(Value *V, Value *Key) { 2650 if (V == Key) 2651 return getScheduleData(V); 2652 auto I = ExtraScheduleDataMap.find(V); 2653 if (I != ExtraScheduleDataMap.end()) { 2654 ScheduleData *SD = I->second[Key]; 2655 if (SD && isInSchedulingRegion(SD)) 2656 return SD; 2657 } 2658 return nullptr; 2659 } 2660 2661 bool isInSchedulingRegion(ScheduleData *SD) const { 2662 return SD->SchedulingRegionID == SchedulingRegionID; 2663 } 2664 2665 /// Marks an instruction as scheduled and puts all dependent ready 2666 /// instructions into the ready-list. 2667 template <typename ReadyListType> 2668 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 2669 SD->IsScheduled = true; 2670 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 2671 2672 for (ScheduleData *BundleMember = SD; BundleMember; 2673 BundleMember = BundleMember->NextInBundle) { 2674 if (BundleMember->Inst != BundleMember->OpValue) 2675 continue; 2676 2677 // Handle the def-use chain dependencies. 2678 2679 // Decrement the unscheduled counter and insert to ready list if ready. 2680 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { 2681 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { 2682 if (OpDef && OpDef->hasValidDependencies() && 2683 OpDef->incrementUnscheduledDeps(-1) == 0) { 2684 // There are no more unscheduled dependencies after 2685 // decrementing, so we can put the dependent instruction 2686 // into the ready list. 2687 ScheduleData *DepBundle = OpDef->FirstInBundle; 2688 assert(!DepBundle->IsScheduled && 2689 "already scheduled bundle gets ready"); 2690 ReadyList.insert(DepBundle); 2691 LLVM_DEBUG(dbgs() 2692 << "SLP: gets ready (def): " << *DepBundle << "\n"); 2693 } 2694 }); 2695 }; 2696 2697 // If BundleMember is a vector bundle, its operands may have been 2698 // reordered during buildTree(). We therefore need to get its operands 2699 // through the TreeEntry. 2700 if (TreeEntry *TE = BundleMember->TE) { 2701 int Lane = BundleMember->Lane; 2702 assert(Lane >= 0 && "Lane not set"); 2703 2704 // Since vectorization tree is being built recursively this assertion 2705 // ensures that the tree entry has all operands set before reaching 2706 // this code. Couple of exceptions known at the moment are extracts 2707 // where their second (immediate) operand is not added. Since 2708 // immediates do not affect scheduler behavior this is considered 2709 // okay. 2710 auto *In = TE->getMainOp(); 2711 assert(In && 2712 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) || 2713 In->getNumOperands() == TE->getNumOperands()) && 2714 "Missed TreeEntry operands?"); 2715 (void)In; // fake use to avoid build failure when assertions disabled 2716 2717 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); 2718 OpIdx != NumOperands; ++OpIdx) 2719 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) 2720 DecrUnsched(I); 2721 } else { 2722 // If BundleMember is a stand-alone instruction, no operand reordering 2723 // has taken place, so we directly access its operands. 2724 for (Use &U : BundleMember->Inst->operands()) 2725 if (auto *I = dyn_cast<Instruction>(U.get())) 2726 DecrUnsched(I); 2727 } 2728 // Handle the memory dependencies. 2729 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 2730 if (MemoryDepSD->hasValidDependencies() && 2731 MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 2732 // There are no more unscheduled dependencies after decrementing, 2733 // so we can put the dependent instruction into the ready list. 2734 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 2735 assert(!DepBundle->IsScheduled && 2736 "already scheduled bundle gets ready"); 2737 ReadyList.insert(DepBundle); 2738 LLVM_DEBUG(dbgs() 2739 << "SLP: gets ready (mem): " << *DepBundle << "\n"); 2740 } 2741 } 2742 } 2743 } 2744 2745 /// Verify basic self consistency properties of the data structure. 2746 void verify() { 2747 if (!ScheduleStart) 2748 return; 2749 2750 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() && 2751 ScheduleStart->comesBefore(ScheduleEnd) && 2752 "Not a valid scheduling region?"); 2753 2754 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2755 auto *SD = getScheduleData(I); 2756 assert(SD && "primary scheduledata must exist in window"); 2757 assert(isInSchedulingRegion(SD) && 2758 "primary schedule data not in window?"); 2759 (void)SD; 2760 doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); }); 2761 } 2762 2763 for (auto *SD : ReadyInsts) { 2764 assert(SD->isSchedulingEntity() && SD->isReady() && 2765 "item in ready list not ready?"); 2766 (void)SD; 2767 } 2768 } 2769 2770 void doForAllOpcodes(Value *V, 2771 function_ref<void(ScheduleData *SD)> Action) { 2772 if (ScheduleData *SD = getScheduleData(V)) 2773 Action(SD); 2774 auto I = ExtraScheduleDataMap.find(V); 2775 if (I != ExtraScheduleDataMap.end()) 2776 for (auto &P : I->second) 2777 if (isInSchedulingRegion(P.second)) 2778 Action(P.second); 2779 } 2780 2781 /// Put all instructions into the ReadyList which are ready for scheduling. 2782 template <typename ReadyListType> 2783 void initialFillReadyList(ReadyListType &ReadyList) { 2784 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2785 doForAllOpcodes(I, [&](ScheduleData *SD) { 2786 if (SD->isSchedulingEntity() && SD->hasValidDependencies() && 2787 SD->isReady()) { 2788 ReadyList.insert(SD); 2789 LLVM_DEBUG(dbgs() 2790 << "SLP: initially in ready list: " << *SD << "\n"); 2791 } 2792 }); 2793 } 2794 } 2795 2796 /// Build a bundle from the ScheduleData nodes corresponding to the 2797 /// scalar instruction for each lane. 2798 ScheduleData *buildBundle(ArrayRef<Value *> VL); 2799 2800 /// Checks if a bundle of instructions can be scheduled, i.e. has no 2801 /// cyclic dependencies. This is only a dry-run, no instructions are 2802 /// actually moved at this stage. 2803 /// \returns the scheduling bundle. The returned Optional value is non-None 2804 /// if \p VL is allowed to be scheduled. 2805 Optional<ScheduleData *> 2806 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 2807 const InstructionsState &S); 2808 2809 /// Un-bundles a group of instructions. 2810 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); 2811 2812 /// Allocates schedule data chunk. 2813 ScheduleData *allocateScheduleDataChunks(); 2814 2815 /// Extends the scheduling region so that V is inside the region. 2816 /// \returns true if the region size is within the limit. 2817 bool extendSchedulingRegion(Value *V, const InstructionsState &S); 2818 2819 /// Initialize the ScheduleData structures for new instructions in the 2820 /// scheduling region. 2821 void initScheduleData(Instruction *FromI, Instruction *ToI, 2822 ScheduleData *PrevLoadStore, 2823 ScheduleData *NextLoadStore); 2824 2825 /// Updates the dependency information of a bundle and of all instructions/ 2826 /// bundles which depend on the original bundle. 2827 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 2828 BoUpSLP *SLP); 2829 2830 /// Sets all instruction in the scheduling region to un-scheduled. 2831 void resetSchedule(); 2832 2833 BasicBlock *BB; 2834 2835 /// Simple memory allocation for ScheduleData. 2836 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 2837 2838 /// The size of a ScheduleData array in ScheduleDataChunks. 2839 int ChunkSize; 2840 2841 /// The allocator position in the current chunk, which is the last entry 2842 /// of ScheduleDataChunks. 2843 int ChunkPos; 2844 2845 /// Attaches ScheduleData to Instruction. 2846 /// Note that the mapping survives during all vectorization iterations, i.e. 2847 /// ScheduleData structures are recycled. 2848 DenseMap<Value *, ScheduleData *> ScheduleDataMap; 2849 2850 /// Attaches ScheduleData to Instruction with the leading key. 2851 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> 2852 ExtraScheduleDataMap; 2853 2854 /// The ready-list for scheduling (only used for the dry-run). 2855 SetVector<ScheduleData *> ReadyInsts; 2856 2857 /// The first instruction of the scheduling region. 2858 Instruction *ScheduleStart = nullptr; 2859 2860 /// The first instruction _after_ the scheduling region. 2861 Instruction *ScheduleEnd = nullptr; 2862 2863 /// The first memory accessing instruction in the scheduling region 2864 /// (can be null). 2865 ScheduleData *FirstLoadStoreInRegion = nullptr; 2866 2867 /// The last memory accessing instruction in the scheduling region 2868 /// (can be null). 2869 ScheduleData *LastLoadStoreInRegion = nullptr; 2870 2871 /// The current size of the scheduling region. 2872 int ScheduleRegionSize = 0; 2873 2874 /// The maximum size allowed for the scheduling region. 2875 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; 2876 2877 /// The ID of the scheduling region. For a new vectorization iteration this 2878 /// is incremented which "removes" all ScheduleData from the region. 2879 /// Make sure that the initial SchedulingRegionID is greater than the 2880 /// initial SchedulingRegionID in ScheduleData (which is 0). 2881 int SchedulingRegionID = 1; 2882 }; 2883 2884 /// Attaches the BlockScheduling structures to basic blocks. 2885 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 2886 2887 /// Performs the "real" scheduling. Done before vectorization is actually 2888 /// performed in a basic block. 2889 void scheduleBlock(BlockScheduling *BS); 2890 2891 /// List of users to ignore during scheduling and that don't need extracting. 2892 ArrayRef<Value *> UserIgnoreList; 2893 2894 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of 2895 /// sorted SmallVectors of unsigned. 2896 struct OrdersTypeDenseMapInfo { 2897 static OrdersType getEmptyKey() { 2898 OrdersType V; 2899 V.push_back(~1U); 2900 return V; 2901 } 2902 2903 static OrdersType getTombstoneKey() { 2904 OrdersType V; 2905 V.push_back(~2U); 2906 return V; 2907 } 2908 2909 static unsigned getHashValue(const OrdersType &V) { 2910 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2911 } 2912 2913 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { 2914 return LHS == RHS; 2915 } 2916 }; 2917 2918 // Analysis and block reference. 2919 Function *F; 2920 ScalarEvolution *SE; 2921 TargetTransformInfo *TTI; 2922 TargetLibraryInfo *TLI; 2923 AAResults *AA; 2924 LoopInfo *LI; 2925 DominatorTree *DT; 2926 AssumptionCache *AC; 2927 DemandedBits *DB; 2928 const DataLayout *DL; 2929 OptimizationRemarkEmitter *ORE; 2930 2931 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 2932 unsigned MinVecRegSize; // Set by cl::opt (default: 128). 2933 2934 /// Instruction builder to construct the vectorized tree. 2935 IRBuilder<> Builder; 2936 2937 /// A map of scalar integer values to the smallest bit width with which they 2938 /// can legally be represented. The values map to (width, signed) pairs, 2939 /// where "width" indicates the minimum bit width and "signed" is True if the 2940 /// value must be signed-extended, rather than zero-extended, back to its 2941 /// original width. 2942 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; 2943 }; 2944 2945 } // end namespace slpvectorizer 2946 2947 template <> struct GraphTraits<BoUpSLP *> { 2948 using TreeEntry = BoUpSLP::TreeEntry; 2949 2950 /// NodeRef has to be a pointer per the GraphWriter. 2951 using NodeRef = TreeEntry *; 2952 2953 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; 2954 2955 /// Add the VectorizableTree to the index iterator to be able to return 2956 /// TreeEntry pointers. 2957 struct ChildIteratorType 2958 : public iterator_adaptor_base< 2959 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { 2960 ContainerTy &VectorizableTree; 2961 2962 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, 2963 ContainerTy &VT) 2964 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} 2965 2966 NodeRef operator*() { return I->UserTE; } 2967 }; 2968 2969 static NodeRef getEntryNode(BoUpSLP &R) { 2970 return R.VectorizableTree[0].get(); 2971 } 2972 2973 static ChildIteratorType child_begin(NodeRef N) { 2974 return {N->UserTreeIndices.begin(), N->Container}; 2975 } 2976 2977 static ChildIteratorType child_end(NodeRef N) { 2978 return {N->UserTreeIndices.end(), N->Container}; 2979 } 2980 2981 /// For the node iterator we just need to turn the TreeEntry iterator into a 2982 /// TreeEntry* iterator so that it dereferences to NodeRef. 2983 class nodes_iterator { 2984 using ItTy = ContainerTy::iterator; 2985 ItTy It; 2986 2987 public: 2988 nodes_iterator(const ItTy &It2) : It(It2) {} 2989 NodeRef operator*() { return It->get(); } 2990 nodes_iterator operator++() { 2991 ++It; 2992 return *this; 2993 } 2994 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } 2995 }; 2996 2997 static nodes_iterator nodes_begin(BoUpSLP *R) { 2998 return nodes_iterator(R->VectorizableTree.begin()); 2999 } 3000 3001 static nodes_iterator nodes_end(BoUpSLP *R) { 3002 return nodes_iterator(R->VectorizableTree.end()); 3003 } 3004 3005 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } 3006 }; 3007 3008 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { 3009 using TreeEntry = BoUpSLP::TreeEntry; 3010 3011 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3012 3013 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { 3014 std::string Str; 3015 raw_string_ostream OS(Str); 3016 if (isSplat(Entry->Scalars)) 3017 OS << "<splat> "; 3018 for (auto V : Entry->Scalars) { 3019 OS << *V; 3020 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) { 3021 return EU.Scalar == V; 3022 })) 3023 OS << " <extract>"; 3024 OS << "\n"; 3025 } 3026 return Str; 3027 } 3028 3029 static std::string getNodeAttributes(const TreeEntry *Entry, 3030 const BoUpSLP *) { 3031 if (Entry->State == TreeEntry::NeedToGather) 3032 return "color=red"; 3033 return ""; 3034 } 3035 }; 3036 3037 } // end namespace llvm 3038 3039 BoUpSLP::~BoUpSLP() { 3040 for (const auto &Pair : DeletedInstructions) { 3041 // Replace operands of ignored instructions with Undefs in case if they were 3042 // marked for deletion. 3043 if (Pair.getSecond()) { 3044 Value *Undef = UndefValue::get(Pair.getFirst()->getType()); 3045 Pair.getFirst()->replaceAllUsesWith(Undef); 3046 } 3047 Pair.getFirst()->dropAllReferences(); 3048 } 3049 for (const auto &Pair : DeletedInstructions) { 3050 assert(Pair.getFirst()->use_empty() && 3051 "trying to erase instruction with users."); 3052 Pair.getFirst()->eraseFromParent(); 3053 } 3054 #ifdef EXPENSIVE_CHECKS 3055 // If we could guarantee that this call is not extremely slow, we could 3056 // remove the ifdef limitation (see PR47712). 3057 assert(!verifyFunction(*F, &dbgs())); 3058 #endif 3059 } 3060 3061 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) { 3062 for (auto *V : AV) { 3063 if (auto *I = dyn_cast<Instruction>(V)) 3064 eraseInstruction(I, /*ReplaceOpsWithUndef=*/true); 3065 }; 3066 } 3067 3068 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses 3069 /// contains original mask for the scalars reused in the node. Procedure 3070 /// transform this mask in accordance with the given \p Mask. 3071 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) { 3072 assert(!Mask.empty() && Reuses.size() == Mask.size() && 3073 "Expected non-empty mask."); 3074 SmallVector<int> Prev(Reuses.begin(), Reuses.end()); 3075 Prev.swap(Reuses); 3076 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 3077 if (Mask[I] != UndefMaskElem) 3078 Reuses[Mask[I]] = Prev[I]; 3079 } 3080 3081 /// Reorders the given \p Order according to the given \p Mask. \p Order - is 3082 /// the original order of the scalars. Procedure transforms the provided order 3083 /// in accordance with the given \p Mask. If the resulting \p Order is just an 3084 /// identity order, \p Order is cleared. 3085 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) { 3086 assert(!Mask.empty() && "Expected non-empty mask."); 3087 SmallVector<int> MaskOrder; 3088 if (Order.empty()) { 3089 MaskOrder.resize(Mask.size()); 3090 std::iota(MaskOrder.begin(), MaskOrder.end(), 0); 3091 } else { 3092 inversePermutation(Order, MaskOrder); 3093 } 3094 reorderReuses(MaskOrder, Mask); 3095 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) { 3096 Order.clear(); 3097 return; 3098 } 3099 Order.assign(Mask.size(), Mask.size()); 3100 for (unsigned I = 0, E = Mask.size(); I < E; ++I) 3101 if (MaskOrder[I] != UndefMaskElem) 3102 Order[MaskOrder[I]] = I; 3103 fixupOrderingIndices(Order); 3104 } 3105 3106 Optional<BoUpSLP::OrdersType> 3107 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) { 3108 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3109 unsigned NumScalars = TE.Scalars.size(); 3110 OrdersType CurrentOrder(NumScalars, NumScalars); 3111 SmallVector<int> Positions; 3112 SmallBitVector UsedPositions(NumScalars); 3113 const TreeEntry *STE = nullptr; 3114 // Try to find all gathered scalars that are gets vectorized in other 3115 // vectorize node. Here we can have only one single tree vector node to 3116 // correctly identify order of the gathered scalars. 3117 for (unsigned I = 0; I < NumScalars; ++I) { 3118 Value *V = TE.Scalars[I]; 3119 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V)) 3120 continue; 3121 if (const auto *LocalSTE = getTreeEntry(V)) { 3122 if (!STE) 3123 STE = LocalSTE; 3124 else if (STE != LocalSTE) 3125 // Take the order only from the single vector node. 3126 return None; 3127 unsigned Lane = 3128 std::distance(STE->Scalars.begin(), find(STE->Scalars, V)); 3129 if (Lane >= NumScalars) 3130 return None; 3131 if (CurrentOrder[Lane] != NumScalars) { 3132 if (Lane != I) 3133 continue; 3134 UsedPositions.reset(CurrentOrder[Lane]); 3135 } 3136 // The partial identity (where only some elements of the gather node are 3137 // in the identity order) is good. 3138 CurrentOrder[Lane] = I; 3139 UsedPositions.set(I); 3140 } 3141 } 3142 // Need to keep the order if we have a vector entry and at least 2 scalars or 3143 // the vectorized entry has just 2 scalars. 3144 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) { 3145 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) { 3146 for (unsigned I = 0; I < NumScalars; ++I) 3147 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars) 3148 return false; 3149 return true; 3150 }; 3151 if (IsIdentityOrder(CurrentOrder)) { 3152 CurrentOrder.clear(); 3153 return CurrentOrder; 3154 } 3155 auto *It = CurrentOrder.begin(); 3156 for (unsigned I = 0; I < NumScalars;) { 3157 if (UsedPositions.test(I)) { 3158 ++I; 3159 continue; 3160 } 3161 if (*It == NumScalars) { 3162 *It = I; 3163 ++I; 3164 } 3165 ++It; 3166 } 3167 return CurrentOrder; 3168 } 3169 return None; 3170 } 3171 3172 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE, 3173 bool TopToBottom) { 3174 // No need to reorder if need to shuffle reuses, still need to shuffle the 3175 // node. 3176 if (!TE.ReuseShuffleIndices.empty()) 3177 return None; 3178 if (TE.State == TreeEntry::Vectorize && 3179 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) || 3180 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) && 3181 !TE.isAltShuffle()) 3182 return TE.ReorderIndices; 3183 if (TE.State == TreeEntry::NeedToGather) { 3184 // TODO: add analysis of other gather nodes with extractelement 3185 // instructions and other values/instructions, not only undefs. 3186 if (((TE.getOpcode() == Instruction::ExtractElement && 3187 !TE.isAltShuffle()) || 3188 (all_of(TE.Scalars, 3189 [](Value *V) { 3190 return isa<UndefValue, ExtractElementInst>(V); 3191 }) && 3192 any_of(TE.Scalars, 3193 [](Value *V) { return isa<ExtractElementInst>(V); }))) && 3194 all_of(TE.Scalars, 3195 [](Value *V) { 3196 auto *EE = dyn_cast<ExtractElementInst>(V); 3197 return !EE || isa<FixedVectorType>(EE->getVectorOperandType()); 3198 }) && 3199 allSameType(TE.Scalars)) { 3200 // Check that gather of extractelements can be represented as 3201 // just a shuffle of a single vector. 3202 OrdersType CurrentOrder; 3203 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder); 3204 if (Reuse || !CurrentOrder.empty()) { 3205 if (!CurrentOrder.empty()) 3206 fixupOrderingIndices(CurrentOrder); 3207 return CurrentOrder; 3208 } 3209 } 3210 if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE)) 3211 return CurrentOrder; 3212 } 3213 return None; 3214 } 3215 3216 void BoUpSLP::reorderTopToBottom() { 3217 // Maps VF to the graph nodes. 3218 DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries; 3219 // ExtractElement gather nodes which can be vectorized and need to handle 3220 // their ordering. 3221 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3222 // Find all reorderable nodes with the given VF. 3223 // Currently the are vectorized stores,loads,extracts + some gathering of 3224 // extracts. 3225 for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders]( 3226 const std::unique_ptr<TreeEntry> &TE) { 3227 if (Optional<OrdersType> CurrentOrder = 3228 getReorderingData(*TE.get(), /*TopToBottom=*/true)) { 3229 // Do not include ordering for nodes used in the alt opcode vectorization, 3230 // better to reorder them during bottom-to-top stage. If follow the order 3231 // here, it causes reordering of the whole graph though actually it is 3232 // profitable just to reorder the subgraph that starts from the alternate 3233 // opcode vectorization node. Such nodes already end-up with the shuffle 3234 // instruction and it is just enough to change this shuffle rather than 3235 // rotate the scalars for the whole graph. 3236 unsigned Cnt = 0; 3237 const TreeEntry *UserTE = TE.get(); 3238 while (UserTE && Cnt < RecursionMaxDepth) { 3239 if (UserTE->UserTreeIndices.size() != 1) 3240 break; 3241 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) { 3242 return EI.UserTE->State == TreeEntry::Vectorize && 3243 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0; 3244 })) 3245 return; 3246 if (UserTE->UserTreeIndices.empty()) 3247 UserTE = nullptr; 3248 else 3249 UserTE = UserTE->UserTreeIndices.back().UserTE; 3250 ++Cnt; 3251 } 3252 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3253 if (TE->State != TreeEntry::Vectorize) 3254 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3255 } 3256 }); 3257 3258 // Reorder the graph nodes according to their vectorization factor. 3259 for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; 3260 VF /= 2) { 3261 auto It = VFToOrderedEntries.find(VF); 3262 if (It == VFToOrderedEntries.end()) 3263 continue; 3264 // Try to find the most profitable order. We just are looking for the most 3265 // used order and reorder scalar elements in the nodes according to this 3266 // mostly used order. 3267 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef(); 3268 // All operands are reordered and used only in this node - propagate the 3269 // most used order to the user node. 3270 MapVector<OrdersType, unsigned, 3271 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3272 OrdersUses; 3273 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3274 for (const TreeEntry *OpTE : OrderedEntries) { 3275 // No need to reorder this nodes, still need to extend and to use shuffle, 3276 // just need to merge reordering shuffle and the reuse shuffle. 3277 if (!OpTE->ReuseShuffleIndices.empty()) 3278 continue; 3279 // Count number of orders uses. 3280 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3281 if (OpTE->State == TreeEntry::NeedToGather) 3282 return GathersToOrders.find(OpTE)->second; 3283 return OpTE->ReorderIndices; 3284 }(); 3285 // Stores actually store the mask, not the order, need to invert. 3286 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3287 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3288 SmallVector<int> Mask; 3289 inversePermutation(Order, Mask); 3290 unsigned E = Order.size(); 3291 OrdersType CurrentOrder(E, E); 3292 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3293 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3294 }); 3295 fixupOrderingIndices(CurrentOrder); 3296 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3297 } else { 3298 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3299 } 3300 } 3301 // Set order of the user node. 3302 if (OrdersUses.empty()) 3303 continue; 3304 // Choose the most used order. 3305 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3306 unsigned Cnt = OrdersUses.front().second; 3307 for (const auto &Pair : drop_begin(OrdersUses)) { 3308 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3309 BestOrder = Pair.first; 3310 Cnt = Pair.second; 3311 } 3312 } 3313 // Set order of the user node. 3314 if (BestOrder.empty()) 3315 continue; 3316 SmallVector<int> Mask; 3317 inversePermutation(BestOrder, Mask); 3318 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3319 unsigned E = BestOrder.size(); 3320 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3321 return I < E ? static_cast<int>(I) : UndefMaskElem; 3322 }); 3323 // Do an actual reordering, if profitable. 3324 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 3325 // Just do the reordering for the nodes with the given VF. 3326 if (TE->Scalars.size() != VF) { 3327 if (TE->ReuseShuffleIndices.size() == VF) { 3328 // Need to reorder the reuses masks of the operands with smaller VF to 3329 // be able to find the match between the graph nodes and scalar 3330 // operands of the given node during vectorization/cost estimation. 3331 assert(all_of(TE->UserTreeIndices, 3332 [VF, &TE](const EdgeInfo &EI) { 3333 return EI.UserTE->Scalars.size() == VF || 3334 EI.UserTE->Scalars.size() == 3335 TE->Scalars.size(); 3336 }) && 3337 "All users must be of VF size."); 3338 // Update ordering of the operands with the smaller VF than the given 3339 // one. 3340 reorderReuses(TE->ReuseShuffleIndices, Mask); 3341 } 3342 continue; 3343 } 3344 if (TE->State == TreeEntry::Vectorize && 3345 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, 3346 InsertElementInst>(TE->getMainOp()) && 3347 !TE->isAltShuffle()) { 3348 // Build correct orders for extract{element,value}, loads and 3349 // stores. 3350 reorderOrder(TE->ReorderIndices, Mask); 3351 if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) 3352 TE->reorderOperands(Mask); 3353 } else { 3354 // Reorder the node and its operands. 3355 TE->reorderOperands(Mask); 3356 assert(TE->ReorderIndices.empty() && 3357 "Expected empty reorder sequence."); 3358 reorderScalars(TE->Scalars, Mask); 3359 } 3360 if (!TE->ReuseShuffleIndices.empty()) { 3361 // Apply reversed order to keep the original ordering of the reused 3362 // elements to avoid extra reorder indices shuffling. 3363 OrdersType CurrentOrder; 3364 reorderOrder(CurrentOrder, MaskOrder); 3365 SmallVector<int> NewReuses; 3366 inversePermutation(CurrentOrder, NewReuses); 3367 addMask(NewReuses, TE->ReuseShuffleIndices); 3368 TE->ReuseShuffleIndices.swap(NewReuses); 3369 } 3370 } 3371 } 3372 } 3373 3374 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { 3375 SetVector<TreeEntry *> OrderedEntries; 3376 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3377 // Find all reorderable leaf nodes with the given VF. 3378 // Currently the are vectorized loads,extracts without alternate operands + 3379 // some gathering of extracts. 3380 SmallVector<TreeEntry *> NonVectorized; 3381 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, 3382 &NonVectorized]( 3383 const std::unique_ptr<TreeEntry> &TE) { 3384 if (TE->State != TreeEntry::Vectorize) 3385 NonVectorized.push_back(TE.get()); 3386 if (Optional<OrdersType> CurrentOrder = 3387 getReorderingData(*TE.get(), /*TopToBottom=*/false)) { 3388 OrderedEntries.insert(TE.get()); 3389 if (TE->State != TreeEntry::Vectorize) 3390 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3391 } 3392 }); 3393 3394 // Checks if the operands of the users are reordarable and have only single 3395 // use. 3396 auto &&CheckOperands = 3397 [this, &NonVectorized](const auto &Data, 3398 SmallVectorImpl<TreeEntry *> &GatherOps) { 3399 for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) { 3400 if (any_of(Data.second, 3401 [I](const std::pair<unsigned, TreeEntry *> &OpData) { 3402 return OpData.first == I && 3403 OpData.second->State == TreeEntry::Vectorize; 3404 })) 3405 continue; 3406 ArrayRef<Value *> VL = Data.first->getOperand(I); 3407 const TreeEntry *TE = nullptr; 3408 const auto *It = find_if(VL, [this, &TE](Value *V) { 3409 TE = getTreeEntry(V); 3410 return TE; 3411 }); 3412 if (It != VL.end() && TE->isSame(VL)) 3413 return false; 3414 TreeEntry *Gather = nullptr; 3415 if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) { 3416 assert(TE->State != TreeEntry::Vectorize && 3417 "Only non-vectorized nodes are expected."); 3418 if (TE->isSame(VL)) { 3419 Gather = TE; 3420 return true; 3421 } 3422 return false; 3423 }) > 1) 3424 return false; 3425 if (Gather) 3426 GatherOps.push_back(Gather); 3427 } 3428 return true; 3429 }; 3430 // 1. Propagate order to the graph nodes, which use only reordered nodes. 3431 // I.e., if the node has operands, that are reordered, try to make at least 3432 // one operand order in the natural order and reorder others + reorder the 3433 // user node itself. 3434 SmallPtrSet<const TreeEntry *, 4> Visited; 3435 while (!OrderedEntries.empty()) { 3436 // 1. Filter out only reordered nodes. 3437 // 2. If the entry has multiple uses - skip it and jump to the next node. 3438 MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; 3439 SmallVector<TreeEntry *> Filtered; 3440 for (TreeEntry *TE : OrderedEntries) { 3441 if (!(TE->State == TreeEntry::Vectorize || 3442 (TE->State == TreeEntry::NeedToGather && 3443 GathersToOrders.count(TE))) || 3444 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3445 !all_of(drop_begin(TE->UserTreeIndices), 3446 [TE](const EdgeInfo &EI) { 3447 return EI.UserTE == TE->UserTreeIndices.front().UserTE; 3448 }) || 3449 !Visited.insert(TE).second) { 3450 Filtered.push_back(TE); 3451 continue; 3452 } 3453 // Build a map between user nodes and their operands order to speedup 3454 // search. The graph currently does not provide this dependency directly. 3455 for (EdgeInfo &EI : TE->UserTreeIndices) { 3456 TreeEntry *UserTE = EI.UserTE; 3457 auto It = Users.find(UserTE); 3458 if (It == Users.end()) 3459 It = Users.insert({UserTE, {}}).first; 3460 It->second.emplace_back(EI.EdgeIdx, TE); 3461 } 3462 } 3463 // Erase filtered entries. 3464 for_each(Filtered, 3465 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); 3466 for (const auto &Data : Users) { 3467 // Check that operands are used only in the User node. 3468 SmallVector<TreeEntry *> GatherOps; 3469 if (!CheckOperands(Data, GatherOps)) { 3470 for_each(Data.second, 3471 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3472 OrderedEntries.remove(Op.second); 3473 }); 3474 continue; 3475 } 3476 // All operands are reordered and used only in this node - propagate the 3477 // most used order to the user node. 3478 MapVector<OrdersType, unsigned, 3479 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3480 OrdersUses; 3481 // Do the analysis for each tree entry only once, otherwise the order of 3482 // the same node my be considered several times, though might be not 3483 // profitable. 3484 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3485 for (const auto &Op : Data.second) { 3486 TreeEntry *OpTE = Op.second; 3487 if (!VisitedOps.insert(OpTE).second) 3488 continue; 3489 if (!OpTE->ReuseShuffleIndices.empty() || 3490 (IgnoreReorder && OpTE == VectorizableTree.front().get())) 3491 continue; 3492 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3493 if (OpTE->State == TreeEntry::NeedToGather) 3494 return GathersToOrders.find(OpTE)->second; 3495 return OpTE->ReorderIndices; 3496 }(); 3497 // Stores actually store the mask, not the order, need to invert. 3498 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3499 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3500 SmallVector<int> Mask; 3501 inversePermutation(Order, Mask); 3502 unsigned E = Order.size(); 3503 OrdersType CurrentOrder(E, E); 3504 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3505 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3506 }); 3507 fixupOrderingIndices(CurrentOrder); 3508 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3509 } else { 3510 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3511 } 3512 OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second += 3513 OpTE->UserTreeIndices.size(); 3514 assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0."); 3515 --OrdersUses[{}]; 3516 } 3517 // If no orders - skip current nodes and jump to the next one, if any. 3518 if (OrdersUses.empty()) { 3519 for_each(Data.second, 3520 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3521 OrderedEntries.remove(Op.second); 3522 }); 3523 continue; 3524 } 3525 // Choose the best order. 3526 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3527 unsigned Cnt = OrdersUses.front().second; 3528 for (const auto &Pair : drop_begin(OrdersUses)) { 3529 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3530 BestOrder = Pair.first; 3531 Cnt = Pair.second; 3532 } 3533 } 3534 // Set order of the user node (reordering of operands and user nodes). 3535 if (BestOrder.empty()) { 3536 for_each(Data.second, 3537 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3538 OrderedEntries.remove(Op.second); 3539 }); 3540 continue; 3541 } 3542 // Erase operands from OrderedEntries list and adjust their orders. 3543 VisitedOps.clear(); 3544 SmallVector<int> Mask; 3545 inversePermutation(BestOrder, Mask); 3546 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3547 unsigned E = BestOrder.size(); 3548 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3549 return I < E ? static_cast<int>(I) : UndefMaskElem; 3550 }); 3551 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { 3552 TreeEntry *TE = Op.second; 3553 OrderedEntries.remove(TE); 3554 if (!VisitedOps.insert(TE).second) 3555 continue; 3556 if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) { 3557 // Just reorder reuses indices. 3558 reorderReuses(TE->ReuseShuffleIndices, Mask); 3559 continue; 3560 } 3561 // Gathers are processed separately. 3562 if (TE->State != TreeEntry::Vectorize) 3563 continue; 3564 assert((BestOrder.size() == TE->ReorderIndices.size() || 3565 TE->ReorderIndices.empty()) && 3566 "Non-matching sizes of user/operand entries."); 3567 reorderOrder(TE->ReorderIndices, Mask); 3568 } 3569 // For gathers just need to reorder its scalars. 3570 for (TreeEntry *Gather : GatherOps) { 3571 assert(Gather->ReorderIndices.empty() && 3572 "Unexpected reordering of gathers."); 3573 if (!Gather->ReuseShuffleIndices.empty()) { 3574 // Just reorder reuses indices. 3575 reorderReuses(Gather->ReuseShuffleIndices, Mask); 3576 continue; 3577 } 3578 reorderScalars(Gather->Scalars, Mask); 3579 OrderedEntries.remove(Gather); 3580 } 3581 // Reorder operands of the user node and set the ordering for the user 3582 // node itself. 3583 if (Data.first->State != TreeEntry::Vectorize || 3584 !isa<ExtractElementInst, ExtractValueInst, LoadInst>( 3585 Data.first->getMainOp()) || 3586 Data.first->isAltShuffle()) 3587 Data.first->reorderOperands(Mask); 3588 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || 3589 Data.first->isAltShuffle()) { 3590 reorderScalars(Data.first->Scalars, Mask); 3591 reorderOrder(Data.first->ReorderIndices, MaskOrder); 3592 if (Data.first->ReuseShuffleIndices.empty() && 3593 !Data.first->ReorderIndices.empty() && 3594 !Data.first->isAltShuffle()) { 3595 // Insert user node to the list to try to sink reordering deeper in 3596 // the graph. 3597 OrderedEntries.insert(Data.first); 3598 } 3599 } else { 3600 reorderOrder(Data.first->ReorderIndices, Mask); 3601 } 3602 } 3603 } 3604 // If the reordering is unnecessary, just remove the reorder. 3605 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && 3606 VectorizableTree.front()->ReuseShuffleIndices.empty()) 3607 VectorizableTree.front()->ReorderIndices.clear(); 3608 } 3609 3610 void BoUpSLP::buildExternalUses( 3611 const ExtraValueToDebugLocsMap &ExternallyUsedValues) { 3612 // Collect the values that we need to extract from the tree. 3613 for (auto &TEPtr : VectorizableTree) { 3614 TreeEntry *Entry = TEPtr.get(); 3615 3616 // No need to handle users of gathered values. 3617 if (Entry->State == TreeEntry::NeedToGather) 3618 continue; 3619 3620 // For each lane: 3621 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 3622 Value *Scalar = Entry->Scalars[Lane]; 3623 int FoundLane = Entry->findLaneForValue(Scalar); 3624 3625 // Check if the scalar is externally used as an extra arg. 3626 auto ExtI = ExternallyUsedValues.find(Scalar); 3627 if (ExtI != ExternallyUsedValues.end()) { 3628 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 3629 << Lane << " from " << *Scalar << ".\n"); 3630 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 3631 } 3632 for (User *U : Scalar->users()) { 3633 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 3634 3635 Instruction *UserInst = dyn_cast<Instruction>(U); 3636 if (!UserInst) 3637 continue; 3638 3639 if (isDeleted(UserInst)) 3640 continue; 3641 3642 // Skip in-tree scalars that become vectors 3643 if (TreeEntry *UseEntry = getTreeEntry(U)) { 3644 Value *UseScalar = UseEntry->Scalars[0]; 3645 // Some in-tree scalars will remain as scalar in vectorized 3646 // instructions. If that is the case, the one in Lane 0 will 3647 // be used. 3648 if (UseScalar != U || 3649 UseEntry->State == TreeEntry::ScatterVectorize || 3650 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 3651 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 3652 << ".\n"); 3653 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 3654 continue; 3655 } 3656 } 3657 3658 // Ignore users in the user ignore list. 3659 if (is_contained(UserIgnoreList, UserInst)) 3660 continue; 3661 3662 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 3663 << Lane << " from " << *Scalar << ".\n"); 3664 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 3665 } 3666 } 3667 } 3668 } 3669 3670 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 3671 ArrayRef<Value *> UserIgnoreLst) { 3672 deleteTree(); 3673 UserIgnoreList = UserIgnoreLst; 3674 if (!allSameType(Roots)) 3675 return; 3676 buildTree_rec(Roots, 0, EdgeInfo()); 3677 } 3678 3679 namespace { 3680 /// Tracks the state we can represent the loads in the given sequence. 3681 enum class LoadsState { Gather, Vectorize, ScatterVectorize }; 3682 } // anonymous namespace 3683 3684 /// Checks if the given array of loads can be represented as a vectorized, 3685 /// scatter or just simple gather. 3686 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0, 3687 const TargetTransformInfo &TTI, 3688 const DataLayout &DL, ScalarEvolution &SE, 3689 SmallVectorImpl<unsigned> &Order, 3690 SmallVectorImpl<Value *> &PointerOps) { 3691 // Check that a vectorized load would load the same memory as a scalar 3692 // load. For example, we don't want to vectorize loads that are smaller 3693 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3694 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3695 // from such a struct, we read/write packed bits disagreeing with the 3696 // unvectorized version. 3697 Type *ScalarTy = VL0->getType(); 3698 3699 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) 3700 return LoadsState::Gather; 3701 3702 // Make sure all loads in the bundle are simple - we can't vectorize 3703 // atomic or volatile loads. 3704 PointerOps.clear(); 3705 PointerOps.resize(VL.size()); 3706 auto *POIter = PointerOps.begin(); 3707 for (Value *V : VL) { 3708 auto *L = cast<LoadInst>(V); 3709 if (!L->isSimple()) 3710 return LoadsState::Gather; 3711 *POIter = L->getPointerOperand(); 3712 ++POIter; 3713 } 3714 3715 Order.clear(); 3716 // Check the order of pointer operands. 3717 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) { 3718 Value *Ptr0; 3719 Value *PtrN; 3720 if (Order.empty()) { 3721 Ptr0 = PointerOps.front(); 3722 PtrN = PointerOps.back(); 3723 } else { 3724 Ptr0 = PointerOps[Order.front()]; 3725 PtrN = PointerOps[Order.back()]; 3726 } 3727 Optional<int> Diff = 3728 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); 3729 // Check that the sorted loads are consecutive. 3730 if (static_cast<unsigned>(*Diff) == VL.size() - 1) 3731 return LoadsState::Vectorize; 3732 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); 3733 for (Value *V : VL) 3734 CommonAlignment = 3735 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 3736 if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()), 3737 CommonAlignment)) 3738 return LoadsState::ScatterVectorize; 3739 } 3740 3741 return LoadsState::Gather; 3742 } 3743 3744 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 3745 const EdgeInfo &UserTreeIdx) { 3746 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 3747 3748 SmallVector<int> ReuseShuffleIndicies; 3749 SmallVector<Value *> UniqueValues; 3750 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, 3751 &UserTreeIdx, 3752 this](const InstructionsState &S) { 3753 // Check that every instruction appears once in this bundle. 3754 DenseMap<Value *, unsigned> UniquePositions; 3755 for (Value *V : VL) { 3756 if (isConstant(V)) { 3757 ReuseShuffleIndicies.emplace_back( 3758 isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size()); 3759 UniqueValues.emplace_back(V); 3760 continue; 3761 } 3762 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 3763 ReuseShuffleIndicies.emplace_back(Res.first->second); 3764 if (Res.second) 3765 UniqueValues.emplace_back(V); 3766 } 3767 size_t NumUniqueScalarValues = UniqueValues.size(); 3768 if (NumUniqueScalarValues == VL.size()) { 3769 ReuseShuffleIndicies.clear(); 3770 } else { 3771 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 3772 if (NumUniqueScalarValues <= 1 || 3773 (UniquePositions.size() == 1 && all_of(UniqueValues, 3774 [](Value *V) { 3775 return isa<UndefValue>(V) || 3776 !isConstant(V); 3777 })) || 3778 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 3779 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 3780 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3781 return false; 3782 } 3783 VL = UniqueValues; 3784 } 3785 return true; 3786 }; 3787 3788 InstructionsState S = getSameOpcode(VL); 3789 if (Depth == RecursionMaxDepth) { 3790 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 3791 if (TryToFindDuplicates(S)) 3792 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3793 ReuseShuffleIndicies); 3794 return; 3795 } 3796 3797 // Don't handle scalable vectors 3798 if (S.getOpcode() == Instruction::ExtractElement && 3799 isa<ScalableVectorType>( 3800 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { 3801 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n"); 3802 if (TryToFindDuplicates(S)) 3803 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3804 ReuseShuffleIndicies); 3805 return; 3806 } 3807 3808 // Don't handle vectors. 3809 if (S.OpValue->getType()->isVectorTy() && 3810 !isa<InsertElementInst>(S.OpValue)) { 3811 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 3812 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3813 return; 3814 } 3815 3816 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 3817 if (SI->getValueOperand()->getType()->isVectorTy()) { 3818 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 3819 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3820 return; 3821 } 3822 3823 // If all of the operands are identical or constant we have a simple solution. 3824 // If we deal with insert/extract instructions, they all must have constant 3825 // indices, otherwise we should gather them, not try to vectorize. 3826 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() || 3827 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) && 3828 !all_of(VL, isVectorLikeInstWithConstOps))) { 3829 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 3830 if (TryToFindDuplicates(S)) 3831 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3832 ReuseShuffleIndicies); 3833 return; 3834 } 3835 3836 // We now know that this is a vector of instructions of the same type from 3837 // the same block. 3838 3839 // Don't vectorize ephemeral values. 3840 for (Value *V : VL) { 3841 if (EphValues.count(V)) { 3842 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3843 << ") is ephemeral.\n"); 3844 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3845 return; 3846 } 3847 } 3848 3849 // Check if this is a duplicate of another entry. 3850 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 3851 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 3852 if (!E->isSame(VL)) { 3853 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 3854 if (TryToFindDuplicates(S)) 3855 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3856 ReuseShuffleIndicies); 3857 return; 3858 } 3859 // Record the reuse of the tree node. FIXME, currently this is only used to 3860 // properly draw the graph rather than for the actual vectorization. 3861 E->UserTreeIndices.push_back(UserTreeIdx); 3862 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 3863 << ".\n"); 3864 return; 3865 } 3866 3867 // Check that none of the instructions in the bundle are already in the tree. 3868 for (Value *V : VL) { 3869 auto *I = dyn_cast<Instruction>(V); 3870 if (!I) 3871 continue; 3872 if (getTreeEntry(I)) { 3873 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3874 << ") is already in tree.\n"); 3875 if (TryToFindDuplicates(S)) 3876 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3877 ReuseShuffleIndicies); 3878 return; 3879 } 3880 } 3881 3882 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 3883 for (Value *V : VL) { 3884 if (is_contained(UserIgnoreList, V)) { 3885 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 3886 if (TryToFindDuplicates(S)) 3887 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3888 ReuseShuffleIndicies); 3889 return; 3890 } 3891 } 3892 3893 // Check that all of the users of the scalars that we want to vectorize are 3894 // schedulable. 3895 auto *VL0 = cast<Instruction>(S.OpValue); 3896 BasicBlock *BB = VL0->getParent(); 3897 3898 if (!DT->isReachableFromEntry(BB)) { 3899 // Don't go into unreachable blocks. They may contain instructions with 3900 // dependency cycles which confuse the final scheduling. 3901 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 3902 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3903 return; 3904 } 3905 3906 // Check that every instruction appears once in this bundle. 3907 if (!TryToFindDuplicates(S)) 3908 return; 3909 3910 auto &BSRef = BlocksSchedules[BB]; 3911 if (!BSRef) 3912 BSRef = std::make_unique<BlockScheduling>(BB); 3913 3914 BlockScheduling &BS = *BSRef.get(); 3915 3916 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 3917 #ifdef EXPENSIVE_CHECKS 3918 // Make sure we didn't break any internal invariants 3919 BS.verify(); 3920 #endif 3921 if (!Bundle) { 3922 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 3923 assert((!BS.getScheduleData(VL0) || 3924 !BS.getScheduleData(VL0)->isPartOfBundle()) && 3925 "tryScheduleBundle should cancelScheduling on failure"); 3926 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3927 ReuseShuffleIndicies); 3928 return; 3929 } 3930 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 3931 3932 unsigned ShuffleOrOp = S.isAltShuffle() ? 3933 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 3934 switch (ShuffleOrOp) { 3935 case Instruction::PHI: { 3936 auto *PH = cast<PHINode>(VL0); 3937 3938 // Check for terminator values (e.g. invoke). 3939 for (Value *V : VL) 3940 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3941 Instruction *Term = dyn_cast<Instruction>( 3942 cast<PHINode>(V)->getIncomingValueForBlock( 3943 PH->getIncomingBlock(I))); 3944 if (Term && Term->isTerminator()) { 3945 LLVM_DEBUG(dbgs() 3946 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 3947 BS.cancelScheduling(VL, VL0); 3948 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3949 ReuseShuffleIndicies); 3950 return; 3951 } 3952 } 3953 3954 TreeEntry *TE = 3955 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 3956 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 3957 3958 // Keeps the reordered operands to avoid code duplication. 3959 SmallVector<ValueList, 2> OperandsVec; 3960 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3961 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { 3962 ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); 3963 TE->setOperand(I, Operands); 3964 OperandsVec.push_back(Operands); 3965 continue; 3966 } 3967 ValueList Operands; 3968 // Prepare the operand vector. 3969 for (Value *V : VL) 3970 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( 3971 PH->getIncomingBlock(I))); 3972 TE->setOperand(I, Operands); 3973 OperandsVec.push_back(Operands); 3974 } 3975 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 3976 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 3977 return; 3978 } 3979 case Instruction::ExtractValue: 3980 case Instruction::ExtractElement: { 3981 OrdersType CurrentOrder; 3982 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 3983 if (Reuse) { 3984 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 3985 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3986 ReuseShuffleIndicies); 3987 // This is a special case, as it does not gather, but at the same time 3988 // we are not extending buildTree_rec() towards the operands. 3989 ValueList Op0; 3990 Op0.assign(VL.size(), VL0->getOperand(0)); 3991 VectorizableTree.back()->setOperand(0, Op0); 3992 return; 3993 } 3994 if (!CurrentOrder.empty()) { 3995 LLVM_DEBUG({ 3996 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 3997 "with order"; 3998 for (unsigned Idx : CurrentOrder) 3999 dbgs() << " " << Idx; 4000 dbgs() << "\n"; 4001 }); 4002 fixupOrderingIndices(CurrentOrder); 4003 // Insert new order with initial value 0, if it does not exist, 4004 // otherwise return the iterator to the existing one. 4005 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4006 ReuseShuffleIndicies, CurrentOrder); 4007 // This is a special case, as it does not gather, but at the same time 4008 // we are not extending buildTree_rec() towards the operands. 4009 ValueList Op0; 4010 Op0.assign(VL.size(), VL0->getOperand(0)); 4011 VectorizableTree.back()->setOperand(0, Op0); 4012 return; 4013 } 4014 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 4015 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4016 ReuseShuffleIndicies); 4017 BS.cancelScheduling(VL, VL0); 4018 return; 4019 } 4020 case Instruction::InsertElement: { 4021 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique"); 4022 4023 // Check that we have a buildvector and not a shuffle of 2 or more 4024 // different vectors. 4025 ValueSet SourceVectors; 4026 for (Value *V : VL) { 4027 SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); 4028 assert(getInsertIndex(V) != None && "Non-constant or undef index?"); 4029 } 4030 4031 if (count_if(VL, [&SourceVectors](Value *V) { 4032 return !SourceVectors.contains(V); 4033 }) >= 2) { 4034 // Found 2nd source vector - cancel. 4035 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with " 4036 "different source vectors.\n"); 4037 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4038 BS.cancelScheduling(VL, VL0); 4039 return; 4040 } 4041 4042 auto OrdCompare = [](const std::pair<int, int> &P1, 4043 const std::pair<int, int> &P2) { 4044 return P1.first > P2.first; 4045 }; 4046 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, 4047 decltype(OrdCompare)> 4048 Indices(OrdCompare); 4049 for (int I = 0, E = VL.size(); I < E; ++I) { 4050 unsigned Idx = *getInsertIndex(VL[I]); 4051 Indices.emplace(Idx, I); 4052 } 4053 OrdersType CurrentOrder(VL.size(), VL.size()); 4054 bool IsIdentity = true; 4055 for (int I = 0, E = VL.size(); I < E; ++I) { 4056 CurrentOrder[Indices.top().second] = I; 4057 IsIdentity &= Indices.top().second == I; 4058 Indices.pop(); 4059 } 4060 if (IsIdentity) 4061 CurrentOrder.clear(); 4062 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4063 None, CurrentOrder); 4064 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n"); 4065 4066 constexpr int NumOps = 2; 4067 ValueList VectorOperands[NumOps]; 4068 for (int I = 0; I < NumOps; ++I) { 4069 for (Value *V : VL) 4070 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); 4071 4072 TE->setOperand(I, VectorOperands[I]); 4073 } 4074 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); 4075 return; 4076 } 4077 case Instruction::Load: { 4078 // Check that a vectorized load would load the same memory as a scalar 4079 // load. For example, we don't want to vectorize loads that are smaller 4080 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 4081 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 4082 // from such a struct, we read/write packed bits disagreeing with the 4083 // unvectorized version. 4084 SmallVector<Value *> PointerOps; 4085 OrdersType CurrentOrder; 4086 TreeEntry *TE = nullptr; 4087 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder, 4088 PointerOps)) { 4089 case LoadsState::Vectorize: 4090 if (CurrentOrder.empty()) { 4091 // Original loads are consecutive and does not require reordering. 4092 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4093 ReuseShuffleIndicies); 4094 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 4095 } else { 4096 fixupOrderingIndices(CurrentOrder); 4097 // Need to reorder. 4098 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4099 ReuseShuffleIndicies, CurrentOrder); 4100 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 4101 } 4102 TE->setOperandsInOrder(); 4103 break; 4104 case LoadsState::ScatterVectorize: 4105 // Vectorizing non-consecutive loads with `llvm.masked.gather`. 4106 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, 4107 UserTreeIdx, ReuseShuffleIndicies); 4108 TE->setOperandsInOrder(); 4109 buildTree_rec(PointerOps, Depth + 1, {TE, 0}); 4110 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n"); 4111 break; 4112 case LoadsState::Gather: 4113 BS.cancelScheduling(VL, VL0); 4114 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4115 ReuseShuffleIndicies); 4116 #ifndef NDEBUG 4117 Type *ScalarTy = VL0->getType(); 4118 if (DL->getTypeSizeInBits(ScalarTy) != 4119 DL->getTypeAllocSizeInBits(ScalarTy)) 4120 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 4121 else if (any_of(VL, [](Value *V) { 4122 return !cast<LoadInst>(V)->isSimple(); 4123 })) 4124 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 4125 else 4126 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 4127 #endif // NDEBUG 4128 break; 4129 } 4130 return; 4131 } 4132 case Instruction::ZExt: 4133 case Instruction::SExt: 4134 case Instruction::FPToUI: 4135 case Instruction::FPToSI: 4136 case Instruction::FPExt: 4137 case Instruction::PtrToInt: 4138 case Instruction::IntToPtr: 4139 case Instruction::SIToFP: 4140 case Instruction::UIToFP: 4141 case Instruction::Trunc: 4142 case Instruction::FPTrunc: 4143 case Instruction::BitCast: { 4144 Type *SrcTy = VL0->getOperand(0)->getType(); 4145 for (Value *V : VL) { 4146 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 4147 if (Ty != SrcTy || !isValidElementType(Ty)) { 4148 BS.cancelScheduling(VL, VL0); 4149 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4150 ReuseShuffleIndicies); 4151 LLVM_DEBUG(dbgs() 4152 << "SLP: Gathering casts with different src types.\n"); 4153 return; 4154 } 4155 } 4156 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4157 ReuseShuffleIndicies); 4158 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 4159 4160 TE->setOperandsInOrder(); 4161 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4162 ValueList Operands; 4163 // Prepare the operand vector. 4164 for (Value *V : VL) 4165 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4166 4167 buildTree_rec(Operands, Depth + 1, {TE, i}); 4168 } 4169 return; 4170 } 4171 case Instruction::ICmp: 4172 case Instruction::FCmp: { 4173 // Check that all of the compares have the same predicate. 4174 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 4175 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 4176 Type *ComparedTy = VL0->getOperand(0)->getType(); 4177 for (Value *V : VL) { 4178 CmpInst *Cmp = cast<CmpInst>(V); 4179 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 4180 Cmp->getOperand(0)->getType() != ComparedTy) { 4181 BS.cancelScheduling(VL, VL0); 4182 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4183 ReuseShuffleIndicies); 4184 LLVM_DEBUG(dbgs() 4185 << "SLP: Gathering cmp with different predicate.\n"); 4186 return; 4187 } 4188 } 4189 4190 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4191 ReuseShuffleIndicies); 4192 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 4193 4194 ValueList Left, Right; 4195 if (cast<CmpInst>(VL0)->isCommutative()) { 4196 // Commutative predicate - collect + sort operands of the instructions 4197 // so that each side is more likely to have the same opcode. 4198 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 4199 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4200 } else { 4201 // Collect operands - commute if it uses the swapped predicate. 4202 for (Value *V : VL) { 4203 auto *Cmp = cast<CmpInst>(V); 4204 Value *LHS = Cmp->getOperand(0); 4205 Value *RHS = Cmp->getOperand(1); 4206 if (Cmp->getPredicate() != P0) 4207 std::swap(LHS, RHS); 4208 Left.push_back(LHS); 4209 Right.push_back(RHS); 4210 } 4211 } 4212 TE->setOperand(0, Left); 4213 TE->setOperand(1, Right); 4214 buildTree_rec(Left, Depth + 1, {TE, 0}); 4215 buildTree_rec(Right, Depth + 1, {TE, 1}); 4216 return; 4217 } 4218 case Instruction::Select: 4219 case Instruction::FNeg: 4220 case Instruction::Add: 4221 case Instruction::FAdd: 4222 case Instruction::Sub: 4223 case Instruction::FSub: 4224 case Instruction::Mul: 4225 case Instruction::FMul: 4226 case Instruction::UDiv: 4227 case Instruction::SDiv: 4228 case Instruction::FDiv: 4229 case Instruction::URem: 4230 case Instruction::SRem: 4231 case Instruction::FRem: 4232 case Instruction::Shl: 4233 case Instruction::LShr: 4234 case Instruction::AShr: 4235 case Instruction::And: 4236 case Instruction::Or: 4237 case Instruction::Xor: { 4238 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4239 ReuseShuffleIndicies); 4240 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 4241 4242 // Sort operands of the instructions so that each side is more likely to 4243 // have the same opcode. 4244 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 4245 ValueList Left, Right; 4246 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4247 TE->setOperand(0, Left); 4248 TE->setOperand(1, Right); 4249 buildTree_rec(Left, Depth + 1, {TE, 0}); 4250 buildTree_rec(Right, Depth + 1, {TE, 1}); 4251 return; 4252 } 4253 4254 TE->setOperandsInOrder(); 4255 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4256 ValueList Operands; 4257 // Prepare the operand vector. 4258 for (Value *V : VL) 4259 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4260 4261 buildTree_rec(Operands, Depth + 1, {TE, i}); 4262 } 4263 return; 4264 } 4265 case Instruction::GetElementPtr: { 4266 // We don't combine GEPs with complicated (nested) indexing. 4267 for (Value *V : VL) { 4268 if (cast<Instruction>(V)->getNumOperands() != 2) { 4269 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 4270 BS.cancelScheduling(VL, VL0); 4271 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4272 ReuseShuffleIndicies); 4273 return; 4274 } 4275 } 4276 4277 // We can't combine several GEPs into one vector if they operate on 4278 // different types. 4279 Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType(); 4280 for (Value *V : VL) { 4281 Type *CurTy = cast<GEPOperator>(V)->getSourceElementType(); 4282 if (Ty0 != CurTy) { 4283 LLVM_DEBUG(dbgs() 4284 << "SLP: not-vectorizable GEP (different types).\n"); 4285 BS.cancelScheduling(VL, VL0); 4286 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4287 ReuseShuffleIndicies); 4288 return; 4289 } 4290 } 4291 4292 // We don't combine GEPs with non-constant indexes. 4293 Type *Ty1 = VL0->getOperand(1)->getType(); 4294 for (Value *V : VL) { 4295 auto Op = cast<Instruction>(V)->getOperand(1); 4296 if (!isa<ConstantInt>(Op) || 4297 (Op->getType() != Ty1 && 4298 Op->getType()->getScalarSizeInBits() > 4299 DL->getIndexSizeInBits( 4300 V->getType()->getPointerAddressSpace()))) { 4301 LLVM_DEBUG(dbgs() 4302 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 4303 BS.cancelScheduling(VL, VL0); 4304 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4305 ReuseShuffleIndicies); 4306 return; 4307 } 4308 } 4309 4310 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4311 ReuseShuffleIndicies); 4312 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 4313 SmallVector<ValueList, 2> Operands(2); 4314 // Prepare the operand vector for pointer operands. 4315 for (Value *V : VL) 4316 Operands.front().push_back( 4317 cast<GetElementPtrInst>(V)->getPointerOperand()); 4318 TE->setOperand(0, Operands.front()); 4319 // Need to cast all indices to the same type before vectorization to 4320 // avoid crash. 4321 // Required to be able to find correct matches between different gather 4322 // nodes and reuse the vectorized values rather than trying to gather them 4323 // again. 4324 int IndexIdx = 1; 4325 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType(); 4326 Type *Ty = all_of(VL, 4327 [VL0Ty, IndexIdx](Value *V) { 4328 return VL0Ty == cast<GetElementPtrInst>(V) 4329 ->getOperand(IndexIdx) 4330 ->getType(); 4331 }) 4332 ? VL0Ty 4333 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 4334 ->getPointerOperandType() 4335 ->getScalarType()); 4336 // Prepare the operand vector. 4337 for (Value *V : VL) { 4338 auto *Op = cast<Instruction>(V)->getOperand(IndexIdx); 4339 auto *CI = cast<ConstantInt>(Op); 4340 Operands.back().push_back(ConstantExpr::getIntegerCast( 4341 CI, Ty, CI->getValue().isSignBitSet())); 4342 } 4343 TE->setOperand(IndexIdx, Operands.back()); 4344 4345 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I) 4346 buildTree_rec(Operands[I], Depth + 1, {TE, I}); 4347 return; 4348 } 4349 case Instruction::Store: { 4350 // Check if the stores are consecutive or if we need to swizzle them. 4351 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 4352 // Avoid types that are padded when being allocated as scalars, while 4353 // being packed together in a vector (such as i1). 4354 if (DL->getTypeSizeInBits(ScalarTy) != 4355 DL->getTypeAllocSizeInBits(ScalarTy)) { 4356 BS.cancelScheduling(VL, VL0); 4357 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4358 ReuseShuffleIndicies); 4359 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n"); 4360 return; 4361 } 4362 // Make sure all stores in the bundle are simple - we can't vectorize 4363 // atomic or volatile stores. 4364 SmallVector<Value *, 4> PointerOps(VL.size()); 4365 ValueList Operands(VL.size()); 4366 auto POIter = PointerOps.begin(); 4367 auto OIter = Operands.begin(); 4368 for (Value *V : VL) { 4369 auto *SI = cast<StoreInst>(V); 4370 if (!SI->isSimple()) { 4371 BS.cancelScheduling(VL, VL0); 4372 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4373 ReuseShuffleIndicies); 4374 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 4375 return; 4376 } 4377 *POIter = SI->getPointerOperand(); 4378 *OIter = SI->getValueOperand(); 4379 ++POIter; 4380 ++OIter; 4381 } 4382 4383 OrdersType CurrentOrder; 4384 // Check the order of pointer operands. 4385 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { 4386 Value *Ptr0; 4387 Value *PtrN; 4388 if (CurrentOrder.empty()) { 4389 Ptr0 = PointerOps.front(); 4390 PtrN = PointerOps.back(); 4391 } else { 4392 Ptr0 = PointerOps[CurrentOrder.front()]; 4393 PtrN = PointerOps[CurrentOrder.back()]; 4394 } 4395 Optional<int> Dist = 4396 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); 4397 // Check that the sorted pointer operands are consecutive. 4398 if (static_cast<unsigned>(*Dist) == VL.size() - 1) { 4399 if (CurrentOrder.empty()) { 4400 // Original stores are consecutive and does not require reordering. 4401 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 4402 UserTreeIdx, ReuseShuffleIndicies); 4403 TE->setOperandsInOrder(); 4404 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4405 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 4406 } else { 4407 fixupOrderingIndices(CurrentOrder); 4408 TreeEntry *TE = 4409 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4410 ReuseShuffleIndicies, CurrentOrder); 4411 TE->setOperandsInOrder(); 4412 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4413 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 4414 } 4415 return; 4416 } 4417 } 4418 4419 BS.cancelScheduling(VL, VL0); 4420 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4421 ReuseShuffleIndicies); 4422 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 4423 return; 4424 } 4425 case Instruction::Call: { 4426 // Check if the calls are all to the same vectorizable intrinsic or 4427 // library function. 4428 CallInst *CI = cast<CallInst>(VL0); 4429 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4430 4431 VFShape Shape = VFShape::get( 4432 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), 4433 false /*HasGlobalPred*/); 4434 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4435 4436 if (!VecFunc && !isTriviallyVectorizable(ID)) { 4437 BS.cancelScheduling(VL, VL0); 4438 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4439 ReuseShuffleIndicies); 4440 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 4441 return; 4442 } 4443 Function *F = CI->getCalledFunction(); 4444 unsigned NumArgs = CI->arg_size(); 4445 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 4446 for (unsigned j = 0; j != NumArgs; ++j) 4447 if (hasVectorInstrinsicScalarOpd(ID, j)) 4448 ScalarArgs[j] = CI->getArgOperand(j); 4449 for (Value *V : VL) { 4450 CallInst *CI2 = dyn_cast<CallInst>(V); 4451 if (!CI2 || CI2->getCalledFunction() != F || 4452 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 4453 (VecFunc && 4454 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || 4455 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 4456 BS.cancelScheduling(VL, VL0); 4457 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4458 ReuseShuffleIndicies); 4459 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 4460 << "\n"); 4461 return; 4462 } 4463 // Some intrinsics have scalar arguments and should be same in order for 4464 // them to be vectorized. 4465 for (unsigned j = 0; j != NumArgs; ++j) { 4466 if (hasVectorInstrinsicScalarOpd(ID, j)) { 4467 Value *A1J = CI2->getArgOperand(j); 4468 if (ScalarArgs[j] != A1J) { 4469 BS.cancelScheduling(VL, VL0); 4470 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4471 ReuseShuffleIndicies); 4472 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 4473 << " argument " << ScalarArgs[j] << "!=" << A1J 4474 << "\n"); 4475 return; 4476 } 4477 } 4478 } 4479 // Verify that the bundle operands are identical between the two calls. 4480 if (CI->hasOperandBundles() && 4481 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 4482 CI->op_begin() + CI->getBundleOperandsEndIndex(), 4483 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 4484 BS.cancelScheduling(VL, VL0); 4485 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4486 ReuseShuffleIndicies); 4487 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 4488 << *CI << "!=" << *V << '\n'); 4489 return; 4490 } 4491 } 4492 4493 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4494 ReuseShuffleIndicies); 4495 TE->setOperandsInOrder(); 4496 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 4497 // For scalar operands no need to to create an entry since no need to 4498 // vectorize it. 4499 if (hasVectorInstrinsicScalarOpd(ID, i)) 4500 continue; 4501 ValueList Operands; 4502 // Prepare the operand vector. 4503 for (Value *V : VL) { 4504 auto *CI2 = cast<CallInst>(V); 4505 Operands.push_back(CI2->getArgOperand(i)); 4506 } 4507 buildTree_rec(Operands, Depth + 1, {TE, i}); 4508 } 4509 return; 4510 } 4511 case Instruction::ShuffleVector: { 4512 // If this is not an alternate sequence of opcode like add-sub 4513 // then do not vectorize this instruction. 4514 if (!S.isAltShuffle()) { 4515 BS.cancelScheduling(VL, VL0); 4516 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4517 ReuseShuffleIndicies); 4518 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 4519 return; 4520 } 4521 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4522 ReuseShuffleIndicies); 4523 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 4524 4525 // Reorder operands if reordering would enable vectorization. 4526 auto *CI = dyn_cast<CmpInst>(VL0); 4527 if (isa<BinaryOperator>(VL0) || CI) { 4528 ValueList Left, Right; 4529 if (!CI || all_of(VL, [](Value *V) { 4530 return cast<CmpInst>(V)->isCommutative(); 4531 })) { 4532 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4533 } else { 4534 CmpInst::Predicate P0 = CI->getPredicate(); 4535 CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate(); 4536 assert(P0 != AltP0 && 4537 "Expected different main/alternate predicates."); 4538 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 4539 Value *BaseOp0 = VL0->getOperand(0); 4540 Value *BaseOp1 = VL0->getOperand(1); 4541 // Collect operands - commute if it uses the swapped predicate or 4542 // alternate operation. 4543 for (Value *V : VL) { 4544 auto *Cmp = cast<CmpInst>(V); 4545 Value *LHS = Cmp->getOperand(0); 4546 Value *RHS = Cmp->getOperand(1); 4547 CmpInst::Predicate CurrentPred = Cmp->getPredicate(); 4548 if (P0 == AltP0Swapped) { 4549 if (CI != Cmp && S.AltOp != Cmp && 4550 ((P0 == CurrentPred && 4551 !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) || 4552 (AltP0 == CurrentPred && 4553 areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))) 4554 std::swap(LHS, RHS); 4555 } else if (P0 != CurrentPred && AltP0 != CurrentPred) { 4556 std::swap(LHS, RHS); 4557 } 4558 Left.push_back(LHS); 4559 Right.push_back(RHS); 4560 } 4561 } 4562 TE->setOperand(0, Left); 4563 TE->setOperand(1, Right); 4564 buildTree_rec(Left, Depth + 1, {TE, 0}); 4565 buildTree_rec(Right, Depth + 1, {TE, 1}); 4566 return; 4567 } 4568 4569 TE->setOperandsInOrder(); 4570 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4571 ValueList Operands; 4572 // Prepare the operand vector. 4573 for (Value *V : VL) 4574 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4575 4576 buildTree_rec(Operands, Depth + 1, {TE, i}); 4577 } 4578 return; 4579 } 4580 default: 4581 BS.cancelScheduling(VL, VL0); 4582 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4583 ReuseShuffleIndicies); 4584 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 4585 return; 4586 } 4587 } 4588 4589 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 4590 unsigned N = 1; 4591 Type *EltTy = T; 4592 4593 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) || 4594 isa<VectorType>(EltTy)) { 4595 if (auto *ST = dyn_cast<StructType>(EltTy)) { 4596 // Check that struct is homogeneous. 4597 for (const auto *Ty : ST->elements()) 4598 if (Ty != *ST->element_begin()) 4599 return 0; 4600 N *= ST->getNumElements(); 4601 EltTy = *ST->element_begin(); 4602 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { 4603 N *= AT->getNumElements(); 4604 EltTy = AT->getElementType(); 4605 } else { 4606 auto *VT = cast<FixedVectorType>(EltTy); 4607 N *= VT->getNumElements(); 4608 EltTy = VT->getElementType(); 4609 } 4610 } 4611 4612 if (!isValidElementType(EltTy)) 4613 return 0; 4614 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); 4615 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 4616 return 0; 4617 return N; 4618 } 4619 4620 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 4621 SmallVectorImpl<unsigned> &CurrentOrder) const { 4622 const auto *It = find_if(VL, [](Value *V) { 4623 return isa<ExtractElementInst, ExtractValueInst>(V); 4624 }); 4625 assert(It != VL.end() && "Expected at least one extract instruction."); 4626 auto *E0 = cast<Instruction>(*It); 4627 assert(all_of(VL, 4628 [](Value *V) { 4629 return isa<UndefValue, ExtractElementInst, ExtractValueInst>( 4630 V); 4631 }) && 4632 "Invalid opcode"); 4633 // Check if all of the extracts come from the same vector and from the 4634 // correct offset. 4635 Value *Vec = E0->getOperand(0); 4636 4637 CurrentOrder.clear(); 4638 4639 // We have to extract from a vector/aggregate with the same number of elements. 4640 unsigned NElts; 4641 if (E0->getOpcode() == Instruction::ExtractValue) { 4642 const DataLayout &DL = E0->getModule()->getDataLayout(); 4643 NElts = canMapToVector(Vec->getType(), DL); 4644 if (!NElts) 4645 return false; 4646 // Check if load can be rewritten as load of vector. 4647 LoadInst *LI = dyn_cast<LoadInst>(Vec); 4648 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 4649 return false; 4650 } else { 4651 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 4652 } 4653 4654 if (NElts != VL.size()) 4655 return false; 4656 4657 // Check that all of the indices extract from the correct offset. 4658 bool ShouldKeepOrder = true; 4659 unsigned E = VL.size(); 4660 // Assign to all items the initial value E + 1 so we can check if the extract 4661 // instruction index was used already. 4662 // Also, later we can check that all the indices are used and we have a 4663 // consecutive access in the extract instructions, by checking that no 4664 // element of CurrentOrder still has value E + 1. 4665 CurrentOrder.assign(E, E); 4666 unsigned I = 0; 4667 for (; I < E; ++I) { 4668 auto *Inst = dyn_cast<Instruction>(VL[I]); 4669 if (!Inst) 4670 continue; 4671 if (Inst->getOperand(0) != Vec) 4672 break; 4673 if (auto *EE = dyn_cast<ExtractElementInst>(Inst)) 4674 if (isa<UndefValue>(EE->getIndexOperand())) 4675 continue; 4676 Optional<unsigned> Idx = getExtractIndex(Inst); 4677 if (!Idx) 4678 break; 4679 const unsigned ExtIdx = *Idx; 4680 if (ExtIdx != I) { 4681 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E) 4682 break; 4683 ShouldKeepOrder = false; 4684 CurrentOrder[ExtIdx] = I; 4685 } else { 4686 if (CurrentOrder[I] != E) 4687 break; 4688 CurrentOrder[I] = I; 4689 } 4690 } 4691 if (I < E) { 4692 CurrentOrder.clear(); 4693 return false; 4694 } 4695 if (ShouldKeepOrder) 4696 CurrentOrder.clear(); 4697 4698 return ShouldKeepOrder; 4699 } 4700 4701 bool BoUpSLP::areAllUsersVectorized(Instruction *I, 4702 ArrayRef<Value *> VectorizedVals) const { 4703 return (I->hasOneUse() && is_contained(VectorizedVals, I)) || 4704 all_of(I->users(), [this](User *U) { 4705 return ScalarToTreeEntry.count(U) > 0 || 4706 isVectorLikeInstWithConstOps(U) || 4707 (isa<ExtractElementInst>(U) && MustGather.contains(U)); 4708 }); 4709 } 4710 4711 static std::pair<InstructionCost, InstructionCost> 4712 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, 4713 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { 4714 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4715 4716 // Calculate the cost of the scalar and vector calls. 4717 SmallVector<Type *, 4> VecTys; 4718 for (Use &Arg : CI->args()) 4719 VecTys.push_back( 4720 FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); 4721 FastMathFlags FMF; 4722 if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) 4723 FMF = FPCI->getFastMathFlags(); 4724 SmallVector<const Value *> Arguments(CI->args()); 4725 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, 4726 dyn_cast<IntrinsicInst>(CI)); 4727 auto IntrinsicCost = 4728 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); 4729 4730 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 4731 VecTy->getNumElements())), 4732 false /*HasGlobalPred*/); 4733 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4734 auto LibCost = IntrinsicCost; 4735 if (!CI->isNoBuiltin() && VecFunc) { 4736 // Calculate the cost of the vector library call. 4737 // If the corresponding vector call is cheaper, return its cost. 4738 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, 4739 TTI::TCK_RecipThroughput); 4740 } 4741 return {IntrinsicCost, LibCost}; 4742 } 4743 4744 /// Compute the cost of creating a vector of type \p VecTy containing the 4745 /// extracted values from \p VL. 4746 static InstructionCost 4747 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, 4748 TargetTransformInfo::ShuffleKind ShuffleKind, 4749 ArrayRef<int> Mask, TargetTransformInfo &TTI) { 4750 unsigned NumOfParts = TTI.getNumberOfParts(VecTy); 4751 4752 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || 4753 VecTy->getNumElements() < NumOfParts) 4754 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); 4755 4756 bool AllConsecutive = true; 4757 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; 4758 unsigned Idx = -1; 4759 InstructionCost Cost = 0; 4760 4761 // Process extracts in blocks of EltsPerVector to check if the source vector 4762 // operand can be re-used directly. If not, add the cost of creating a shuffle 4763 // to extract the values into a vector register. 4764 for (auto *V : VL) { 4765 ++Idx; 4766 4767 // Need to exclude undefs from analysis. 4768 if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem) 4769 continue; 4770 4771 // Reached the start of a new vector registers. 4772 if (Idx % EltsPerVector == 0) { 4773 AllConsecutive = true; 4774 continue; 4775 } 4776 4777 // Check all extracts for a vector register on the target directly 4778 // extract values in order. 4779 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); 4780 if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) { 4781 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); 4782 AllConsecutive &= PrevIdx + 1 == CurrentIdx && 4783 CurrentIdx % EltsPerVector == Idx % EltsPerVector; 4784 } 4785 4786 if (AllConsecutive) 4787 continue; 4788 4789 // Skip all indices, except for the last index per vector block. 4790 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) 4791 continue; 4792 4793 // If we have a series of extracts which are not consecutive and hence 4794 // cannot re-use the source vector register directly, compute the shuffle 4795 // cost to extract the a vector with EltsPerVector elements. 4796 Cost += TTI.getShuffleCost( 4797 TargetTransformInfo::SK_PermuteSingleSrc, 4798 FixedVectorType::get(VecTy->getElementType(), EltsPerVector)); 4799 } 4800 return Cost; 4801 } 4802 4803 /// Build shuffle mask for shuffle graph entries and lists of main and alternate 4804 /// operations operands. 4805 static void 4806 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, 4807 ArrayRef<int> ReusesIndices, 4808 const function_ref<bool(Instruction *)> IsAltOp, 4809 SmallVectorImpl<int> &Mask, 4810 SmallVectorImpl<Value *> *OpScalars = nullptr, 4811 SmallVectorImpl<Value *> *AltScalars = nullptr) { 4812 unsigned Sz = VL.size(); 4813 Mask.assign(Sz, UndefMaskElem); 4814 SmallVector<int> OrderMask; 4815 if (!ReorderIndices.empty()) 4816 inversePermutation(ReorderIndices, OrderMask); 4817 for (unsigned I = 0; I < Sz; ++I) { 4818 unsigned Idx = I; 4819 if (!ReorderIndices.empty()) 4820 Idx = OrderMask[I]; 4821 auto *OpInst = cast<Instruction>(VL[Idx]); 4822 if (IsAltOp(OpInst)) { 4823 Mask[I] = Sz + Idx; 4824 if (AltScalars) 4825 AltScalars->push_back(OpInst); 4826 } else { 4827 Mask[I] = Idx; 4828 if (OpScalars) 4829 OpScalars->push_back(OpInst); 4830 } 4831 } 4832 if (!ReusesIndices.empty()) { 4833 SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); 4834 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { 4835 return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; 4836 }); 4837 Mask.swap(NewMask); 4838 } 4839 } 4840 4841 /// Checks if the specified instruction \p I is an alternate operation for the 4842 /// given \p MainOp and \p AltOp instructions. 4843 static bool isAlternateInstruction(const Instruction *I, 4844 const Instruction *MainOp, 4845 const Instruction *AltOp) { 4846 if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) { 4847 auto *AltCI0 = cast<CmpInst>(AltOp); 4848 auto *CI = cast<CmpInst>(I); 4849 CmpInst::Predicate P0 = CI0->getPredicate(); 4850 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 4851 assert(P0 != AltP0 && "Expected different main/alternate predicates."); 4852 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 4853 CmpInst::Predicate CurrentPred = CI->getPredicate(); 4854 if (P0 == AltP0Swapped) 4855 return I == AltCI0 || 4856 (I != MainOp && 4857 !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1), 4858 CI->getOperand(0), CI->getOperand(1))); 4859 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 4860 } 4861 return I->getOpcode() == AltOp->getOpcode(); 4862 } 4863 4864 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, 4865 ArrayRef<Value *> VectorizedVals) { 4866 ArrayRef<Value*> VL = E->Scalars; 4867 4868 Type *ScalarTy = VL[0]->getType(); 4869 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 4870 ScalarTy = SI->getValueOperand()->getType(); 4871 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 4872 ScalarTy = CI->getOperand(0)->getType(); 4873 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 4874 ScalarTy = IE->getOperand(1)->getType(); 4875 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 4876 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 4877 4878 // If we have computed a smaller type for the expression, update VecTy so 4879 // that the costs will be accurate. 4880 if (MinBWs.count(VL[0])) 4881 VecTy = FixedVectorType::get( 4882 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 4883 unsigned EntryVF = E->getVectorFactor(); 4884 auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF); 4885 4886 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 4887 // FIXME: it tries to fix a problem with MSVC buildbots. 4888 TargetTransformInfo &TTIRef = *TTI; 4889 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy, 4890 VectorizedVals, E](InstructionCost &Cost) { 4891 DenseMap<Value *, int> ExtractVectorsTys; 4892 SmallPtrSet<Value *, 4> CheckedExtracts; 4893 for (auto *V : VL) { 4894 if (isa<UndefValue>(V)) 4895 continue; 4896 // If all users of instruction are going to be vectorized and this 4897 // instruction itself is not going to be vectorized, consider this 4898 // instruction as dead and remove its cost from the final cost of the 4899 // vectorized tree. 4900 // Also, avoid adjusting the cost for extractelements with multiple uses 4901 // in different graph entries. 4902 const TreeEntry *VE = getTreeEntry(V); 4903 if (!CheckedExtracts.insert(V).second || 4904 !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || 4905 (VE && VE != E)) 4906 continue; 4907 auto *EE = cast<ExtractElementInst>(V); 4908 Optional<unsigned> EEIdx = getExtractIndex(EE); 4909 if (!EEIdx) 4910 continue; 4911 unsigned Idx = *EEIdx; 4912 if (TTIRef.getNumberOfParts(VecTy) != 4913 TTIRef.getNumberOfParts(EE->getVectorOperandType())) { 4914 auto It = 4915 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; 4916 It->getSecond() = std::min<int>(It->second, Idx); 4917 } 4918 // Take credit for instruction that will become dead. 4919 if (EE->hasOneUse()) { 4920 Instruction *Ext = EE->user_back(); 4921 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 4922 all_of(Ext->users(), 4923 [](User *U) { return isa<GetElementPtrInst>(U); })) { 4924 // Use getExtractWithExtendCost() to calculate the cost of 4925 // extractelement/ext pair. 4926 Cost -= 4927 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), 4928 EE->getVectorOperandType(), Idx); 4929 // Add back the cost of s|zext which is subtracted separately. 4930 Cost += TTIRef.getCastInstrCost( 4931 Ext->getOpcode(), Ext->getType(), EE->getType(), 4932 TTI::getCastContextHint(Ext), CostKind, Ext); 4933 continue; 4934 } 4935 } 4936 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement, 4937 EE->getVectorOperandType(), Idx); 4938 } 4939 // Add a cost for subvector extracts/inserts if required. 4940 for (const auto &Data : ExtractVectorsTys) { 4941 auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); 4942 unsigned NumElts = VecTy->getNumElements(); 4943 if (Data.second % NumElts == 0) 4944 continue; 4945 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) { 4946 unsigned Idx = (Data.second / NumElts) * NumElts; 4947 unsigned EENumElts = EEVTy->getNumElements(); 4948 if (Idx + NumElts <= EENumElts) { 4949 Cost += 4950 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4951 EEVTy, None, Idx, VecTy); 4952 } else { 4953 // Need to round up the subvector type vectorization factor to avoid a 4954 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT 4955 // <= EENumElts. 4956 auto *SubVT = 4957 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); 4958 Cost += 4959 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4960 EEVTy, None, Idx, SubVT); 4961 } 4962 } else { 4963 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector, 4964 VecTy, None, 0, EEVTy); 4965 } 4966 } 4967 }; 4968 if (E->State == TreeEntry::NeedToGather) { 4969 if (allConstant(VL)) 4970 return 0; 4971 if (isa<InsertElementInst>(VL[0])) 4972 return InstructionCost::getInvalid(); 4973 SmallVector<int> Mask; 4974 SmallVector<const TreeEntry *> Entries; 4975 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 4976 isGatherShuffledEntry(E, Mask, Entries); 4977 if (Shuffle.hasValue()) { 4978 InstructionCost GatherCost = 0; 4979 if (ShuffleVectorInst::isIdentityMask(Mask)) { 4980 // Perfect match in the graph, will reuse the previously vectorized 4981 // node. Cost is 0. 4982 LLVM_DEBUG( 4983 dbgs() 4984 << "SLP: perfect diamond match for gather bundle that starts with " 4985 << *VL.front() << ".\n"); 4986 if (NeedToShuffleReuses) 4987 GatherCost = 4988 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 4989 FinalVecTy, E->ReuseShuffleIndices); 4990 } else { 4991 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size() 4992 << " entries for bundle that starts with " 4993 << *VL.front() << ".\n"); 4994 // Detected that instead of gather we can emit a shuffle of single/two 4995 // previously vectorized nodes. Add the cost of the permutation rather 4996 // than gather. 4997 ::addMask(Mask, E->ReuseShuffleIndices); 4998 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); 4999 } 5000 return GatherCost; 5001 } 5002 if ((E->getOpcode() == Instruction::ExtractElement || 5003 all_of(E->Scalars, 5004 [](Value *V) { 5005 return isa<ExtractElementInst, UndefValue>(V); 5006 })) && 5007 allSameType(VL)) { 5008 // Check that gather of extractelements can be represented as just a 5009 // shuffle of a single/two vectors the scalars are extracted from. 5010 SmallVector<int> Mask; 5011 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = 5012 isFixedVectorShuffle(VL, Mask); 5013 if (ShuffleKind.hasValue()) { 5014 // Found the bunch of extractelement instructions that must be gathered 5015 // into a vector and can be represented as a permutation elements in a 5016 // single input vector or of 2 input vectors. 5017 InstructionCost Cost = 5018 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); 5019 AdjustExtractsCost(Cost); 5020 if (NeedToShuffleReuses) 5021 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5022 FinalVecTy, E->ReuseShuffleIndices); 5023 return Cost; 5024 } 5025 } 5026 if (isSplat(VL)) { 5027 // Found the broadcasting of the single scalar, calculate the cost as the 5028 // broadcast. 5029 assert(VecTy == FinalVecTy && 5030 "No reused scalars expected for broadcast."); 5031 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy); 5032 } 5033 InstructionCost ReuseShuffleCost = 0; 5034 if (NeedToShuffleReuses) 5035 ReuseShuffleCost = TTI->getShuffleCost( 5036 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); 5037 // Improve gather cost for gather of loads, if we can group some of the 5038 // loads into vector loads. 5039 if (VL.size() > 2 && E->getOpcode() == Instruction::Load && 5040 !E->isAltShuffle()) { 5041 BoUpSLP::ValueSet VectorizedLoads; 5042 unsigned StartIdx = 0; 5043 unsigned VF = VL.size() / 2; 5044 unsigned VectorizedCnt = 0; 5045 unsigned ScatterVectorizeCnt = 0; 5046 const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); 5047 for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { 5048 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; 5049 Cnt += VF) { 5050 ArrayRef<Value *> Slice = VL.slice(Cnt, VF); 5051 if (!VectorizedLoads.count(Slice.front()) && 5052 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { 5053 SmallVector<Value *> PointerOps; 5054 OrdersType CurrentOrder; 5055 LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, 5056 *SE, CurrentOrder, PointerOps); 5057 switch (LS) { 5058 case LoadsState::Vectorize: 5059 case LoadsState::ScatterVectorize: 5060 // Mark the vectorized loads so that we don't vectorize them 5061 // again. 5062 if (LS == LoadsState::Vectorize) 5063 ++VectorizedCnt; 5064 else 5065 ++ScatterVectorizeCnt; 5066 VectorizedLoads.insert(Slice.begin(), Slice.end()); 5067 // If we vectorized initial block, no need to try to vectorize it 5068 // again. 5069 if (Cnt == StartIdx) 5070 StartIdx += VF; 5071 break; 5072 case LoadsState::Gather: 5073 break; 5074 } 5075 } 5076 } 5077 // Check if the whole array was vectorized already - exit. 5078 if (StartIdx >= VL.size()) 5079 break; 5080 // Found vectorizable parts - exit. 5081 if (!VectorizedLoads.empty()) 5082 break; 5083 } 5084 if (!VectorizedLoads.empty()) { 5085 InstructionCost GatherCost = 0; 5086 unsigned NumParts = TTI->getNumberOfParts(VecTy); 5087 bool NeedInsertSubvectorAnalysis = 5088 !NumParts || (VL.size() / VF) > NumParts; 5089 // Get the cost for gathered loads. 5090 for (unsigned I = 0, End = VL.size(); I < End; I += VF) { 5091 if (VectorizedLoads.contains(VL[I])) 5092 continue; 5093 GatherCost += getGatherCost(VL.slice(I, VF)); 5094 } 5095 // The cost for vectorized loads. 5096 InstructionCost ScalarsCost = 0; 5097 for (Value *V : VectorizedLoads) { 5098 auto *LI = cast<LoadInst>(V); 5099 ScalarsCost += TTI->getMemoryOpCost( 5100 Instruction::Load, LI->getType(), LI->getAlign(), 5101 LI->getPointerAddressSpace(), CostKind, LI); 5102 } 5103 auto *LI = cast<LoadInst>(E->getMainOp()); 5104 auto *LoadTy = FixedVectorType::get(LI->getType(), VF); 5105 Align Alignment = LI->getAlign(); 5106 GatherCost += 5107 VectorizedCnt * 5108 TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, 5109 LI->getPointerAddressSpace(), CostKind, LI); 5110 GatherCost += ScatterVectorizeCnt * 5111 TTI->getGatherScatterOpCost( 5112 Instruction::Load, LoadTy, LI->getPointerOperand(), 5113 /*VariableMask=*/false, Alignment, CostKind, LI); 5114 if (NeedInsertSubvectorAnalysis) { 5115 // Add the cost for the subvectors insert. 5116 for (int I = VF, E = VL.size(); I < E; I += VF) 5117 GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, 5118 None, I, LoadTy); 5119 } 5120 return ReuseShuffleCost + GatherCost - ScalarsCost; 5121 } 5122 } 5123 return ReuseShuffleCost + getGatherCost(VL); 5124 } 5125 InstructionCost CommonCost = 0; 5126 SmallVector<int> Mask; 5127 if (!E->ReorderIndices.empty()) { 5128 SmallVector<int> NewMask; 5129 if (E->getOpcode() == Instruction::Store) { 5130 // For stores the order is actually a mask. 5131 NewMask.resize(E->ReorderIndices.size()); 5132 copy(E->ReorderIndices, NewMask.begin()); 5133 } else { 5134 inversePermutation(E->ReorderIndices, NewMask); 5135 } 5136 ::addMask(Mask, NewMask); 5137 } 5138 if (NeedToShuffleReuses) 5139 ::addMask(Mask, E->ReuseShuffleIndices); 5140 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) 5141 CommonCost = 5142 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); 5143 assert((E->State == TreeEntry::Vectorize || 5144 E->State == TreeEntry::ScatterVectorize) && 5145 "Unhandled state"); 5146 assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL"); 5147 Instruction *VL0 = E->getMainOp(); 5148 unsigned ShuffleOrOp = 5149 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 5150 switch (ShuffleOrOp) { 5151 case Instruction::PHI: 5152 return 0; 5153 5154 case Instruction::ExtractValue: 5155 case Instruction::ExtractElement: { 5156 // The common cost of removal ExtractElement/ExtractValue instructions + 5157 // the cost of shuffles, if required to resuffle the original vector. 5158 if (NeedToShuffleReuses) { 5159 unsigned Idx = 0; 5160 for (unsigned I : E->ReuseShuffleIndices) { 5161 if (ShuffleOrOp == Instruction::ExtractElement) { 5162 auto *EE = cast<ExtractElementInst>(VL[I]); 5163 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5164 EE->getVectorOperandType(), 5165 *getExtractIndex(EE)); 5166 } else { 5167 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5168 VecTy, Idx); 5169 ++Idx; 5170 } 5171 } 5172 Idx = EntryVF; 5173 for (Value *V : VL) { 5174 if (ShuffleOrOp == Instruction::ExtractElement) { 5175 auto *EE = cast<ExtractElementInst>(V); 5176 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5177 EE->getVectorOperandType(), 5178 *getExtractIndex(EE)); 5179 } else { 5180 --Idx; 5181 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5182 VecTy, Idx); 5183 } 5184 } 5185 } 5186 if (ShuffleOrOp == Instruction::ExtractValue) { 5187 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 5188 auto *EI = cast<Instruction>(VL[I]); 5189 // Take credit for instruction that will become dead. 5190 if (EI->hasOneUse()) { 5191 Instruction *Ext = EI->user_back(); 5192 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5193 all_of(Ext->users(), 5194 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5195 // Use getExtractWithExtendCost() to calculate the cost of 5196 // extractelement/ext pair. 5197 CommonCost -= TTI->getExtractWithExtendCost( 5198 Ext->getOpcode(), Ext->getType(), VecTy, I); 5199 // Add back the cost of s|zext which is subtracted separately. 5200 CommonCost += TTI->getCastInstrCost( 5201 Ext->getOpcode(), Ext->getType(), EI->getType(), 5202 TTI::getCastContextHint(Ext), CostKind, Ext); 5203 continue; 5204 } 5205 } 5206 CommonCost -= 5207 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I); 5208 } 5209 } else { 5210 AdjustExtractsCost(CommonCost); 5211 } 5212 return CommonCost; 5213 } 5214 case Instruction::InsertElement: { 5215 assert(E->ReuseShuffleIndices.empty() && 5216 "Unique insertelements only are expected."); 5217 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); 5218 5219 unsigned const NumElts = SrcVecTy->getNumElements(); 5220 unsigned const NumScalars = VL.size(); 5221 APInt DemandedElts = APInt::getZero(NumElts); 5222 // TODO: Add support for Instruction::InsertValue. 5223 SmallVector<int> Mask; 5224 if (!E->ReorderIndices.empty()) { 5225 inversePermutation(E->ReorderIndices, Mask); 5226 Mask.append(NumElts - NumScalars, UndefMaskElem); 5227 } else { 5228 Mask.assign(NumElts, UndefMaskElem); 5229 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 5230 } 5231 unsigned Offset = *getInsertIndex(VL0); 5232 bool IsIdentity = true; 5233 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 5234 Mask.swap(PrevMask); 5235 for (unsigned I = 0; I < NumScalars; ++I) { 5236 unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]); 5237 DemandedElts.setBit(InsertIdx); 5238 IsIdentity &= InsertIdx - Offset == I; 5239 Mask[InsertIdx - Offset] = I; 5240 } 5241 assert(Offset < NumElts && "Failed to find vector index offset"); 5242 5243 InstructionCost Cost = 0; 5244 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, 5245 /*Insert*/ true, /*Extract*/ false); 5246 5247 if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) { 5248 // FIXME: Replace with SK_InsertSubvector once it is properly supported. 5249 unsigned Sz = PowerOf2Ceil(Offset + NumScalars); 5250 Cost += TTI->getShuffleCost( 5251 TargetTransformInfo::SK_PermuteSingleSrc, 5252 FixedVectorType::get(SrcVecTy->getElementType(), Sz)); 5253 } else if (!IsIdentity) { 5254 auto *FirstInsert = 5255 cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 5256 return !is_contained(E->Scalars, 5257 cast<Instruction>(V)->getOperand(0)); 5258 })); 5259 if (isUndefVector(FirstInsert->getOperand(0))) { 5260 Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask); 5261 } else { 5262 SmallVector<int> InsertMask(NumElts); 5263 std::iota(InsertMask.begin(), InsertMask.end(), 0); 5264 for (unsigned I = 0; I < NumElts; I++) { 5265 if (Mask[I] != UndefMaskElem) 5266 InsertMask[Offset + I] = NumElts + I; 5267 } 5268 Cost += 5269 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask); 5270 } 5271 } 5272 5273 return Cost; 5274 } 5275 case Instruction::ZExt: 5276 case Instruction::SExt: 5277 case Instruction::FPToUI: 5278 case Instruction::FPToSI: 5279 case Instruction::FPExt: 5280 case Instruction::PtrToInt: 5281 case Instruction::IntToPtr: 5282 case Instruction::SIToFP: 5283 case Instruction::UIToFP: 5284 case Instruction::Trunc: 5285 case Instruction::FPTrunc: 5286 case Instruction::BitCast: { 5287 Type *SrcTy = VL0->getOperand(0)->getType(); 5288 InstructionCost ScalarEltCost = 5289 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, 5290 TTI::getCastContextHint(VL0), CostKind, VL0); 5291 if (NeedToShuffleReuses) { 5292 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5293 } 5294 5295 // Calculate the cost of this instruction. 5296 InstructionCost ScalarCost = VL.size() * ScalarEltCost; 5297 5298 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); 5299 InstructionCost VecCost = 0; 5300 // Check if the values are candidates to demote. 5301 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 5302 VecCost = CommonCost + TTI->getCastInstrCost( 5303 E->getOpcode(), VecTy, SrcVecTy, 5304 TTI::getCastContextHint(VL0), CostKind, VL0); 5305 } 5306 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5307 return VecCost - ScalarCost; 5308 } 5309 case Instruction::FCmp: 5310 case Instruction::ICmp: 5311 case Instruction::Select: { 5312 // Calculate the cost of this instruction. 5313 InstructionCost ScalarEltCost = 5314 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5315 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0); 5316 if (NeedToShuffleReuses) { 5317 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5318 } 5319 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); 5320 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5321 5322 // Check if all entries in VL are either compares or selects with compares 5323 // as condition that have the same predicates. 5324 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE; 5325 bool First = true; 5326 for (auto *V : VL) { 5327 CmpInst::Predicate CurrentPred; 5328 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); 5329 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) && 5330 !match(V, MatchCmp)) || 5331 (!First && VecPred != CurrentPred)) { 5332 VecPred = CmpInst::BAD_ICMP_PREDICATE; 5333 break; 5334 } 5335 First = false; 5336 VecPred = CurrentPred; 5337 } 5338 5339 InstructionCost VecCost = TTI->getCmpSelInstrCost( 5340 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); 5341 // Check if it is possible and profitable to use min/max for selects in 5342 // VL. 5343 // 5344 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); 5345 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { 5346 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, 5347 {VecTy, VecTy}); 5348 InstructionCost IntrinsicCost = 5349 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5350 // If the selects are the only uses of the compares, they will be dead 5351 // and we can adjust the cost by removing their cost. 5352 if (IntrinsicAndUse.second) 5353 IntrinsicCost -= 5354 TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy, 5355 CmpInst::BAD_ICMP_PREDICATE, CostKind); 5356 VecCost = std::min(VecCost, IntrinsicCost); 5357 } 5358 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5359 return CommonCost + VecCost - ScalarCost; 5360 } 5361 case Instruction::FNeg: 5362 case Instruction::Add: 5363 case Instruction::FAdd: 5364 case Instruction::Sub: 5365 case Instruction::FSub: 5366 case Instruction::Mul: 5367 case Instruction::FMul: 5368 case Instruction::UDiv: 5369 case Instruction::SDiv: 5370 case Instruction::FDiv: 5371 case Instruction::URem: 5372 case Instruction::SRem: 5373 case Instruction::FRem: 5374 case Instruction::Shl: 5375 case Instruction::LShr: 5376 case Instruction::AShr: 5377 case Instruction::And: 5378 case Instruction::Or: 5379 case Instruction::Xor: { 5380 // Certain instructions can be cheaper to vectorize if they have a 5381 // constant second vector operand. 5382 TargetTransformInfo::OperandValueKind Op1VK = 5383 TargetTransformInfo::OK_AnyValue; 5384 TargetTransformInfo::OperandValueKind Op2VK = 5385 TargetTransformInfo::OK_UniformConstantValue; 5386 TargetTransformInfo::OperandValueProperties Op1VP = 5387 TargetTransformInfo::OP_None; 5388 TargetTransformInfo::OperandValueProperties Op2VP = 5389 TargetTransformInfo::OP_PowerOf2; 5390 5391 // If all operands are exactly the same ConstantInt then set the 5392 // operand kind to OK_UniformConstantValue. 5393 // If instead not all operands are constants, then set the operand kind 5394 // to OK_AnyValue. If all operands are constants but not the same, 5395 // then set the operand kind to OK_NonUniformConstantValue. 5396 ConstantInt *CInt0 = nullptr; 5397 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 5398 const Instruction *I = cast<Instruction>(VL[i]); 5399 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 5400 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 5401 if (!CInt) { 5402 Op2VK = TargetTransformInfo::OK_AnyValue; 5403 Op2VP = TargetTransformInfo::OP_None; 5404 break; 5405 } 5406 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 5407 !CInt->getValue().isPowerOf2()) 5408 Op2VP = TargetTransformInfo::OP_None; 5409 if (i == 0) { 5410 CInt0 = CInt; 5411 continue; 5412 } 5413 if (CInt0 != CInt) 5414 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 5415 } 5416 5417 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 5418 InstructionCost ScalarEltCost = 5419 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK, 5420 Op2VK, Op1VP, Op2VP, Operands, VL0); 5421 if (NeedToShuffleReuses) { 5422 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5423 } 5424 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5425 InstructionCost VecCost = 5426 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK, 5427 Op2VK, Op1VP, Op2VP, Operands, VL0); 5428 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5429 return CommonCost + VecCost - ScalarCost; 5430 } 5431 case Instruction::GetElementPtr: { 5432 TargetTransformInfo::OperandValueKind Op1VK = 5433 TargetTransformInfo::OK_AnyValue; 5434 TargetTransformInfo::OperandValueKind Op2VK = 5435 TargetTransformInfo::OK_UniformConstantValue; 5436 5437 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost( 5438 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK); 5439 if (NeedToShuffleReuses) { 5440 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5441 } 5442 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5443 InstructionCost VecCost = TTI->getArithmeticInstrCost( 5444 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK); 5445 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5446 return CommonCost + VecCost - ScalarCost; 5447 } 5448 case Instruction::Load: { 5449 // Cost of wide load - cost of scalar loads. 5450 Align Alignment = cast<LoadInst>(VL0)->getAlign(); 5451 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5452 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0); 5453 if (NeedToShuffleReuses) { 5454 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5455 } 5456 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 5457 InstructionCost VecLdCost; 5458 if (E->State == TreeEntry::Vectorize) { 5459 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0, 5460 CostKind, VL0); 5461 } else { 5462 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState"); 5463 Align CommonAlignment = Alignment; 5464 for (Value *V : VL) 5465 CommonAlignment = 5466 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 5467 VecLdCost = TTI->getGatherScatterOpCost( 5468 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(), 5469 /*VariableMask=*/false, CommonAlignment, CostKind, VL0); 5470 } 5471 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost)); 5472 return CommonCost + VecLdCost - ScalarLdCost; 5473 } 5474 case Instruction::Store: { 5475 // We know that we can merge the stores. Calculate the cost. 5476 bool IsReorder = !E->ReorderIndices.empty(); 5477 auto *SI = 5478 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 5479 Align Alignment = SI->getAlign(); 5480 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5481 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0); 5482 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 5483 InstructionCost VecStCost = TTI->getMemoryOpCost( 5484 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0); 5485 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost)); 5486 return CommonCost + VecStCost - ScalarStCost; 5487 } 5488 case Instruction::Call: { 5489 CallInst *CI = cast<CallInst>(VL0); 5490 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5491 5492 // Calculate the cost of the scalar and vector calls. 5493 IntrinsicCostAttributes CostAttrs(ID, *CI, 1); 5494 InstructionCost ScalarEltCost = 5495 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5496 if (NeedToShuffleReuses) { 5497 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5498 } 5499 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 5500 5501 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 5502 InstructionCost VecCallCost = 5503 std::min(VecCallCosts.first, VecCallCosts.second); 5504 5505 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 5506 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 5507 << " for " << *CI << "\n"); 5508 5509 return CommonCost + VecCallCost - ScalarCallCost; 5510 } 5511 case Instruction::ShuffleVector: { 5512 assert(E->isAltShuffle() && 5513 ((Instruction::isBinaryOp(E->getOpcode()) && 5514 Instruction::isBinaryOp(E->getAltOpcode())) || 5515 (Instruction::isCast(E->getOpcode()) && 5516 Instruction::isCast(E->getAltOpcode())) || 5517 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 5518 "Invalid Shuffle Vector Operand"); 5519 InstructionCost ScalarCost = 0; 5520 if (NeedToShuffleReuses) { 5521 for (unsigned Idx : E->ReuseShuffleIndices) { 5522 Instruction *I = cast<Instruction>(VL[Idx]); 5523 CommonCost -= TTI->getInstructionCost(I, CostKind); 5524 } 5525 for (Value *V : VL) { 5526 Instruction *I = cast<Instruction>(V); 5527 CommonCost += TTI->getInstructionCost(I, CostKind); 5528 } 5529 } 5530 for (Value *V : VL) { 5531 Instruction *I = cast<Instruction>(V); 5532 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5533 ScalarCost += TTI->getInstructionCost(I, CostKind); 5534 } 5535 // VecCost is equal to sum of the cost of creating 2 vectors 5536 // and the cost of creating shuffle. 5537 InstructionCost VecCost = 0; 5538 // Try to find the previous shuffle node with the same operands and same 5539 // main/alternate ops. 5540 auto &&TryFindNodeWithEqualOperands = [this, E]() { 5541 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 5542 if (TE.get() == E) 5543 break; 5544 if (TE->isAltShuffle() && 5545 ((TE->getOpcode() == E->getOpcode() && 5546 TE->getAltOpcode() == E->getAltOpcode()) || 5547 (TE->getOpcode() == E->getAltOpcode() && 5548 TE->getAltOpcode() == E->getOpcode())) && 5549 TE->hasEqualOperands(*E)) 5550 return true; 5551 } 5552 return false; 5553 }; 5554 if (TryFindNodeWithEqualOperands()) { 5555 LLVM_DEBUG({ 5556 dbgs() << "SLP: diamond match for alternate node found.\n"; 5557 E->dump(); 5558 }); 5559 // No need to add new vector costs here since we're going to reuse 5560 // same main/alternate vector ops, just do different shuffling. 5561 } else if (Instruction::isBinaryOp(E->getOpcode())) { 5562 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); 5563 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, 5564 CostKind); 5565 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 5566 VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, 5567 Builder.getInt1Ty(), 5568 CI0->getPredicate(), CostKind, VL0); 5569 VecCost += TTI->getCmpSelInstrCost( 5570 E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5571 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, 5572 E->getAltOp()); 5573 } else { 5574 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 5575 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 5576 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); 5577 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); 5578 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, 5579 TTI::CastContextHint::None, CostKind); 5580 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, 5581 TTI::CastContextHint::None, CostKind); 5582 } 5583 5584 SmallVector<int> Mask; 5585 buildShuffleEntryMask( 5586 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 5587 [E](Instruction *I) { 5588 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5589 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp()); 5590 }, 5591 Mask); 5592 CommonCost = 5593 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask); 5594 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5595 return CommonCost + VecCost - ScalarCost; 5596 } 5597 default: 5598 llvm_unreachable("Unknown instruction"); 5599 } 5600 } 5601 5602 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { 5603 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 5604 << VectorizableTree.size() << " is fully vectorizable .\n"); 5605 5606 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { 5607 SmallVector<int> Mask; 5608 return TE->State == TreeEntry::NeedToGather && 5609 !any_of(TE->Scalars, 5610 [this](Value *V) { return EphValues.contains(V); }) && 5611 (allConstant(TE->Scalars) || isSplat(TE->Scalars) || 5612 TE->Scalars.size() < Limit || 5613 ((TE->getOpcode() == Instruction::ExtractElement || 5614 all_of(TE->Scalars, 5615 [](Value *V) { 5616 return isa<ExtractElementInst, UndefValue>(V); 5617 })) && 5618 isFixedVectorShuffle(TE->Scalars, Mask)) || 5619 (TE->State == TreeEntry::NeedToGather && 5620 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); 5621 }; 5622 5623 // We only handle trees of heights 1 and 2. 5624 if (VectorizableTree.size() == 1 && 5625 (VectorizableTree[0]->State == TreeEntry::Vectorize || 5626 (ForReduction && 5627 AreVectorizableGathers(VectorizableTree[0].get(), 5628 VectorizableTree[0]->Scalars.size()) && 5629 VectorizableTree[0]->getVectorFactor() > 2))) 5630 return true; 5631 5632 if (VectorizableTree.size() != 2) 5633 return false; 5634 5635 // Handle splat and all-constants stores. Also try to vectorize tiny trees 5636 // with the second gather nodes if they have less scalar operands rather than 5637 // the initial tree element (may be profitable to shuffle the second gather) 5638 // or they are extractelements, which form shuffle. 5639 SmallVector<int> Mask; 5640 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 5641 AreVectorizableGathers(VectorizableTree[1].get(), 5642 VectorizableTree[0]->Scalars.size())) 5643 return true; 5644 5645 // Gathering cost would be too much for tiny trees. 5646 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 5647 (VectorizableTree[1]->State == TreeEntry::NeedToGather && 5648 VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) 5649 return false; 5650 5651 return true; 5652 } 5653 5654 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, 5655 TargetTransformInfo *TTI, 5656 bool MustMatchOrInst) { 5657 // Look past the root to find a source value. Arbitrarily follow the 5658 // path through operand 0 of any 'or'. Also, peek through optional 5659 // shift-left-by-multiple-of-8-bits. 5660 Value *ZextLoad = Root; 5661 const APInt *ShAmtC; 5662 bool FoundOr = false; 5663 while (!isa<ConstantExpr>(ZextLoad) && 5664 (match(ZextLoad, m_Or(m_Value(), m_Value())) || 5665 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && 5666 ShAmtC->urem(8) == 0))) { 5667 auto *BinOp = cast<BinaryOperator>(ZextLoad); 5668 ZextLoad = BinOp->getOperand(0); 5669 if (BinOp->getOpcode() == Instruction::Or) 5670 FoundOr = true; 5671 } 5672 // Check if the input is an extended load of the required or/shift expression. 5673 Value *Load; 5674 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || 5675 !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load)) 5676 return false; 5677 5678 // Require that the total load bit width is a legal integer type. 5679 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 5680 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 5681 Type *SrcTy = Load->getType(); 5682 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 5683 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) 5684 return false; 5685 5686 // Everything matched - assume that we can fold the whole sequence using 5687 // load combining. 5688 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at " 5689 << *(cast<Instruction>(Root)) << "\n"); 5690 5691 return true; 5692 } 5693 5694 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { 5695 if (RdxKind != RecurKind::Or) 5696 return false; 5697 5698 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5699 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 5700 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, 5701 /* MatchOr */ false); 5702 } 5703 5704 bool BoUpSLP::isLoadCombineCandidate() const { 5705 // Peek through a final sequence of stores and check if all operations are 5706 // likely to be load-combined. 5707 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5708 for (Value *Scalar : VectorizableTree[0]->Scalars) { 5709 Value *X; 5710 if (!match(Scalar, m_Store(m_Value(X), m_Value())) || 5711 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) 5712 return false; 5713 } 5714 return true; 5715 } 5716 5717 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { 5718 // No need to vectorize inserts of gathered values. 5719 if (VectorizableTree.size() == 2 && 5720 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && 5721 VectorizableTree[1]->State == TreeEntry::NeedToGather) 5722 return true; 5723 5724 // We can vectorize the tree if its size is greater than or equal to the 5725 // minimum size specified by the MinTreeSize command line option. 5726 if (VectorizableTree.size() >= MinTreeSize) 5727 return false; 5728 5729 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 5730 // can vectorize it if we can prove it fully vectorizable. 5731 if (isFullyVectorizableTinyTree(ForReduction)) 5732 return false; 5733 5734 assert(VectorizableTree.empty() 5735 ? ExternalUses.empty() 5736 : true && "We shouldn't have any external users"); 5737 5738 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 5739 // vectorizable. 5740 return true; 5741 } 5742 5743 InstructionCost BoUpSLP::getSpillCost() const { 5744 // Walk from the bottom of the tree to the top, tracking which values are 5745 // live. When we see a call instruction that is not part of our tree, 5746 // query TTI to see if there is a cost to keeping values live over it 5747 // (for example, if spills and fills are required). 5748 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 5749 InstructionCost Cost = 0; 5750 5751 SmallPtrSet<Instruction*, 4> LiveValues; 5752 Instruction *PrevInst = nullptr; 5753 5754 // The entries in VectorizableTree are not necessarily ordered by their 5755 // position in basic blocks. Collect them and order them by dominance so later 5756 // instructions are guaranteed to be visited first. For instructions in 5757 // different basic blocks, we only scan to the beginning of the block, so 5758 // their order does not matter, as long as all instructions in a basic block 5759 // are grouped together. Using dominance ensures a deterministic order. 5760 SmallVector<Instruction *, 16> OrderedScalars; 5761 for (const auto &TEPtr : VectorizableTree) { 5762 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 5763 if (!Inst) 5764 continue; 5765 OrderedScalars.push_back(Inst); 5766 } 5767 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { 5768 auto *NodeA = DT->getNode(A->getParent()); 5769 auto *NodeB = DT->getNode(B->getParent()); 5770 assert(NodeA && "Should only process reachable instructions"); 5771 assert(NodeB && "Should only process reachable instructions"); 5772 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 5773 "Different nodes should have different DFS numbers"); 5774 if (NodeA != NodeB) 5775 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); 5776 return B->comesBefore(A); 5777 }); 5778 5779 for (Instruction *Inst : OrderedScalars) { 5780 if (!PrevInst) { 5781 PrevInst = Inst; 5782 continue; 5783 } 5784 5785 // Update LiveValues. 5786 LiveValues.erase(PrevInst); 5787 for (auto &J : PrevInst->operands()) { 5788 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 5789 LiveValues.insert(cast<Instruction>(&*J)); 5790 } 5791 5792 LLVM_DEBUG({ 5793 dbgs() << "SLP: #LV: " << LiveValues.size(); 5794 for (auto *X : LiveValues) 5795 dbgs() << " " << X->getName(); 5796 dbgs() << ", Looking at "; 5797 Inst->dump(); 5798 }); 5799 5800 // Now find the sequence of instructions between PrevInst and Inst. 5801 unsigned NumCalls = 0; 5802 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 5803 PrevInstIt = 5804 PrevInst->getIterator().getReverse(); 5805 while (InstIt != PrevInstIt) { 5806 if (PrevInstIt == PrevInst->getParent()->rend()) { 5807 PrevInstIt = Inst->getParent()->rbegin(); 5808 continue; 5809 } 5810 5811 // Debug information does not impact spill cost. 5812 if ((isa<CallInst>(&*PrevInstIt) && 5813 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 5814 &*PrevInstIt != PrevInst) 5815 NumCalls++; 5816 5817 ++PrevInstIt; 5818 } 5819 5820 if (NumCalls) { 5821 SmallVector<Type*, 4> V; 5822 for (auto *II : LiveValues) { 5823 auto *ScalarTy = II->getType(); 5824 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) 5825 ScalarTy = VectorTy->getElementType(); 5826 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); 5827 } 5828 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 5829 } 5830 5831 PrevInst = Inst; 5832 } 5833 5834 return Cost; 5835 } 5836 5837 /// Check if two insertelement instructions are from the same buildvector. 5838 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU, 5839 InsertElementInst *V) { 5840 // Instructions must be from the same basic blocks. 5841 if (VU->getParent() != V->getParent()) 5842 return false; 5843 // Checks if 2 insertelements are from the same buildvector. 5844 if (VU->getType() != V->getType()) 5845 return false; 5846 // Multiple used inserts are separate nodes. 5847 if (!VU->hasOneUse() && !V->hasOneUse()) 5848 return false; 5849 auto *IE1 = VU; 5850 auto *IE2 = V; 5851 // Go through the vector operand of insertelement instructions trying to find 5852 // either VU as the original vector for IE2 or V as the original vector for 5853 // IE1. 5854 do { 5855 if (IE2 == VU || IE1 == V) 5856 return true; 5857 if (IE1) { 5858 if (IE1 != VU && !IE1->hasOneUse()) 5859 IE1 = nullptr; 5860 else 5861 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0)); 5862 } 5863 if (IE2) { 5864 if (IE2 != V && !IE2->hasOneUse()) 5865 IE2 = nullptr; 5866 else 5867 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0)); 5868 } 5869 } while (IE1 || IE2); 5870 return false; 5871 } 5872 5873 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { 5874 InstructionCost Cost = 0; 5875 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 5876 << VectorizableTree.size() << ".\n"); 5877 5878 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 5879 5880 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 5881 TreeEntry &TE = *VectorizableTree[I].get(); 5882 5883 InstructionCost C = getEntryCost(&TE, VectorizedVals); 5884 Cost += C; 5885 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5886 << " for bundle that starts with " << *TE.Scalars[0] 5887 << ".\n" 5888 << "SLP: Current total cost = " << Cost << "\n"); 5889 } 5890 5891 SmallPtrSet<Value *, 16> ExtractCostCalculated; 5892 InstructionCost ExtractCost = 0; 5893 SmallVector<unsigned> VF; 5894 SmallVector<SmallVector<int>> ShuffleMask; 5895 SmallVector<Value *> FirstUsers; 5896 SmallVector<APInt> DemandedElts; 5897 for (ExternalUser &EU : ExternalUses) { 5898 // We only add extract cost once for the same scalar. 5899 if (!isa_and_nonnull<InsertElementInst>(EU.User) && 5900 !ExtractCostCalculated.insert(EU.Scalar).second) 5901 continue; 5902 5903 // Uses by ephemeral values are free (because the ephemeral value will be 5904 // removed prior to code generation, and so the extraction will be 5905 // removed as well). 5906 if (EphValues.count(EU.User)) 5907 continue; 5908 5909 // No extract cost for vector "scalar" 5910 if (isa<FixedVectorType>(EU.Scalar->getType())) 5911 continue; 5912 5913 // Already counted the cost for external uses when tried to adjust the cost 5914 // for extractelements, no need to add it again. 5915 if (isa<ExtractElementInst>(EU.Scalar)) 5916 continue; 5917 5918 // If found user is an insertelement, do not calculate extract cost but try 5919 // to detect it as a final shuffled/identity match. 5920 if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) { 5921 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) { 5922 unsigned InsertIdx = *getInsertIndex(VU); 5923 auto *It = find_if(FirstUsers, [VU](Value *V) { 5924 return areTwoInsertFromSameBuildVector(VU, 5925 cast<InsertElementInst>(V)); 5926 }); 5927 int VecId = -1; 5928 if (It == FirstUsers.end()) { 5929 VF.push_back(FTy->getNumElements()); 5930 ShuffleMask.emplace_back(VF.back(), UndefMaskElem); 5931 // Find the insertvector, vectorized in tree, if any. 5932 Value *Base = VU; 5933 while (isa<InsertElementInst>(Base)) { 5934 // Build the mask for the vectorized insertelement instructions. 5935 if (const TreeEntry *E = getTreeEntry(Base)) { 5936 VU = cast<InsertElementInst>(Base); 5937 do { 5938 int Idx = E->findLaneForValue(Base); 5939 ShuffleMask.back()[Idx] = Idx; 5940 Base = cast<InsertElementInst>(Base)->getOperand(0); 5941 } while (E == getTreeEntry(Base)); 5942 break; 5943 } 5944 Base = cast<InsertElementInst>(Base)->getOperand(0); 5945 } 5946 FirstUsers.push_back(VU); 5947 DemandedElts.push_back(APInt::getZero(VF.back())); 5948 VecId = FirstUsers.size() - 1; 5949 } else { 5950 VecId = std::distance(FirstUsers.begin(), It); 5951 } 5952 ShuffleMask[VecId][InsertIdx] = EU.Lane; 5953 DemandedElts[VecId].setBit(InsertIdx); 5954 continue; 5955 } 5956 } 5957 5958 // If we plan to rewrite the tree in a smaller type, we will need to sign 5959 // extend the extracted value back to the original type. Here, we account 5960 // for the extract and the added cost of the sign extend if needed. 5961 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); 5962 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 5963 if (MinBWs.count(ScalarRoot)) { 5964 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 5965 auto Extend = 5966 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 5967 VecTy = FixedVectorType::get(MinTy, BundleWidth); 5968 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 5969 VecTy, EU.Lane); 5970 } else { 5971 ExtractCost += 5972 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 5973 } 5974 } 5975 5976 InstructionCost SpillCost = getSpillCost(); 5977 Cost += SpillCost + ExtractCost; 5978 if (FirstUsers.size() == 1) { 5979 int Limit = ShuffleMask.front().size() * 2; 5980 if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) && 5981 !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) { 5982 InstructionCost C = TTI->getShuffleCost( 5983 TTI::SK_PermuteSingleSrc, 5984 cast<FixedVectorType>(FirstUsers.front()->getType()), 5985 ShuffleMask.front()); 5986 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5987 << " for final shuffle of insertelement external users " 5988 << *VectorizableTree.front()->Scalars.front() << ".\n" 5989 << "SLP: Current total cost = " << Cost << "\n"); 5990 Cost += C; 5991 } 5992 InstructionCost InsertCost = TTI->getScalarizationOverhead( 5993 cast<FixedVectorType>(FirstUsers.front()->getType()), 5994 DemandedElts.front(), /*Insert*/ true, /*Extract*/ false); 5995 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 5996 << " for insertelements gather.\n" 5997 << "SLP: Current total cost = " << Cost << "\n"); 5998 Cost -= InsertCost; 5999 } else if (FirstUsers.size() >= 2) { 6000 unsigned MaxVF = *std::max_element(VF.begin(), VF.end()); 6001 // Combined masks of the first 2 vectors. 6002 SmallVector<int> CombinedMask(MaxVF, UndefMaskElem); 6003 copy(ShuffleMask.front(), CombinedMask.begin()); 6004 APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF); 6005 auto *VecTy = FixedVectorType::get( 6006 cast<VectorType>(FirstUsers.front()->getType())->getElementType(), 6007 MaxVF); 6008 for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) { 6009 if (ShuffleMask[1][I] != UndefMaskElem) { 6010 CombinedMask[I] = ShuffleMask[1][I] + MaxVF; 6011 CombinedDemandedElts.setBit(I); 6012 } 6013 } 6014 InstructionCost C = 6015 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6016 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6017 << " for final shuffle of vector node and external " 6018 "insertelement users " 6019 << *VectorizableTree.front()->Scalars.front() << ".\n" 6020 << "SLP: Current total cost = " << Cost << "\n"); 6021 Cost += C; 6022 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6023 VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false); 6024 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6025 << " for insertelements gather.\n" 6026 << "SLP: Current total cost = " << Cost << "\n"); 6027 Cost -= InsertCost; 6028 for (int I = 2, E = FirstUsers.size(); I < E; ++I) { 6029 // Other elements - permutation of 2 vectors (the initial one and the 6030 // next Ith incoming vector). 6031 unsigned VF = ShuffleMask[I].size(); 6032 for (unsigned Idx = 0; Idx < VF; ++Idx) { 6033 int Mask = ShuffleMask[I][Idx]; 6034 if (Mask != UndefMaskElem) 6035 CombinedMask[Idx] = MaxVF + Mask; 6036 else if (CombinedMask[Idx] != UndefMaskElem) 6037 CombinedMask[Idx] = Idx; 6038 } 6039 for (unsigned Idx = VF; Idx < MaxVF; ++Idx) 6040 if (CombinedMask[Idx] != UndefMaskElem) 6041 CombinedMask[Idx] = Idx; 6042 InstructionCost C = 6043 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6044 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6045 << " for final shuffle of vector node and external " 6046 "insertelement users " 6047 << *VectorizableTree.front()->Scalars.front() << ".\n" 6048 << "SLP: Current total cost = " << Cost << "\n"); 6049 Cost += C; 6050 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6051 cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I], 6052 /*Insert*/ true, /*Extract*/ false); 6053 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6054 << " for insertelements gather.\n" 6055 << "SLP: Current total cost = " << Cost << "\n"); 6056 Cost -= InsertCost; 6057 } 6058 } 6059 6060 #ifndef NDEBUG 6061 SmallString<256> Str; 6062 { 6063 raw_svector_ostream OS(Str); 6064 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 6065 << "SLP: Extract Cost = " << ExtractCost << ".\n" 6066 << "SLP: Total Cost = " << Cost << ".\n"; 6067 } 6068 LLVM_DEBUG(dbgs() << Str); 6069 if (ViewSLPTree) 6070 ViewGraph(this, "SLP" + F->getName(), false, Str); 6071 #endif 6072 6073 return Cost; 6074 } 6075 6076 Optional<TargetTransformInfo::ShuffleKind> 6077 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 6078 SmallVectorImpl<const TreeEntry *> &Entries) { 6079 // TODO: currently checking only for Scalars in the tree entry, need to count 6080 // reused elements too for better cost estimation. 6081 Mask.assign(TE->Scalars.size(), UndefMaskElem); 6082 Entries.clear(); 6083 // Build a lists of values to tree entries. 6084 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; 6085 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { 6086 if (EntryPtr.get() == TE) 6087 break; 6088 if (EntryPtr->State != TreeEntry::NeedToGather) 6089 continue; 6090 for (Value *V : EntryPtr->Scalars) 6091 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); 6092 } 6093 // Find all tree entries used by the gathered values. If no common entries 6094 // found - not a shuffle. 6095 // Here we build a set of tree nodes for each gathered value and trying to 6096 // find the intersection between these sets. If we have at least one common 6097 // tree node for each gathered value - we have just a permutation of the 6098 // single vector. If we have 2 different sets, we're in situation where we 6099 // have a permutation of 2 input vectors. 6100 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; 6101 DenseMap<Value *, int> UsedValuesEntry; 6102 for (Value *V : TE->Scalars) { 6103 if (isa<UndefValue>(V)) 6104 continue; 6105 // Build a list of tree entries where V is used. 6106 SmallPtrSet<const TreeEntry *, 4> VToTEs; 6107 auto It = ValueToTEs.find(V); 6108 if (It != ValueToTEs.end()) 6109 VToTEs = It->second; 6110 if (const TreeEntry *VTE = getTreeEntry(V)) 6111 VToTEs.insert(VTE); 6112 if (VToTEs.empty()) 6113 return None; 6114 if (UsedTEs.empty()) { 6115 // The first iteration, just insert the list of nodes to vector. 6116 UsedTEs.push_back(VToTEs); 6117 } else { 6118 // Need to check if there are any previously used tree nodes which use V. 6119 // If there are no such nodes, consider that we have another one input 6120 // vector. 6121 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); 6122 unsigned Idx = 0; 6123 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { 6124 // Do we have a non-empty intersection of previously listed tree entries 6125 // and tree entries using current V? 6126 set_intersect(VToTEs, Set); 6127 if (!VToTEs.empty()) { 6128 // Yes, write the new subset and continue analysis for the next 6129 // scalar. 6130 Set.swap(VToTEs); 6131 break; 6132 } 6133 VToTEs = SavedVToTEs; 6134 ++Idx; 6135 } 6136 // No non-empty intersection found - need to add a second set of possible 6137 // source vectors. 6138 if (Idx == UsedTEs.size()) { 6139 // If the number of input vectors is greater than 2 - not a permutation, 6140 // fallback to the regular gather. 6141 if (UsedTEs.size() == 2) 6142 return None; 6143 UsedTEs.push_back(SavedVToTEs); 6144 Idx = UsedTEs.size() - 1; 6145 } 6146 UsedValuesEntry.try_emplace(V, Idx); 6147 } 6148 } 6149 6150 unsigned VF = 0; 6151 if (UsedTEs.size() == 1) { 6152 // Try to find the perfect match in another gather node at first. 6153 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { 6154 return EntryPtr->isSame(TE->Scalars); 6155 }); 6156 if (It != UsedTEs.front().end()) { 6157 Entries.push_back(*It); 6158 std::iota(Mask.begin(), Mask.end(), 0); 6159 return TargetTransformInfo::SK_PermuteSingleSrc; 6160 } 6161 // No perfect match, just shuffle, so choose the first tree node. 6162 Entries.push_back(*UsedTEs.front().begin()); 6163 } else { 6164 // Try to find nodes with the same vector factor. 6165 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries."); 6166 DenseMap<int, const TreeEntry *> VFToTE; 6167 for (const TreeEntry *TE : UsedTEs.front()) 6168 VFToTE.try_emplace(TE->getVectorFactor(), TE); 6169 for (const TreeEntry *TE : UsedTEs.back()) { 6170 auto It = VFToTE.find(TE->getVectorFactor()); 6171 if (It != VFToTE.end()) { 6172 VF = It->first; 6173 Entries.push_back(It->second); 6174 Entries.push_back(TE); 6175 break; 6176 } 6177 } 6178 // No 2 source vectors with the same vector factor - give up and do regular 6179 // gather. 6180 if (Entries.empty()) 6181 return None; 6182 } 6183 6184 // Build a shuffle mask for better cost estimation and vector emission. 6185 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { 6186 Value *V = TE->Scalars[I]; 6187 if (isa<UndefValue>(V)) 6188 continue; 6189 unsigned Idx = UsedValuesEntry.lookup(V); 6190 const TreeEntry *VTE = Entries[Idx]; 6191 int FoundLane = VTE->findLaneForValue(V); 6192 Mask[I] = Idx * VF + FoundLane; 6193 // Extra check required by isSingleSourceMaskImpl function (called by 6194 // ShuffleVectorInst::isSingleSourceMask). 6195 if (Mask[I] >= 2 * E) 6196 return None; 6197 } 6198 switch (Entries.size()) { 6199 case 1: 6200 return TargetTransformInfo::SK_PermuteSingleSrc; 6201 case 2: 6202 return TargetTransformInfo::SK_PermuteTwoSrc; 6203 default: 6204 break; 6205 } 6206 return None; 6207 } 6208 6209 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty, 6210 const APInt &ShuffledIndices, 6211 bool NeedToShuffle) const { 6212 InstructionCost Cost = 6213 TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true, 6214 /*Extract*/ false); 6215 if (NeedToShuffle) 6216 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 6217 return Cost; 6218 } 6219 6220 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 6221 // Find the type of the operands in VL. 6222 Type *ScalarTy = VL[0]->getType(); 6223 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 6224 ScalarTy = SI->getValueOperand()->getType(); 6225 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 6226 bool DuplicateNonConst = false; 6227 // Find the cost of inserting/extracting values from the vector. 6228 // Check if the same elements are inserted several times and count them as 6229 // shuffle candidates. 6230 APInt ShuffledElements = APInt::getZero(VL.size()); 6231 DenseSet<Value *> UniqueElements; 6232 // Iterate in reverse order to consider insert elements with the high cost. 6233 for (unsigned I = VL.size(); I > 0; --I) { 6234 unsigned Idx = I - 1; 6235 // No need to shuffle duplicates for constants. 6236 if (isConstant(VL[Idx])) { 6237 ShuffledElements.setBit(Idx); 6238 continue; 6239 } 6240 if (!UniqueElements.insert(VL[Idx]).second) { 6241 DuplicateNonConst = true; 6242 ShuffledElements.setBit(Idx); 6243 } 6244 } 6245 return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst); 6246 } 6247 6248 // Perform operand reordering on the instructions in VL and return the reordered 6249 // operands in Left and Right. 6250 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 6251 SmallVectorImpl<Value *> &Left, 6252 SmallVectorImpl<Value *> &Right, 6253 const DataLayout &DL, 6254 ScalarEvolution &SE, 6255 const BoUpSLP &R) { 6256 if (VL.empty()) 6257 return; 6258 VLOperands Ops(VL, DL, SE, R); 6259 // Reorder the operands in place. 6260 Ops.reorder(); 6261 Left = Ops.getVL(0); 6262 Right = Ops.getVL(1); 6263 } 6264 6265 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { 6266 // Get the basic block this bundle is in. All instructions in the bundle 6267 // should be in this block. 6268 auto *Front = E->getMainOp(); 6269 auto *BB = Front->getParent(); 6270 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool { 6271 auto *I = cast<Instruction>(V); 6272 return !E->isOpcodeOrAlt(I) || I->getParent() == BB; 6273 })); 6274 6275 // The last instruction in the bundle in program order. 6276 Instruction *LastInst = nullptr; 6277 6278 // Find the last instruction. The common case should be that BB has been 6279 // scheduled, and the last instruction is VL.back(). So we start with 6280 // VL.back() and iterate over schedule data until we reach the end of the 6281 // bundle. The end of the bundle is marked by null ScheduleData. 6282 if (BlocksSchedules.count(BB)) { 6283 auto *Bundle = 6284 BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back())); 6285 if (Bundle && Bundle->isPartOfBundle()) 6286 for (; Bundle; Bundle = Bundle->NextInBundle) 6287 if (Bundle->OpValue == Bundle->Inst) 6288 LastInst = Bundle->Inst; 6289 } 6290 6291 // LastInst can still be null at this point if there's either not an entry 6292 // for BB in BlocksSchedules or there's no ScheduleData available for 6293 // VL.back(). This can be the case if buildTree_rec aborts for various 6294 // reasons (e.g., the maximum recursion depth is reached, the maximum region 6295 // size is reached, etc.). ScheduleData is initialized in the scheduling 6296 // "dry-run". 6297 // 6298 // If this happens, we can still find the last instruction by brute force. We 6299 // iterate forwards from Front (inclusive) until we either see all 6300 // instructions in the bundle or reach the end of the block. If Front is the 6301 // last instruction in program order, LastInst will be set to Front, and we 6302 // will visit all the remaining instructions in the block. 6303 // 6304 // One of the reasons we exit early from buildTree_rec is to place an upper 6305 // bound on compile-time. Thus, taking an additional compile-time hit here is 6306 // not ideal. However, this should be exceedingly rare since it requires that 6307 // we both exit early from buildTree_rec and that the bundle be out-of-order 6308 // (causing us to iterate all the way to the end of the block). 6309 if (!LastInst) { 6310 SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end()); 6311 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) { 6312 if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I)) 6313 LastInst = &I; 6314 if (Bundle.empty()) 6315 break; 6316 } 6317 } 6318 assert(LastInst && "Failed to find last instruction in bundle"); 6319 6320 // Set the insertion point after the last instruction in the bundle. Set the 6321 // debug location to Front. 6322 Builder.SetInsertPoint(BB, ++LastInst->getIterator()); 6323 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 6324 } 6325 6326 Value *BoUpSLP::gather(ArrayRef<Value *> VL) { 6327 // List of instructions/lanes from current block and/or the blocks which are 6328 // part of the current loop. These instructions will be inserted at the end to 6329 // make it possible to optimize loops and hoist invariant instructions out of 6330 // the loops body with better chances for success. 6331 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; 6332 SmallSet<int, 4> PostponedIndices; 6333 Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); 6334 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { 6335 SmallPtrSet<BasicBlock *, 4> Visited; 6336 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) 6337 InsertBB = InsertBB->getSinglePredecessor(); 6338 return InsertBB && InsertBB == InstBB; 6339 }; 6340 for (int I = 0, E = VL.size(); I < E; ++I) { 6341 if (auto *Inst = dyn_cast<Instruction>(VL[I])) 6342 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || 6343 getTreeEntry(Inst) || (L && (L->contains(Inst)))) && 6344 PostponedIndices.insert(I).second) 6345 PostponedInsts.emplace_back(Inst, I); 6346 } 6347 6348 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { 6349 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); 6350 auto *InsElt = dyn_cast<InsertElementInst>(Vec); 6351 if (!InsElt) 6352 return Vec; 6353 GatherShuffleSeq.insert(InsElt); 6354 CSEBlocks.insert(InsElt->getParent()); 6355 // Add to our 'need-to-extract' list. 6356 if (TreeEntry *Entry = getTreeEntry(V)) { 6357 // Find which lane we need to extract. 6358 unsigned FoundLane = Entry->findLaneForValue(V); 6359 ExternalUses.emplace_back(V, InsElt, FoundLane); 6360 } 6361 return Vec; 6362 }; 6363 Value *Val0 = 6364 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; 6365 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); 6366 Value *Vec = PoisonValue::get(VecTy); 6367 SmallVector<int> NonConsts; 6368 // Insert constant values at first. 6369 for (int I = 0, E = VL.size(); I < E; ++I) { 6370 if (PostponedIndices.contains(I)) 6371 continue; 6372 if (!isConstant(VL[I])) { 6373 NonConsts.push_back(I); 6374 continue; 6375 } 6376 Vec = CreateInsertElement(Vec, VL[I], I); 6377 } 6378 // Insert non-constant values. 6379 for (int I : NonConsts) 6380 Vec = CreateInsertElement(Vec, VL[I], I); 6381 // Append instructions, which are/may be part of the loop, in the end to make 6382 // it possible to hoist non-loop-based instructions. 6383 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) 6384 Vec = CreateInsertElement(Vec, Pair.first, Pair.second); 6385 6386 return Vec; 6387 } 6388 6389 namespace { 6390 /// Merges shuffle masks and emits final shuffle instruction, if required. 6391 class ShuffleInstructionBuilder { 6392 IRBuilderBase &Builder; 6393 const unsigned VF = 0; 6394 bool IsFinalized = false; 6395 SmallVector<int, 4> Mask; 6396 /// Holds all of the instructions that we gathered. 6397 SetVector<Instruction *> &GatherShuffleSeq; 6398 /// A list of blocks that we are going to CSE. 6399 SetVector<BasicBlock *> &CSEBlocks; 6400 6401 public: 6402 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF, 6403 SetVector<Instruction *> &GatherShuffleSeq, 6404 SetVector<BasicBlock *> &CSEBlocks) 6405 : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq), 6406 CSEBlocks(CSEBlocks) {} 6407 6408 /// Adds a mask, inverting it before applying. 6409 void addInversedMask(ArrayRef<unsigned> SubMask) { 6410 if (SubMask.empty()) 6411 return; 6412 SmallVector<int, 4> NewMask; 6413 inversePermutation(SubMask, NewMask); 6414 addMask(NewMask); 6415 } 6416 6417 /// Functions adds masks, merging them into single one. 6418 void addMask(ArrayRef<unsigned> SubMask) { 6419 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end()); 6420 addMask(NewMask); 6421 } 6422 6423 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } 6424 6425 Value *finalize(Value *V) { 6426 IsFinalized = true; 6427 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); 6428 if (VF == ValueVF && Mask.empty()) 6429 return V; 6430 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); 6431 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); 6432 addMask(NormalizedMask); 6433 6434 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) 6435 return V; 6436 Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle"); 6437 if (auto *I = dyn_cast<Instruction>(Vec)) { 6438 GatherShuffleSeq.insert(I); 6439 CSEBlocks.insert(I->getParent()); 6440 } 6441 return Vec; 6442 } 6443 6444 ~ShuffleInstructionBuilder() { 6445 assert((IsFinalized || Mask.empty()) && 6446 "Shuffle construction must be finalized."); 6447 } 6448 }; 6449 } // namespace 6450 6451 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 6452 unsigned VF = VL.size(); 6453 InstructionsState S = getSameOpcode(VL); 6454 if (S.getOpcode()) { 6455 if (TreeEntry *E = getTreeEntry(S.OpValue)) 6456 if (E->isSame(VL)) { 6457 Value *V = vectorizeTree(E); 6458 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { 6459 if (!E->ReuseShuffleIndices.empty()) { 6460 // Reshuffle to get only unique values. 6461 // If some of the scalars are duplicated in the vectorization tree 6462 // entry, we do not vectorize them but instead generate a mask for 6463 // the reuses. But if there are several users of the same entry, 6464 // they may have different vectorization factors. This is especially 6465 // important for PHI nodes. In this case, we need to adapt the 6466 // resulting instruction for the user vectorization factor and have 6467 // to reshuffle it again to take only unique elements of the vector. 6468 // Without this code the function incorrectly returns reduced vector 6469 // instruction with the same elements, not with the unique ones. 6470 6471 // block: 6472 // %phi = phi <2 x > { .., %entry} {%shuffle, %block} 6473 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> 6474 // ... (use %2) 6475 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} 6476 // br %block 6477 SmallVector<int> UniqueIdxs(VF, UndefMaskElem); 6478 SmallSet<int, 4> UsedIdxs; 6479 int Pos = 0; 6480 int Sz = VL.size(); 6481 for (int Idx : E->ReuseShuffleIndices) { 6482 if (Idx != Sz && Idx != UndefMaskElem && 6483 UsedIdxs.insert(Idx).second) 6484 UniqueIdxs[Idx] = Pos; 6485 ++Pos; 6486 } 6487 assert(VF >= UsedIdxs.size() && "Expected vectorization factor " 6488 "less than original vector size."); 6489 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); 6490 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); 6491 } else { 6492 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() && 6493 "Expected vectorization factor less " 6494 "than original vector size."); 6495 SmallVector<int> UniformMask(VF, 0); 6496 std::iota(UniformMask.begin(), UniformMask.end(), 0); 6497 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); 6498 } 6499 if (auto *I = dyn_cast<Instruction>(V)) { 6500 GatherShuffleSeq.insert(I); 6501 CSEBlocks.insert(I->getParent()); 6502 } 6503 } 6504 return V; 6505 } 6506 } 6507 6508 // Check that every instruction appears once in this bundle. 6509 SmallVector<int> ReuseShuffleIndicies; 6510 SmallVector<Value *> UniqueValues; 6511 if (VL.size() > 2) { 6512 DenseMap<Value *, unsigned> UniquePositions; 6513 unsigned NumValues = 6514 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { 6515 return !isa<UndefValue>(V); 6516 }).base()); 6517 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); 6518 int UniqueVals = 0; 6519 for (Value *V : VL.drop_back(VL.size() - VF)) { 6520 if (isa<UndefValue>(V)) { 6521 ReuseShuffleIndicies.emplace_back(UndefMaskElem); 6522 continue; 6523 } 6524 if (isConstant(V)) { 6525 ReuseShuffleIndicies.emplace_back(UniqueValues.size()); 6526 UniqueValues.emplace_back(V); 6527 continue; 6528 } 6529 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 6530 ReuseShuffleIndicies.emplace_back(Res.first->second); 6531 if (Res.second) { 6532 UniqueValues.emplace_back(V); 6533 ++UniqueVals; 6534 } 6535 } 6536 if (UniqueVals == 1 && UniqueValues.size() == 1) { 6537 // Emit pure splat vector. 6538 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), 6539 UndefMaskElem); 6540 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { 6541 ReuseShuffleIndicies.clear(); 6542 UniqueValues.clear(); 6543 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); 6544 } 6545 UniqueValues.append(VF - UniqueValues.size(), 6546 PoisonValue::get(VL[0]->getType())); 6547 VL = UniqueValues; 6548 } 6549 6550 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6551 CSEBlocks); 6552 Value *Vec = gather(VL); 6553 if (!ReuseShuffleIndicies.empty()) { 6554 ShuffleBuilder.addMask(ReuseShuffleIndicies); 6555 Vec = ShuffleBuilder.finalize(Vec); 6556 } 6557 return Vec; 6558 } 6559 6560 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 6561 IRBuilder<>::InsertPointGuard Guard(Builder); 6562 6563 if (E->VectorizedValue) { 6564 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 6565 return E->VectorizedValue; 6566 } 6567 6568 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 6569 unsigned VF = E->getVectorFactor(); 6570 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6571 CSEBlocks); 6572 if (E->State == TreeEntry::NeedToGather) { 6573 if (E->getMainOp()) 6574 setInsertPointAfterBundle(E); 6575 Value *Vec; 6576 SmallVector<int> Mask; 6577 SmallVector<const TreeEntry *> Entries; 6578 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 6579 isGatherShuffledEntry(E, Mask, Entries); 6580 if (Shuffle.hasValue()) { 6581 assert((Entries.size() == 1 || Entries.size() == 2) && 6582 "Expected shuffle of 1 or 2 entries."); 6583 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, 6584 Entries.back()->VectorizedValue, Mask); 6585 if (auto *I = dyn_cast<Instruction>(Vec)) { 6586 GatherShuffleSeq.insert(I); 6587 CSEBlocks.insert(I->getParent()); 6588 } 6589 } else { 6590 Vec = gather(E->Scalars); 6591 } 6592 if (NeedToShuffleReuses) { 6593 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6594 Vec = ShuffleBuilder.finalize(Vec); 6595 } 6596 E->VectorizedValue = Vec; 6597 return Vec; 6598 } 6599 6600 assert((E->State == TreeEntry::Vectorize || 6601 E->State == TreeEntry::ScatterVectorize) && 6602 "Unhandled state"); 6603 unsigned ShuffleOrOp = 6604 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 6605 Instruction *VL0 = E->getMainOp(); 6606 Type *ScalarTy = VL0->getType(); 6607 if (auto *Store = dyn_cast<StoreInst>(VL0)) 6608 ScalarTy = Store->getValueOperand()->getType(); 6609 else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) 6610 ScalarTy = IE->getOperand(1)->getType(); 6611 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); 6612 switch (ShuffleOrOp) { 6613 case Instruction::PHI: { 6614 assert( 6615 (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) && 6616 "PHI reordering is free."); 6617 auto *PH = cast<PHINode>(VL0); 6618 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 6619 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6620 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 6621 Value *V = NewPhi; 6622 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6623 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6624 V = ShuffleBuilder.finalize(V); 6625 6626 E->VectorizedValue = V; 6627 6628 // PHINodes may have multiple entries from the same block. We want to 6629 // visit every block once. 6630 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 6631 6632 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 6633 ValueList Operands; 6634 BasicBlock *IBB = PH->getIncomingBlock(i); 6635 6636 if (!VisitedBBs.insert(IBB).second) { 6637 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 6638 continue; 6639 } 6640 6641 Builder.SetInsertPoint(IBB->getTerminator()); 6642 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6643 Value *Vec = vectorizeTree(E->getOperand(i)); 6644 NewPhi->addIncoming(Vec, IBB); 6645 } 6646 6647 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 6648 "Invalid number of incoming values"); 6649 return V; 6650 } 6651 6652 case Instruction::ExtractElement: { 6653 Value *V = E->getSingleOperand(0); 6654 Builder.SetInsertPoint(VL0); 6655 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6656 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6657 V = ShuffleBuilder.finalize(V); 6658 E->VectorizedValue = V; 6659 return V; 6660 } 6661 case Instruction::ExtractValue: { 6662 auto *LI = cast<LoadInst>(E->getSingleOperand(0)); 6663 Builder.SetInsertPoint(LI); 6664 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); 6665 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 6666 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 6667 Value *NewV = propagateMetadata(V, E->Scalars); 6668 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6669 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6670 NewV = ShuffleBuilder.finalize(NewV); 6671 E->VectorizedValue = NewV; 6672 return NewV; 6673 } 6674 case Instruction::InsertElement: { 6675 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique"); 6676 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); 6677 Value *V = vectorizeTree(E->getOperand(1)); 6678 6679 // Create InsertVector shuffle if necessary 6680 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 6681 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 6682 })); 6683 const unsigned NumElts = 6684 cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); 6685 const unsigned NumScalars = E->Scalars.size(); 6686 6687 unsigned Offset = *getInsertIndex(VL0); 6688 assert(Offset < NumElts && "Failed to find vector index offset"); 6689 6690 // Create shuffle to resize vector 6691 SmallVector<int> Mask; 6692 if (!E->ReorderIndices.empty()) { 6693 inversePermutation(E->ReorderIndices, Mask); 6694 Mask.append(NumElts - NumScalars, UndefMaskElem); 6695 } else { 6696 Mask.assign(NumElts, UndefMaskElem); 6697 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 6698 } 6699 // Create InsertVector shuffle if necessary 6700 bool IsIdentity = true; 6701 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 6702 Mask.swap(PrevMask); 6703 for (unsigned I = 0; I < NumScalars; ++I) { 6704 Value *Scalar = E->Scalars[PrevMask[I]]; 6705 unsigned InsertIdx = *getInsertIndex(Scalar); 6706 IsIdentity &= InsertIdx - Offset == I; 6707 Mask[InsertIdx - Offset] = I; 6708 } 6709 if (!IsIdentity || NumElts != NumScalars) { 6710 V = Builder.CreateShuffleVector(V, Mask); 6711 if (auto *I = dyn_cast<Instruction>(V)) { 6712 GatherShuffleSeq.insert(I); 6713 CSEBlocks.insert(I->getParent()); 6714 } 6715 } 6716 6717 if ((!IsIdentity || Offset != 0 || 6718 !isUndefVector(FirstInsert->getOperand(0))) && 6719 NumElts != NumScalars) { 6720 SmallVector<int> InsertMask(NumElts); 6721 std::iota(InsertMask.begin(), InsertMask.end(), 0); 6722 for (unsigned I = 0; I < NumElts; I++) { 6723 if (Mask[I] != UndefMaskElem) 6724 InsertMask[Offset + I] = NumElts + I; 6725 } 6726 6727 V = Builder.CreateShuffleVector( 6728 FirstInsert->getOperand(0), V, InsertMask, 6729 cast<Instruction>(E->Scalars.back())->getName()); 6730 if (auto *I = dyn_cast<Instruction>(V)) { 6731 GatherShuffleSeq.insert(I); 6732 CSEBlocks.insert(I->getParent()); 6733 } 6734 } 6735 6736 ++NumVectorInstructions; 6737 E->VectorizedValue = V; 6738 return V; 6739 } 6740 case Instruction::ZExt: 6741 case Instruction::SExt: 6742 case Instruction::FPToUI: 6743 case Instruction::FPToSI: 6744 case Instruction::FPExt: 6745 case Instruction::PtrToInt: 6746 case Instruction::IntToPtr: 6747 case Instruction::SIToFP: 6748 case Instruction::UIToFP: 6749 case Instruction::Trunc: 6750 case Instruction::FPTrunc: 6751 case Instruction::BitCast: { 6752 setInsertPointAfterBundle(E); 6753 6754 Value *InVec = vectorizeTree(E->getOperand(0)); 6755 6756 if (E->VectorizedValue) { 6757 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6758 return E->VectorizedValue; 6759 } 6760 6761 auto *CI = cast<CastInst>(VL0); 6762 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 6763 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6764 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6765 V = ShuffleBuilder.finalize(V); 6766 6767 E->VectorizedValue = V; 6768 ++NumVectorInstructions; 6769 return V; 6770 } 6771 case Instruction::FCmp: 6772 case Instruction::ICmp: { 6773 setInsertPointAfterBundle(E); 6774 6775 Value *L = vectorizeTree(E->getOperand(0)); 6776 Value *R = vectorizeTree(E->getOperand(1)); 6777 6778 if (E->VectorizedValue) { 6779 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6780 return E->VectorizedValue; 6781 } 6782 6783 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 6784 Value *V = Builder.CreateCmp(P0, L, R); 6785 propagateIRFlags(V, E->Scalars, VL0); 6786 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6787 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6788 V = ShuffleBuilder.finalize(V); 6789 6790 E->VectorizedValue = V; 6791 ++NumVectorInstructions; 6792 return V; 6793 } 6794 case Instruction::Select: { 6795 setInsertPointAfterBundle(E); 6796 6797 Value *Cond = vectorizeTree(E->getOperand(0)); 6798 Value *True = vectorizeTree(E->getOperand(1)); 6799 Value *False = vectorizeTree(E->getOperand(2)); 6800 6801 if (E->VectorizedValue) { 6802 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6803 return E->VectorizedValue; 6804 } 6805 6806 Value *V = Builder.CreateSelect(Cond, True, False); 6807 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6808 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6809 V = ShuffleBuilder.finalize(V); 6810 6811 E->VectorizedValue = V; 6812 ++NumVectorInstructions; 6813 return V; 6814 } 6815 case Instruction::FNeg: { 6816 setInsertPointAfterBundle(E); 6817 6818 Value *Op = vectorizeTree(E->getOperand(0)); 6819 6820 if (E->VectorizedValue) { 6821 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6822 return E->VectorizedValue; 6823 } 6824 6825 Value *V = Builder.CreateUnOp( 6826 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 6827 propagateIRFlags(V, E->Scalars, VL0); 6828 if (auto *I = dyn_cast<Instruction>(V)) 6829 V = propagateMetadata(I, E->Scalars); 6830 6831 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6832 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6833 V = ShuffleBuilder.finalize(V); 6834 6835 E->VectorizedValue = V; 6836 ++NumVectorInstructions; 6837 6838 return V; 6839 } 6840 case Instruction::Add: 6841 case Instruction::FAdd: 6842 case Instruction::Sub: 6843 case Instruction::FSub: 6844 case Instruction::Mul: 6845 case Instruction::FMul: 6846 case Instruction::UDiv: 6847 case Instruction::SDiv: 6848 case Instruction::FDiv: 6849 case Instruction::URem: 6850 case Instruction::SRem: 6851 case Instruction::FRem: 6852 case Instruction::Shl: 6853 case Instruction::LShr: 6854 case Instruction::AShr: 6855 case Instruction::And: 6856 case Instruction::Or: 6857 case Instruction::Xor: { 6858 setInsertPointAfterBundle(E); 6859 6860 Value *LHS = vectorizeTree(E->getOperand(0)); 6861 Value *RHS = vectorizeTree(E->getOperand(1)); 6862 6863 if (E->VectorizedValue) { 6864 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6865 return E->VectorizedValue; 6866 } 6867 6868 Value *V = Builder.CreateBinOp( 6869 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 6870 RHS); 6871 propagateIRFlags(V, E->Scalars, VL0); 6872 if (auto *I = dyn_cast<Instruction>(V)) 6873 V = propagateMetadata(I, E->Scalars); 6874 6875 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6876 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6877 V = ShuffleBuilder.finalize(V); 6878 6879 E->VectorizedValue = V; 6880 ++NumVectorInstructions; 6881 6882 return V; 6883 } 6884 case Instruction::Load: { 6885 // Loads are inserted at the head of the tree because we don't want to 6886 // sink them all the way down past store instructions. 6887 setInsertPointAfterBundle(E); 6888 6889 LoadInst *LI = cast<LoadInst>(VL0); 6890 Instruction *NewLI; 6891 unsigned AS = LI->getPointerAddressSpace(); 6892 Value *PO = LI->getPointerOperand(); 6893 if (E->State == TreeEntry::Vectorize) { 6894 6895 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); 6896 6897 // The pointer operand uses an in-tree scalar so we add the new BitCast 6898 // to ExternalUses list to make sure that an extract will be generated 6899 // in the future. 6900 if (TreeEntry *Entry = getTreeEntry(PO)) { 6901 // Find which lane we need to extract. 6902 unsigned FoundLane = Entry->findLaneForValue(PO); 6903 ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane); 6904 } 6905 6906 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); 6907 } else { 6908 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state"); 6909 Value *VecPtr = vectorizeTree(E->getOperand(0)); 6910 // Use the minimum alignment of the gathered loads. 6911 Align CommonAlignment = LI->getAlign(); 6912 for (Value *V : E->Scalars) 6913 CommonAlignment = 6914 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 6915 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); 6916 } 6917 Value *V = propagateMetadata(NewLI, E->Scalars); 6918 6919 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6920 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6921 V = ShuffleBuilder.finalize(V); 6922 E->VectorizedValue = V; 6923 ++NumVectorInstructions; 6924 return V; 6925 } 6926 case Instruction::Store: { 6927 auto *SI = cast<StoreInst>(VL0); 6928 unsigned AS = SI->getPointerAddressSpace(); 6929 6930 setInsertPointAfterBundle(E); 6931 6932 Value *VecValue = vectorizeTree(E->getOperand(0)); 6933 ShuffleBuilder.addMask(E->ReorderIndices); 6934 VecValue = ShuffleBuilder.finalize(VecValue); 6935 6936 Value *ScalarPtr = SI->getPointerOperand(); 6937 Value *VecPtr = Builder.CreateBitCast( 6938 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 6939 StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr, 6940 SI->getAlign()); 6941 6942 // The pointer operand uses an in-tree scalar, so add the new BitCast to 6943 // ExternalUses to make sure that an extract will be generated in the 6944 // future. 6945 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { 6946 // Find which lane we need to extract. 6947 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); 6948 ExternalUses.push_back( 6949 ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane)); 6950 } 6951 6952 Value *V = propagateMetadata(ST, E->Scalars); 6953 6954 E->VectorizedValue = V; 6955 ++NumVectorInstructions; 6956 return V; 6957 } 6958 case Instruction::GetElementPtr: { 6959 auto *GEP0 = cast<GetElementPtrInst>(VL0); 6960 setInsertPointAfterBundle(E); 6961 6962 Value *Op0 = vectorizeTree(E->getOperand(0)); 6963 6964 SmallVector<Value *> OpVecs; 6965 for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) { 6966 Value *OpVec = vectorizeTree(E->getOperand(J)); 6967 OpVecs.push_back(OpVec); 6968 } 6969 6970 Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs); 6971 if (Instruction *I = dyn_cast<Instruction>(V)) 6972 V = propagateMetadata(I, E->Scalars); 6973 6974 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6975 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6976 V = ShuffleBuilder.finalize(V); 6977 6978 E->VectorizedValue = V; 6979 ++NumVectorInstructions; 6980 6981 return V; 6982 } 6983 case Instruction::Call: { 6984 CallInst *CI = cast<CallInst>(VL0); 6985 setInsertPointAfterBundle(E); 6986 6987 Intrinsic::ID IID = Intrinsic::not_intrinsic; 6988 if (Function *FI = CI->getCalledFunction()) 6989 IID = FI->getIntrinsicID(); 6990 6991 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 6992 6993 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 6994 bool UseIntrinsic = ID != Intrinsic::not_intrinsic && 6995 VecCallCosts.first <= VecCallCosts.second; 6996 6997 Value *ScalarArg = nullptr; 6998 std::vector<Value *> OpVecs; 6999 SmallVector<Type *, 2> TysForDecl = 7000 {FixedVectorType::get(CI->getType(), E->Scalars.size())}; 7001 for (int j = 0, e = CI->arg_size(); j < e; ++j) { 7002 ValueList OpVL; 7003 // Some intrinsics have scalar arguments. This argument should not be 7004 // vectorized. 7005 if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) { 7006 CallInst *CEI = cast<CallInst>(VL0); 7007 ScalarArg = CEI->getArgOperand(j); 7008 OpVecs.push_back(CEI->getArgOperand(j)); 7009 if (hasVectorInstrinsicOverloadedScalarOpd(IID, j)) 7010 TysForDecl.push_back(ScalarArg->getType()); 7011 continue; 7012 } 7013 7014 Value *OpVec = vectorizeTree(E->getOperand(j)); 7015 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 7016 OpVecs.push_back(OpVec); 7017 } 7018 7019 Function *CF; 7020 if (!UseIntrinsic) { 7021 VFShape Shape = 7022 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 7023 VecTy->getNumElements())), 7024 false /*HasGlobalPred*/); 7025 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 7026 } else { 7027 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); 7028 } 7029 7030 SmallVector<OperandBundleDef, 1> OpBundles; 7031 CI->getOperandBundlesAsDefs(OpBundles); 7032 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 7033 7034 // The scalar argument uses an in-tree scalar so we add the new vectorized 7035 // call to ExternalUses list to make sure that an extract will be 7036 // generated in the future. 7037 if (ScalarArg) { 7038 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { 7039 // Find which lane we need to extract. 7040 unsigned FoundLane = Entry->findLaneForValue(ScalarArg); 7041 ExternalUses.push_back( 7042 ExternalUser(ScalarArg, cast<User>(V), FoundLane)); 7043 } 7044 } 7045 7046 propagateIRFlags(V, E->Scalars, VL0); 7047 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7048 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7049 V = ShuffleBuilder.finalize(V); 7050 7051 E->VectorizedValue = V; 7052 ++NumVectorInstructions; 7053 return V; 7054 } 7055 case Instruction::ShuffleVector: { 7056 assert(E->isAltShuffle() && 7057 ((Instruction::isBinaryOp(E->getOpcode()) && 7058 Instruction::isBinaryOp(E->getAltOpcode())) || 7059 (Instruction::isCast(E->getOpcode()) && 7060 Instruction::isCast(E->getAltOpcode())) || 7061 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 7062 "Invalid Shuffle Vector Operand"); 7063 7064 Value *LHS = nullptr, *RHS = nullptr; 7065 if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) { 7066 setInsertPointAfterBundle(E); 7067 LHS = vectorizeTree(E->getOperand(0)); 7068 RHS = vectorizeTree(E->getOperand(1)); 7069 } else { 7070 setInsertPointAfterBundle(E); 7071 LHS = vectorizeTree(E->getOperand(0)); 7072 } 7073 7074 if (E->VectorizedValue) { 7075 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7076 return E->VectorizedValue; 7077 } 7078 7079 Value *V0, *V1; 7080 if (Instruction::isBinaryOp(E->getOpcode())) { 7081 V0 = Builder.CreateBinOp( 7082 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 7083 V1 = Builder.CreateBinOp( 7084 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 7085 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 7086 V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS); 7087 auto *AltCI = cast<CmpInst>(E->getAltOp()); 7088 CmpInst::Predicate AltPred = AltCI->getPredicate(); 7089 V1 = Builder.CreateCmp(AltPred, LHS, RHS); 7090 } else { 7091 V0 = Builder.CreateCast( 7092 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 7093 V1 = Builder.CreateCast( 7094 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 7095 } 7096 // Add V0 and V1 to later analysis to try to find and remove matching 7097 // instruction, if any. 7098 for (Value *V : {V0, V1}) { 7099 if (auto *I = dyn_cast<Instruction>(V)) { 7100 GatherShuffleSeq.insert(I); 7101 CSEBlocks.insert(I->getParent()); 7102 } 7103 } 7104 7105 // Create shuffle to take alternate operations from the vector. 7106 // Also, gather up main and alt scalar ops to propagate IR flags to 7107 // each vector operation. 7108 ValueList OpScalars, AltScalars; 7109 SmallVector<int> Mask; 7110 buildShuffleEntryMask( 7111 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 7112 [E](Instruction *I) { 7113 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 7114 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp()); 7115 }, 7116 Mask, &OpScalars, &AltScalars); 7117 7118 propagateIRFlags(V0, OpScalars); 7119 propagateIRFlags(V1, AltScalars); 7120 7121 Value *V = Builder.CreateShuffleVector(V0, V1, Mask); 7122 if (auto *I = dyn_cast<Instruction>(V)) { 7123 V = propagateMetadata(I, E->Scalars); 7124 GatherShuffleSeq.insert(I); 7125 CSEBlocks.insert(I->getParent()); 7126 } 7127 V = ShuffleBuilder.finalize(V); 7128 7129 E->VectorizedValue = V; 7130 ++NumVectorInstructions; 7131 7132 return V; 7133 } 7134 default: 7135 llvm_unreachable("unknown inst"); 7136 } 7137 return nullptr; 7138 } 7139 7140 Value *BoUpSLP::vectorizeTree() { 7141 ExtraValueToDebugLocsMap ExternallyUsedValues; 7142 return vectorizeTree(ExternallyUsedValues); 7143 } 7144 7145 Value * 7146 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 7147 // All blocks must be scheduled before any instructions are inserted. 7148 for (auto &BSIter : BlocksSchedules) { 7149 scheduleBlock(BSIter.second.get()); 7150 } 7151 7152 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7153 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 7154 7155 // If the vectorized tree can be rewritten in a smaller type, we truncate the 7156 // vectorized root. InstCombine will then rewrite the entire expression. We 7157 // sign extend the extracted values below. 7158 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 7159 if (MinBWs.count(ScalarRoot)) { 7160 if (auto *I = dyn_cast<Instruction>(VectorRoot)) { 7161 // If current instr is a phi and not the last phi, insert it after the 7162 // last phi node. 7163 if (isa<PHINode>(I)) 7164 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); 7165 else 7166 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 7167 } 7168 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 7169 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 7170 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); 7171 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 7172 VectorizableTree[0]->VectorizedValue = Trunc; 7173 } 7174 7175 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 7176 << " values .\n"); 7177 7178 // Extract all of the elements with the external uses. 7179 for (const auto &ExternalUse : ExternalUses) { 7180 Value *Scalar = ExternalUse.Scalar; 7181 llvm::User *User = ExternalUse.User; 7182 7183 // Skip users that we already RAUW. This happens when one instruction 7184 // has multiple uses of the same value. 7185 if (User && !is_contained(Scalar->users(), User)) 7186 continue; 7187 TreeEntry *E = getTreeEntry(Scalar); 7188 assert(E && "Invalid scalar"); 7189 assert(E->State != TreeEntry::NeedToGather && 7190 "Extracting from a gather list"); 7191 7192 Value *Vec = E->VectorizedValue; 7193 assert(Vec && "Can't find vectorizable value"); 7194 7195 Value *Lane = Builder.getInt32(ExternalUse.Lane); 7196 auto ExtractAndExtendIfNeeded = [&](Value *Vec) { 7197 if (Scalar->getType() != Vec->getType()) { 7198 Value *Ex; 7199 // "Reuse" the existing extract to improve final codegen. 7200 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { 7201 Ex = Builder.CreateExtractElement(ES->getOperand(0), 7202 ES->getOperand(1)); 7203 } else { 7204 Ex = Builder.CreateExtractElement(Vec, Lane); 7205 } 7206 // If necessary, sign-extend or zero-extend ScalarRoot 7207 // to the larger type. 7208 if (!MinBWs.count(ScalarRoot)) 7209 return Ex; 7210 if (MinBWs[ScalarRoot].second) 7211 return Builder.CreateSExt(Ex, Scalar->getType()); 7212 return Builder.CreateZExt(Ex, Scalar->getType()); 7213 } 7214 assert(isa<FixedVectorType>(Scalar->getType()) && 7215 isa<InsertElementInst>(Scalar) && 7216 "In-tree scalar of vector type is not insertelement?"); 7217 return Vec; 7218 }; 7219 // If User == nullptr, the Scalar is used as extra arg. Generate 7220 // ExtractElement instruction and update the record for this scalar in 7221 // ExternallyUsedValues. 7222 if (!User) { 7223 assert(ExternallyUsedValues.count(Scalar) && 7224 "Scalar with nullptr as an external user must be registered in " 7225 "ExternallyUsedValues map"); 7226 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7227 Builder.SetInsertPoint(VecI->getParent(), 7228 std::next(VecI->getIterator())); 7229 } else { 7230 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7231 } 7232 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7233 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 7234 auto &NewInstLocs = ExternallyUsedValues[NewInst]; 7235 auto It = ExternallyUsedValues.find(Scalar); 7236 assert(It != ExternallyUsedValues.end() && 7237 "Externally used scalar is not found in ExternallyUsedValues"); 7238 NewInstLocs.append(It->second); 7239 ExternallyUsedValues.erase(Scalar); 7240 // Required to update internally referenced instructions. 7241 Scalar->replaceAllUsesWith(NewInst); 7242 continue; 7243 } 7244 7245 // Generate extracts for out-of-tree users. 7246 // Find the insertion point for the extractelement lane. 7247 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7248 if (PHINode *PH = dyn_cast<PHINode>(User)) { 7249 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 7250 if (PH->getIncomingValue(i) == Scalar) { 7251 Instruction *IncomingTerminator = 7252 PH->getIncomingBlock(i)->getTerminator(); 7253 if (isa<CatchSwitchInst>(IncomingTerminator)) { 7254 Builder.SetInsertPoint(VecI->getParent(), 7255 std::next(VecI->getIterator())); 7256 } else { 7257 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 7258 } 7259 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7260 CSEBlocks.insert(PH->getIncomingBlock(i)); 7261 PH->setOperand(i, NewInst); 7262 } 7263 } 7264 } else { 7265 Builder.SetInsertPoint(cast<Instruction>(User)); 7266 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7267 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 7268 User->replaceUsesOfWith(Scalar, NewInst); 7269 } 7270 } else { 7271 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7272 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7273 CSEBlocks.insert(&F->getEntryBlock()); 7274 User->replaceUsesOfWith(Scalar, NewInst); 7275 } 7276 7277 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 7278 } 7279 7280 // For each vectorized value: 7281 for (auto &TEPtr : VectorizableTree) { 7282 TreeEntry *Entry = TEPtr.get(); 7283 7284 // No need to handle users of gathered values. 7285 if (Entry->State == TreeEntry::NeedToGather) 7286 continue; 7287 7288 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 7289 7290 // For each lane: 7291 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 7292 Value *Scalar = Entry->Scalars[Lane]; 7293 7294 #ifndef NDEBUG 7295 Type *Ty = Scalar->getType(); 7296 if (!Ty->isVoidTy()) { 7297 for (User *U : Scalar->users()) { 7298 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 7299 7300 // It is legal to delete users in the ignorelist. 7301 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) || 7302 (isa_and_nonnull<Instruction>(U) && 7303 isDeleted(cast<Instruction>(U)))) && 7304 "Deleting out-of-tree value"); 7305 } 7306 } 7307 #endif 7308 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 7309 eraseInstruction(cast<Instruction>(Scalar)); 7310 } 7311 } 7312 7313 Builder.ClearInsertionPoint(); 7314 InstrElementSize.clear(); 7315 7316 return VectorizableTree[0]->VectorizedValue; 7317 } 7318 7319 void BoUpSLP::optimizeGatherSequence() { 7320 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size() 7321 << " gather sequences instructions.\n"); 7322 // LICM InsertElementInst sequences. 7323 for (Instruction *I : GatherShuffleSeq) { 7324 if (isDeleted(I)) 7325 continue; 7326 7327 // Check if this block is inside a loop. 7328 Loop *L = LI->getLoopFor(I->getParent()); 7329 if (!L) 7330 continue; 7331 7332 // Check if it has a preheader. 7333 BasicBlock *PreHeader = L->getLoopPreheader(); 7334 if (!PreHeader) 7335 continue; 7336 7337 // If the vector or the element that we insert into it are 7338 // instructions that are defined in this basic block then we can't 7339 // hoist this instruction. 7340 if (any_of(I->operands(), [L](Value *V) { 7341 auto *OpI = dyn_cast<Instruction>(V); 7342 return OpI && L->contains(OpI); 7343 })) 7344 continue; 7345 7346 // We can hoist this instruction. Move it to the pre-header. 7347 I->moveBefore(PreHeader->getTerminator()); 7348 } 7349 7350 // Make a list of all reachable blocks in our CSE queue. 7351 SmallVector<const DomTreeNode *, 8> CSEWorkList; 7352 CSEWorkList.reserve(CSEBlocks.size()); 7353 for (BasicBlock *BB : CSEBlocks) 7354 if (DomTreeNode *N = DT->getNode(BB)) { 7355 assert(DT->isReachableFromEntry(N)); 7356 CSEWorkList.push_back(N); 7357 } 7358 7359 // Sort blocks by domination. This ensures we visit a block after all blocks 7360 // dominating it are visited. 7361 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { 7362 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && 7363 "Different nodes should have different DFS numbers"); 7364 return A->getDFSNumIn() < B->getDFSNumIn(); 7365 }); 7366 7367 // Less defined shuffles can be replaced by the more defined copies. 7368 // Between two shuffles one is less defined if it has the same vector operands 7369 // and its mask indeces are the same as in the first one or undefs. E.g. 7370 // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0, 7371 // poison, <0, 0, 0, 0>. 7372 auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2, 7373 SmallVectorImpl<int> &NewMask) { 7374 if (I1->getType() != I2->getType()) 7375 return false; 7376 auto *SI1 = dyn_cast<ShuffleVectorInst>(I1); 7377 auto *SI2 = dyn_cast<ShuffleVectorInst>(I2); 7378 if (!SI1 || !SI2) 7379 return I1->isIdenticalTo(I2); 7380 if (SI1->isIdenticalTo(SI2)) 7381 return true; 7382 for (int I = 0, E = SI1->getNumOperands(); I < E; ++I) 7383 if (SI1->getOperand(I) != SI2->getOperand(I)) 7384 return false; 7385 // Check if the second instruction is more defined than the first one. 7386 NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end()); 7387 ArrayRef<int> SM1 = SI1->getShuffleMask(); 7388 // Count trailing undefs in the mask to check the final number of used 7389 // registers. 7390 unsigned LastUndefsCnt = 0; 7391 for (int I = 0, E = NewMask.size(); I < E; ++I) { 7392 if (SM1[I] == UndefMaskElem) 7393 ++LastUndefsCnt; 7394 else 7395 LastUndefsCnt = 0; 7396 if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem && 7397 NewMask[I] != SM1[I]) 7398 return false; 7399 if (NewMask[I] == UndefMaskElem) 7400 NewMask[I] = SM1[I]; 7401 } 7402 // Check if the last undefs actually change the final number of used vector 7403 // registers. 7404 return SM1.size() - LastUndefsCnt > 1 && 7405 TTI->getNumberOfParts(SI1->getType()) == 7406 TTI->getNumberOfParts( 7407 FixedVectorType::get(SI1->getType()->getElementType(), 7408 SM1.size() - LastUndefsCnt)); 7409 }; 7410 // Perform O(N^2) search over the gather/shuffle sequences and merge identical 7411 // instructions. TODO: We can further optimize this scan if we split the 7412 // instructions into different buckets based on the insert lane. 7413 SmallVector<Instruction *, 16> Visited; 7414 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 7415 assert(*I && 7416 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 7417 "Worklist not sorted properly!"); 7418 BasicBlock *BB = (*I)->getBlock(); 7419 // For all instructions in blocks containing gather sequences: 7420 for (Instruction &In : llvm::make_early_inc_range(*BB)) { 7421 if (isDeleted(&In)) 7422 continue; 7423 if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) && 7424 !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In)) 7425 continue; 7426 7427 // Check if we can replace this instruction with any of the 7428 // visited instructions. 7429 bool Replaced = false; 7430 for (Instruction *&V : Visited) { 7431 SmallVector<int> NewMask; 7432 if (IsIdenticalOrLessDefined(&In, V, NewMask) && 7433 DT->dominates(V->getParent(), In.getParent())) { 7434 In.replaceAllUsesWith(V); 7435 eraseInstruction(&In); 7436 if (auto *SI = dyn_cast<ShuffleVectorInst>(V)) 7437 if (!NewMask.empty()) 7438 SI->setShuffleMask(NewMask); 7439 Replaced = true; 7440 break; 7441 } 7442 if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) && 7443 GatherShuffleSeq.contains(V) && 7444 IsIdenticalOrLessDefined(V, &In, NewMask) && 7445 DT->dominates(In.getParent(), V->getParent())) { 7446 In.moveAfter(V); 7447 V->replaceAllUsesWith(&In); 7448 eraseInstruction(V); 7449 if (auto *SI = dyn_cast<ShuffleVectorInst>(&In)) 7450 if (!NewMask.empty()) 7451 SI->setShuffleMask(NewMask); 7452 V = &In; 7453 Replaced = true; 7454 break; 7455 } 7456 } 7457 if (!Replaced) { 7458 assert(!is_contained(Visited, &In)); 7459 Visited.push_back(&In); 7460 } 7461 } 7462 } 7463 CSEBlocks.clear(); 7464 GatherShuffleSeq.clear(); 7465 } 7466 7467 BoUpSLP::ScheduleData * 7468 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) { 7469 ScheduleData *Bundle = nullptr; 7470 ScheduleData *PrevInBundle = nullptr; 7471 for (Value *V : VL) { 7472 ScheduleData *BundleMember = getScheduleData(V); 7473 assert(BundleMember && 7474 "no ScheduleData for bundle member " 7475 "(maybe not in same basic block)"); 7476 assert(BundleMember->isSchedulingEntity() && 7477 "bundle member already part of other bundle"); 7478 if (PrevInBundle) { 7479 PrevInBundle->NextInBundle = BundleMember; 7480 } else { 7481 Bundle = BundleMember; 7482 } 7483 7484 // Group the instructions to a bundle. 7485 BundleMember->FirstInBundle = Bundle; 7486 PrevInBundle = BundleMember; 7487 } 7488 assert(Bundle && "Failed to find schedule bundle"); 7489 return Bundle; 7490 } 7491 7492 // Groups the instructions to a bundle (which is then a single scheduling entity) 7493 // and schedules instructions until the bundle gets ready. 7494 Optional<BoUpSLP::ScheduleData *> 7495 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 7496 const InstructionsState &S) { 7497 // No need to schedule PHIs, insertelement, extractelement and extractvalue 7498 // instructions. 7499 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue)) 7500 return nullptr; 7501 7502 // Initialize the instruction bundle. 7503 Instruction *OldScheduleEnd = ScheduleEnd; 7504 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 7505 7506 auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule, 7507 ScheduleData *Bundle) { 7508 // The scheduling region got new instructions at the lower end (or it is a 7509 // new region for the first bundle). This makes it necessary to 7510 // recalculate all dependencies. 7511 // It is seldom that this needs to be done a second time after adding the 7512 // initial bundle to the region. 7513 if (ScheduleEnd != OldScheduleEnd) { 7514 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) 7515 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); 7516 ReSchedule = true; 7517 } 7518 if (Bundle) { 7519 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle 7520 << " in block " << BB->getName() << "\n"); 7521 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); 7522 } 7523 7524 if (ReSchedule) { 7525 resetSchedule(); 7526 initialFillReadyList(ReadyInsts); 7527 } 7528 7529 // Now try to schedule the new bundle or (if no bundle) just calculate 7530 // dependencies. As soon as the bundle is "ready" it means that there are no 7531 // cyclic dependencies and we can schedule it. Note that's important that we 7532 // don't "schedule" the bundle yet (see cancelScheduling). 7533 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && 7534 !ReadyInsts.empty()) { 7535 ScheduleData *Picked = ReadyInsts.pop_back_val(); 7536 assert(Picked->isSchedulingEntity() && Picked->isReady() && 7537 "must be ready to schedule"); 7538 schedule(Picked, ReadyInsts); 7539 } 7540 }; 7541 7542 // Make sure that the scheduling region contains all 7543 // instructions of the bundle. 7544 for (Value *V : VL) { 7545 if (!extendSchedulingRegion(V, S)) { 7546 // If the scheduling region got new instructions at the lower end (or it 7547 // is a new region for the first bundle). This makes it necessary to 7548 // recalculate all dependencies. 7549 // Otherwise the compiler may crash trying to incorrectly calculate 7550 // dependencies and emit instruction in the wrong order at the actual 7551 // scheduling. 7552 TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr); 7553 return None; 7554 } 7555 } 7556 7557 bool ReSchedule = false; 7558 for (Value *V : VL) { 7559 ScheduleData *BundleMember = getScheduleData(V); 7560 assert(BundleMember && 7561 "no ScheduleData for bundle member (maybe not in same basic block)"); 7562 7563 // Make sure we don't leave the pieces of the bundle in the ready list when 7564 // whole bundle might not be ready. 7565 ReadyInsts.remove(BundleMember); 7566 7567 if (!BundleMember->IsScheduled) 7568 continue; 7569 // A bundle member was scheduled as single instruction before and now 7570 // needs to be scheduled as part of the bundle. We just get rid of the 7571 // existing schedule. 7572 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 7573 << " was already scheduled\n"); 7574 ReSchedule = true; 7575 } 7576 7577 auto *Bundle = buildBundle(VL); 7578 TryScheduleBundleImpl(ReSchedule, Bundle); 7579 if (!Bundle->isReady()) { 7580 cancelScheduling(VL, S.OpValue); 7581 return None; 7582 } 7583 return Bundle; 7584 } 7585 7586 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 7587 Value *OpValue) { 7588 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue)) 7589 return; 7590 7591 ScheduleData *Bundle = getScheduleData(OpValue); 7592 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 7593 assert(!Bundle->IsScheduled && 7594 "Can't cancel bundle which is already scheduled"); 7595 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() && 7596 "tried to unbundle something which is not a bundle"); 7597 7598 // Remove the bundle from the ready list. 7599 if (Bundle->isReady()) 7600 ReadyInsts.remove(Bundle); 7601 7602 // Un-bundle: make single instructions out of the bundle. 7603 ScheduleData *BundleMember = Bundle; 7604 while (BundleMember) { 7605 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 7606 BundleMember->FirstInBundle = BundleMember; 7607 ScheduleData *Next = BundleMember->NextInBundle; 7608 BundleMember->NextInBundle = nullptr; 7609 if (BundleMember->unscheduledDepsInBundle() == 0) { 7610 ReadyInsts.insert(BundleMember); 7611 } 7612 BundleMember = Next; 7613 } 7614 } 7615 7616 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 7617 // Allocate a new ScheduleData for the instruction. 7618 if (ChunkPos >= ChunkSize) { 7619 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 7620 ChunkPos = 0; 7621 } 7622 return &(ScheduleDataChunks.back()[ChunkPos++]); 7623 } 7624 7625 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 7626 const InstructionsState &S) { 7627 if (getScheduleData(V, isOneOf(S, V))) 7628 return true; 7629 Instruction *I = dyn_cast<Instruction>(V); 7630 assert(I && "bundle member must be an instruction"); 7631 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && 7632 "phi nodes/insertelements/extractelements/extractvalues don't need to " 7633 "be scheduled"); 7634 auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool { 7635 ScheduleData *ISD = getScheduleData(I); 7636 if (!ISD) 7637 return false; 7638 assert(isInSchedulingRegion(ISD) && 7639 "ScheduleData not in scheduling region"); 7640 ScheduleData *SD = allocateScheduleDataChunks(); 7641 SD->Inst = I; 7642 SD->init(SchedulingRegionID, S.OpValue); 7643 ExtraScheduleDataMap[I][S.OpValue] = SD; 7644 return true; 7645 }; 7646 if (CheckSheduleForI(I)) 7647 return true; 7648 if (!ScheduleStart) { 7649 // It's the first instruction in the new region. 7650 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 7651 ScheduleStart = I; 7652 ScheduleEnd = I->getNextNode(); 7653 if (isOneOf(S, I) != I) 7654 CheckSheduleForI(I); 7655 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7656 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 7657 return true; 7658 } 7659 // Search up and down at the same time, because we don't know if the new 7660 // instruction is above or below the existing scheduling region. 7661 BasicBlock::reverse_iterator UpIter = 7662 ++ScheduleStart->getIterator().getReverse(); 7663 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 7664 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 7665 BasicBlock::iterator LowerEnd = BB->end(); 7666 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && 7667 &*DownIter != I) { 7668 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 7669 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 7670 return false; 7671 } 7672 7673 ++UpIter; 7674 ++DownIter; 7675 } 7676 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { 7677 assert(I->getParent() == ScheduleStart->getParent() && 7678 "Instruction is in wrong basic block."); 7679 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 7680 ScheduleStart = I; 7681 if (isOneOf(S, I) != I) 7682 CheckSheduleForI(I); 7683 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 7684 << "\n"); 7685 return true; 7686 } 7687 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && 7688 "Expected to reach top of the basic block or instruction down the " 7689 "lower end."); 7690 assert(I->getParent() == ScheduleEnd->getParent() && 7691 "Instruction is in wrong basic block."); 7692 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 7693 nullptr); 7694 ScheduleEnd = I->getNextNode(); 7695 if (isOneOf(S, I) != I) 7696 CheckSheduleForI(I); 7697 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7698 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 7699 return true; 7700 } 7701 7702 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 7703 Instruction *ToI, 7704 ScheduleData *PrevLoadStore, 7705 ScheduleData *NextLoadStore) { 7706 ScheduleData *CurrentLoadStore = PrevLoadStore; 7707 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 7708 ScheduleData *SD = ScheduleDataMap[I]; 7709 if (!SD) { 7710 SD = allocateScheduleDataChunks(); 7711 ScheduleDataMap[I] = SD; 7712 SD->Inst = I; 7713 } 7714 assert(!isInSchedulingRegion(SD) && 7715 "new ScheduleData already in scheduling region"); 7716 SD->init(SchedulingRegionID, I); 7717 7718 if (I->mayReadOrWriteMemory() && 7719 (!isa<IntrinsicInst>(I) || 7720 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && 7721 cast<IntrinsicInst>(I)->getIntrinsicID() != 7722 Intrinsic::pseudoprobe))) { 7723 // Update the linked list of memory accessing instructions. 7724 if (CurrentLoadStore) { 7725 CurrentLoadStore->NextLoadStore = SD; 7726 } else { 7727 FirstLoadStoreInRegion = SD; 7728 } 7729 CurrentLoadStore = SD; 7730 } 7731 } 7732 if (NextLoadStore) { 7733 if (CurrentLoadStore) 7734 CurrentLoadStore->NextLoadStore = NextLoadStore; 7735 } else { 7736 LastLoadStoreInRegion = CurrentLoadStore; 7737 } 7738 } 7739 7740 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 7741 bool InsertInReadyList, 7742 BoUpSLP *SLP) { 7743 assert(SD->isSchedulingEntity()); 7744 7745 SmallVector<ScheduleData *, 10> WorkList; 7746 WorkList.push_back(SD); 7747 7748 while (!WorkList.empty()) { 7749 ScheduleData *SD = WorkList.pop_back_val(); 7750 for (ScheduleData *BundleMember = SD; BundleMember; 7751 BundleMember = BundleMember->NextInBundle) { 7752 assert(isInSchedulingRegion(BundleMember)); 7753 if (BundleMember->hasValidDependencies()) 7754 continue; 7755 7756 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 7757 << "\n"); 7758 BundleMember->Dependencies = 0; 7759 BundleMember->resetUnscheduledDeps(); 7760 7761 // Handle def-use chain dependencies. 7762 if (BundleMember->OpValue != BundleMember->Inst) { 7763 ScheduleData *UseSD = getScheduleData(BundleMember->Inst); 7764 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 7765 BundleMember->Dependencies++; 7766 ScheduleData *DestBundle = UseSD->FirstInBundle; 7767 if (!DestBundle->IsScheduled) 7768 BundleMember->incrementUnscheduledDeps(1); 7769 if (!DestBundle->hasValidDependencies()) 7770 WorkList.push_back(DestBundle); 7771 } 7772 } else { 7773 for (User *U : BundleMember->Inst->users()) { 7774 assert(isa<Instruction>(U) && 7775 "user of instruction must be instruction"); 7776 ScheduleData *UseSD = getScheduleData(U); 7777 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 7778 BundleMember->Dependencies++; 7779 ScheduleData *DestBundle = UseSD->FirstInBundle; 7780 if (!DestBundle->IsScheduled) 7781 BundleMember->incrementUnscheduledDeps(1); 7782 if (!DestBundle->hasValidDependencies()) 7783 WorkList.push_back(DestBundle); 7784 } 7785 } 7786 } 7787 7788 // Handle the memory dependencies (if any). 7789 ScheduleData *DepDest = BundleMember->NextLoadStore; 7790 if (!DepDest) 7791 continue; 7792 Instruction *SrcInst = BundleMember->Inst; 7793 assert(SrcInst->mayReadOrWriteMemory() && 7794 "NextLoadStore list for non memory effecting bundle?"); 7795 MemoryLocation SrcLoc = getLocation(SrcInst); 7796 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 7797 unsigned numAliased = 0; 7798 unsigned DistToSrc = 1; 7799 7800 for ( ; DepDest; DepDest = DepDest->NextLoadStore) { 7801 assert(isInSchedulingRegion(DepDest)); 7802 7803 // We have two limits to reduce the complexity: 7804 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 7805 // SLP->isAliased (which is the expensive part in this loop). 7806 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 7807 // the whole loop (even if the loop is fast, it's quadratic). 7808 // It's important for the loop break condition (see below) to 7809 // check this limit even between two read-only instructions. 7810 if (DistToSrc >= MaxMemDepDistance || 7811 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 7812 (numAliased >= AliasedCheckLimit || 7813 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 7814 7815 // We increment the counter only if the locations are aliased 7816 // (instead of counting all alias checks). This gives a better 7817 // balance between reduced runtime and accurate dependencies. 7818 numAliased++; 7819 7820 DepDest->MemoryDependencies.push_back(BundleMember); 7821 BundleMember->Dependencies++; 7822 ScheduleData *DestBundle = DepDest->FirstInBundle; 7823 if (!DestBundle->IsScheduled) { 7824 BundleMember->incrementUnscheduledDeps(1); 7825 } 7826 if (!DestBundle->hasValidDependencies()) { 7827 WorkList.push_back(DestBundle); 7828 } 7829 } 7830 7831 // Example, explaining the loop break condition: Let's assume our 7832 // starting instruction is i0 and MaxMemDepDistance = 3. 7833 // 7834 // +--------v--v--v 7835 // i0,i1,i2,i3,i4,i5,i6,i7,i8 7836 // +--------^--^--^ 7837 // 7838 // MaxMemDepDistance let us stop alias-checking at i3 and we add 7839 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 7840 // Previously we already added dependencies from i3 to i6,i7,i8 7841 // (because of MaxMemDepDistance). As we added a dependency from 7842 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 7843 // and we can abort this loop at i6. 7844 if (DistToSrc >= 2 * MaxMemDepDistance) 7845 break; 7846 DistToSrc++; 7847 } 7848 } 7849 if (InsertInReadyList && SD->isReady()) { 7850 ReadyInsts.insert(SD); 7851 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 7852 << "\n"); 7853 } 7854 } 7855 } 7856 7857 void BoUpSLP::BlockScheduling::resetSchedule() { 7858 assert(ScheduleStart && 7859 "tried to reset schedule on block which has not been scheduled"); 7860 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 7861 doForAllOpcodes(I, [&](ScheduleData *SD) { 7862 assert(isInSchedulingRegion(SD) && 7863 "ScheduleData not in scheduling region"); 7864 SD->IsScheduled = false; 7865 SD->resetUnscheduledDeps(); 7866 }); 7867 } 7868 ReadyInsts.clear(); 7869 } 7870 7871 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 7872 if (!BS->ScheduleStart) 7873 return; 7874 7875 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 7876 7877 // A key point - if we got here, pre-scheduling was able to find a valid 7878 // scheduling of the sub-graph of the scheduling window which consists 7879 // of all vector bundles and their transitive users. As such, we do not 7880 // need to reschedule anything *outside of* that subgraph. 7881 7882 BS->resetSchedule(); 7883 7884 // For the real scheduling we use a more sophisticated ready-list: it is 7885 // sorted by the original instruction location. This lets the final schedule 7886 // be as close as possible to the original instruction order. 7887 struct ScheduleDataCompare { 7888 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { 7889 return SD2->SchedulingPriority < SD1->SchedulingPriority; 7890 } 7891 }; 7892 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 7893 7894 // Ensure that all dependency data is updated (for nodes in the sub-graph) 7895 // and fill the ready-list with initial instructions. 7896 int Idx = 0; 7897 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 7898 I = I->getNextNode()) { 7899 BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) { 7900 assert((isVectorLikeInstWithConstOps(SD->Inst) || 7901 SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) && 7902 "scheduler and vectorizer bundle mismatch"); 7903 SD->FirstInBundle->SchedulingPriority = Idx++; 7904 7905 if (SD->isSchedulingEntity() && SD->isPartOfBundle()) 7906 BS->calculateDependencies(SD, false, this); 7907 }); 7908 } 7909 BS->initialFillReadyList(ReadyInsts); 7910 7911 Instruction *LastScheduledInst = BS->ScheduleEnd; 7912 7913 // Do the "real" scheduling. 7914 while (!ReadyInsts.empty()) { 7915 ScheduleData *picked = *ReadyInsts.begin(); 7916 ReadyInsts.erase(ReadyInsts.begin()); 7917 7918 // Move the scheduled instruction(s) to their dedicated places, if not 7919 // there yet. 7920 for (ScheduleData *BundleMember = picked; BundleMember; 7921 BundleMember = BundleMember->NextInBundle) { 7922 Instruction *pickedInst = BundleMember->Inst; 7923 if (pickedInst->getNextNode() != LastScheduledInst) 7924 pickedInst->moveBefore(LastScheduledInst); 7925 LastScheduledInst = pickedInst; 7926 } 7927 7928 BS->schedule(picked, ReadyInsts); 7929 } 7930 7931 // Check that we didn't break any of our invariants. 7932 #ifdef EXPENSIVE_CHECKS 7933 BS->verify(); 7934 #endif 7935 7936 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) 7937 // Check that all schedulable entities got scheduled 7938 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) { 7939 BS->doForAllOpcodes(I, [&](ScheduleData *SD) { 7940 if (SD->isSchedulingEntity() && SD->hasValidDependencies()) { 7941 assert(SD->IsScheduled && "must be scheduled at this point"); 7942 } 7943 }); 7944 } 7945 #endif 7946 7947 // Avoid duplicate scheduling of the block. 7948 BS->ScheduleStart = nullptr; 7949 } 7950 7951 unsigned BoUpSLP::getVectorElementSize(Value *V) { 7952 // If V is a store, just return the width of the stored value (or value 7953 // truncated just before storing) without traversing the expression tree. 7954 // This is the common case. 7955 if (auto *Store = dyn_cast<StoreInst>(V)) { 7956 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) 7957 return DL->getTypeSizeInBits(Trunc->getSrcTy()); 7958 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 7959 } 7960 7961 if (auto *IEI = dyn_cast<InsertElementInst>(V)) 7962 return getVectorElementSize(IEI->getOperand(1)); 7963 7964 auto E = InstrElementSize.find(V); 7965 if (E != InstrElementSize.end()) 7966 return E->second; 7967 7968 // If V is not a store, we can traverse the expression tree to find loads 7969 // that feed it. The type of the loaded value may indicate a more suitable 7970 // width than V's type. We want to base the vector element size on the width 7971 // of memory operations where possible. 7972 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; 7973 SmallPtrSet<Instruction *, 16> Visited; 7974 if (auto *I = dyn_cast<Instruction>(V)) { 7975 Worklist.emplace_back(I, I->getParent()); 7976 Visited.insert(I); 7977 } 7978 7979 // Traverse the expression tree in bottom-up order looking for loads. If we 7980 // encounter an instruction we don't yet handle, we give up. 7981 auto Width = 0u; 7982 while (!Worklist.empty()) { 7983 Instruction *I; 7984 BasicBlock *Parent; 7985 std::tie(I, Parent) = Worklist.pop_back_val(); 7986 7987 // We should only be looking at scalar instructions here. If the current 7988 // instruction has a vector type, skip. 7989 auto *Ty = I->getType(); 7990 if (isa<VectorType>(Ty)) 7991 continue; 7992 7993 // If the current instruction is a load, update MaxWidth to reflect the 7994 // width of the loaded value. 7995 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) || 7996 isa<ExtractValueInst>(I)) 7997 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); 7998 7999 // Otherwise, we need to visit the operands of the instruction. We only 8000 // handle the interesting cases from buildTree here. If an operand is an 8001 // instruction we haven't yet visited and from the same basic block as the 8002 // user or the use is a PHI node, we add it to the worklist. 8003 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8004 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) || 8005 isa<UnaryOperator>(I)) { 8006 for (Use &U : I->operands()) 8007 if (auto *J = dyn_cast<Instruction>(U.get())) 8008 if (Visited.insert(J).second && 8009 (isa<PHINode>(I) || J->getParent() == Parent)) 8010 Worklist.emplace_back(J, J->getParent()); 8011 } else { 8012 break; 8013 } 8014 } 8015 8016 // If we didn't encounter a memory access in the expression tree, or if we 8017 // gave up for some reason, just return the width of V. Otherwise, return the 8018 // maximum width we found. 8019 if (!Width) { 8020 if (auto *CI = dyn_cast<CmpInst>(V)) 8021 V = CI->getOperand(0); 8022 Width = DL->getTypeSizeInBits(V->getType()); 8023 } 8024 8025 for (Instruction *I : Visited) 8026 InstrElementSize[I] = Width; 8027 8028 return Width; 8029 } 8030 8031 // Determine if a value V in a vectorizable expression Expr can be demoted to a 8032 // smaller type with a truncation. We collect the values that will be demoted 8033 // in ToDemote and additional roots that require investigating in Roots. 8034 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 8035 SmallVectorImpl<Value *> &ToDemote, 8036 SmallVectorImpl<Value *> &Roots) { 8037 // We can always demote constants. 8038 if (isa<Constant>(V)) { 8039 ToDemote.push_back(V); 8040 return true; 8041 } 8042 8043 // If the value is not an instruction in the expression with only one use, it 8044 // cannot be demoted. 8045 auto *I = dyn_cast<Instruction>(V); 8046 if (!I || !I->hasOneUse() || !Expr.count(I)) 8047 return false; 8048 8049 switch (I->getOpcode()) { 8050 8051 // We can always demote truncations and extensions. Since truncations can 8052 // seed additional demotion, we save the truncated value. 8053 case Instruction::Trunc: 8054 Roots.push_back(I->getOperand(0)); 8055 break; 8056 case Instruction::ZExt: 8057 case Instruction::SExt: 8058 if (isa<ExtractElementInst>(I->getOperand(0)) || 8059 isa<InsertElementInst>(I->getOperand(0))) 8060 return false; 8061 break; 8062 8063 // We can demote certain binary operations if we can demote both of their 8064 // operands. 8065 case Instruction::Add: 8066 case Instruction::Sub: 8067 case Instruction::Mul: 8068 case Instruction::And: 8069 case Instruction::Or: 8070 case Instruction::Xor: 8071 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 8072 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 8073 return false; 8074 break; 8075 8076 // We can demote selects if we can demote their true and false values. 8077 case Instruction::Select: { 8078 SelectInst *SI = cast<SelectInst>(I); 8079 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 8080 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 8081 return false; 8082 break; 8083 } 8084 8085 // We can demote phis if we can demote all their incoming operands. Note that 8086 // we don't need to worry about cycles since we ensure single use above. 8087 case Instruction::PHI: { 8088 PHINode *PN = cast<PHINode>(I); 8089 for (Value *IncValue : PN->incoming_values()) 8090 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 8091 return false; 8092 break; 8093 } 8094 8095 // Otherwise, conservatively give up. 8096 default: 8097 return false; 8098 } 8099 8100 // Record the value that we can demote. 8101 ToDemote.push_back(V); 8102 return true; 8103 } 8104 8105 void BoUpSLP::computeMinimumValueSizes() { 8106 // If there are no external uses, the expression tree must be rooted by a 8107 // store. We can't demote in-memory values, so there is nothing to do here. 8108 if (ExternalUses.empty()) 8109 return; 8110 8111 // We only attempt to truncate integer expressions. 8112 auto &TreeRoot = VectorizableTree[0]->Scalars; 8113 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 8114 if (!TreeRootIT) 8115 return; 8116 8117 // If the expression is not rooted by a store, these roots should have 8118 // external uses. We will rely on InstCombine to rewrite the expression in 8119 // the narrower type. However, InstCombine only rewrites single-use values. 8120 // This means that if a tree entry other than a root is used externally, it 8121 // must have multiple uses and InstCombine will not rewrite it. The code 8122 // below ensures that only the roots are used externally. 8123 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 8124 for (auto &EU : ExternalUses) 8125 if (!Expr.erase(EU.Scalar)) 8126 return; 8127 if (!Expr.empty()) 8128 return; 8129 8130 // Collect the scalar values of the vectorizable expression. We will use this 8131 // context to determine which values can be demoted. If we see a truncation, 8132 // we mark it as seeding another demotion. 8133 for (auto &EntryPtr : VectorizableTree) 8134 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 8135 8136 // Ensure the roots of the vectorizable tree don't form a cycle. They must 8137 // have a single external user that is not in the vectorizable tree. 8138 for (auto *Root : TreeRoot) 8139 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 8140 return; 8141 8142 // Conservatively determine if we can actually truncate the roots of the 8143 // expression. Collect the values that can be demoted in ToDemote and 8144 // additional roots that require investigating in Roots. 8145 SmallVector<Value *, 32> ToDemote; 8146 SmallVector<Value *, 4> Roots; 8147 for (auto *Root : TreeRoot) 8148 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 8149 return; 8150 8151 // The maximum bit width required to represent all the values that can be 8152 // demoted without loss of precision. It would be safe to truncate the roots 8153 // of the expression to this width. 8154 auto MaxBitWidth = 8u; 8155 8156 // We first check if all the bits of the roots are demanded. If they're not, 8157 // we can truncate the roots to this narrower type. 8158 for (auto *Root : TreeRoot) { 8159 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 8160 MaxBitWidth = std::max<unsigned>( 8161 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 8162 } 8163 8164 // True if the roots can be zero-extended back to their original type, rather 8165 // than sign-extended. We know that if the leading bits are not demanded, we 8166 // can safely zero-extend. So we initialize IsKnownPositive to True. 8167 bool IsKnownPositive = true; 8168 8169 // If all the bits of the roots are demanded, we can try a little harder to 8170 // compute a narrower type. This can happen, for example, if the roots are 8171 // getelementptr indices. InstCombine promotes these indices to the pointer 8172 // width. Thus, all their bits are technically demanded even though the 8173 // address computation might be vectorized in a smaller type. 8174 // 8175 // We start by looking at each entry that can be demoted. We compute the 8176 // maximum bit width required to store the scalar by using ValueTracking to 8177 // compute the number of high-order bits we can truncate. 8178 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 8179 llvm::all_of(TreeRoot, [](Value *R) { 8180 assert(R->hasOneUse() && "Root should have only one use!"); 8181 return isa<GetElementPtrInst>(R->user_back()); 8182 })) { 8183 MaxBitWidth = 8u; 8184 8185 // Determine if the sign bit of all the roots is known to be zero. If not, 8186 // IsKnownPositive is set to False. 8187 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 8188 KnownBits Known = computeKnownBits(R, *DL); 8189 return Known.isNonNegative(); 8190 }); 8191 8192 // Determine the maximum number of bits required to store the scalar 8193 // values. 8194 for (auto *Scalar : ToDemote) { 8195 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 8196 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 8197 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 8198 } 8199 8200 // If we can't prove that the sign bit is zero, we must add one to the 8201 // maximum bit width to account for the unknown sign bit. This preserves 8202 // the existing sign bit so we can safely sign-extend the root back to the 8203 // original type. Otherwise, if we know the sign bit is zero, we will 8204 // zero-extend the root instead. 8205 // 8206 // FIXME: This is somewhat suboptimal, as there will be cases where adding 8207 // one to the maximum bit width will yield a larger-than-necessary 8208 // type. In general, we need to add an extra bit only if we can't 8209 // prove that the upper bit of the original type is equal to the 8210 // upper bit of the proposed smaller type. If these two bits are the 8211 // same (either zero or one) we know that sign-extending from the 8212 // smaller type will result in the same value. Here, since we can't 8213 // yet prove this, we are just making the proposed smaller type 8214 // larger to ensure correctness. 8215 if (!IsKnownPositive) 8216 ++MaxBitWidth; 8217 } 8218 8219 // Round MaxBitWidth up to the next power-of-two. 8220 if (!isPowerOf2_64(MaxBitWidth)) 8221 MaxBitWidth = NextPowerOf2(MaxBitWidth); 8222 8223 // If the maximum bit width we compute is less than the with of the roots' 8224 // type, we can proceed with the narrowing. Otherwise, do nothing. 8225 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 8226 return; 8227 8228 // If we can truncate the root, we must collect additional values that might 8229 // be demoted as a result. That is, those seeded by truncations we will 8230 // modify. 8231 while (!Roots.empty()) 8232 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 8233 8234 // Finally, map the values we can demote to the maximum bit with we computed. 8235 for (auto *Scalar : ToDemote) 8236 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 8237 } 8238 8239 namespace { 8240 8241 /// The SLPVectorizer Pass. 8242 struct SLPVectorizer : public FunctionPass { 8243 SLPVectorizerPass Impl; 8244 8245 /// Pass identification, replacement for typeid 8246 static char ID; 8247 8248 explicit SLPVectorizer() : FunctionPass(ID) { 8249 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 8250 } 8251 8252 bool doInitialization(Module &M) override { return false; } 8253 8254 bool runOnFunction(Function &F) override { 8255 if (skipFunction(F)) 8256 return false; 8257 8258 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 8259 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 8260 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 8261 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 8262 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 8263 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 8264 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 8265 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 8266 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 8267 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 8268 8269 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8270 } 8271 8272 void getAnalysisUsage(AnalysisUsage &AU) const override { 8273 FunctionPass::getAnalysisUsage(AU); 8274 AU.addRequired<AssumptionCacheTracker>(); 8275 AU.addRequired<ScalarEvolutionWrapperPass>(); 8276 AU.addRequired<AAResultsWrapperPass>(); 8277 AU.addRequired<TargetTransformInfoWrapperPass>(); 8278 AU.addRequired<LoopInfoWrapperPass>(); 8279 AU.addRequired<DominatorTreeWrapperPass>(); 8280 AU.addRequired<DemandedBitsWrapperPass>(); 8281 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 8282 AU.addRequired<InjectTLIMappingsLegacy>(); 8283 AU.addPreserved<LoopInfoWrapperPass>(); 8284 AU.addPreserved<DominatorTreeWrapperPass>(); 8285 AU.addPreserved<AAResultsWrapperPass>(); 8286 AU.addPreserved<GlobalsAAWrapperPass>(); 8287 AU.setPreservesCFG(); 8288 } 8289 }; 8290 8291 } // end anonymous namespace 8292 8293 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 8294 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 8295 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 8296 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 8297 auto *AA = &AM.getResult<AAManager>(F); 8298 auto *LI = &AM.getResult<LoopAnalysis>(F); 8299 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 8300 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 8301 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 8302 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 8303 8304 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8305 if (!Changed) 8306 return PreservedAnalyses::all(); 8307 8308 PreservedAnalyses PA; 8309 PA.preserveSet<CFGAnalyses>(); 8310 return PA; 8311 } 8312 8313 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 8314 TargetTransformInfo *TTI_, 8315 TargetLibraryInfo *TLI_, AAResults *AA_, 8316 LoopInfo *LI_, DominatorTree *DT_, 8317 AssumptionCache *AC_, DemandedBits *DB_, 8318 OptimizationRemarkEmitter *ORE_) { 8319 if (!RunSLPVectorization) 8320 return false; 8321 SE = SE_; 8322 TTI = TTI_; 8323 TLI = TLI_; 8324 AA = AA_; 8325 LI = LI_; 8326 DT = DT_; 8327 AC = AC_; 8328 DB = DB_; 8329 DL = &F.getParent()->getDataLayout(); 8330 8331 Stores.clear(); 8332 GEPs.clear(); 8333 bool Changed = false; 8334 8335 // If the target claims to have no vector registers don't attempt 8336 // vectorization. 8337 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) { 8338 LLVM_DEBUG( 8339 dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"); 8340 return false; 8341 } 8342 8343 // Don't vectorize when the attribute NoImplicitFloat is used. 8344 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 8345 return false; 8346 8347 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 8348 8349 // Use the bottom up slp vectorizer to construct chains that start with 8350 // store instructions. 8351 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 8352 8353 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 8354 // delete instructions. 8355 8356 // Update DFS numbers now so that we can use them for ordering. 8357 DT->updateDFSNumbers(); 8358 8359 // Scan the blocks in the function in post order. 8360 for (auto BB : post_order(&F.getEntryBlock())) { 8361 collectSeedInstructions(BB); 8362 8363 // Vectorize trees that end at stores. 8364 if (!Stores.empty()) { 8365 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 8366 << " underlying objects.\n"); 8367 Changed |= vectorizeStoreChains(R); 8368 } 8369 8370 // Vectorize trees that end at reductions. 8371 Changed |= vectorizeChainsInBlock(BB, R); 8372 8373 // Vectorize the index computations of getelementptr instructions. This 8374 // is primarily intended to catch gather-like idioms ending at 8375 // non-consecutive loads. 8376 if (!GEPs.empty()) { 8377 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 8378 << " underlying objects.\n"); 8379 Changed |= vectorizeGEPIndices(BB, R); 8380 } 8381 } 8382 8383 if (Changed) { 8384 R.optimizeGatherSequence(); 8385 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 8386 } 8387 return Changed; 8388 } 8389 8390 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 8391 unsigned Idx) { 8392 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 8393 << "\n"); 8394 const unsigned Sz = R.getVectorElementSize(Chain[0]); 8395 const unsigned MinVF = R.getMinVecRegSize() / Sz; 8396 unsigned VF = Chain.size(); 8397 8398 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 8399 return false; 8400 8401 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 8402 << "\n"); 8403 8404 R.buildTree(Chain); 8405 if (R.isTreeTinyAndNotFullyVectorizable()) 8406 return false; 8407 if (R.isLoadCombineCandidate()) 8408 return false; 8409 R.reorderTopToBottom(); 8410 R.reorderBottomToTop(); 8411 R.buildExternalUses(); 8412 8413 R.computeMinimumValueSizes(); 8414 8415 InstructionCost Cost = R.getTreeCost(); 8416 8417 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n"); 8418 if (Cost < -SLPCostThreshold) { 8419 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"); 8420 8421 using namespace ore; 8422 8423 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 8424 cast<StoreInst>(Chain[0])) 8425 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 8426 << " and with tree size " 8427 << NV("TreeSize", R.getTreeSize())); 8428 8429 R.vectorizeTree(); 8430 return true; 8431 } 8432 8433 return false; 8434 } 8435 8436 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 8437 BoUpSLP &R) { 8438 // We may run into multiple chains that merge into a single chain. We mark the 8439 // stores that we vectorized so that we don't visit the same store twice. 8440 BoUpSLP::ValueSet VectorizedStores; 8441 bool Changed = false; 8442 8443 int E = Stores.size(); 8444 SmallBitVector Tails(E, false); 8445 int MaxIter = MaxStoreLookup.getValue(); 8446 SmallVector<std::pair<int, int>, 16> ConsecutiveChain( 8447 E, std::make_pair(E, INT_MAX)); 8448 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); 8449 int IterCnt; 8450 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 8451 &CheckedPairs, 8452 &ConsecutiveChain](int K, int Idx) { 8453 if (IterCnt >= MaxIter) 8454 return true; 8455 if (CheckedPairs[Idx].test(K)) 8456 return ConsecutiveChain[K].second == 1 && 8457 ConsecutiveChain[K].first == Idx; 8458 ++IterCnt; 8459 CheckedPairs[Idx].set(K); 8460 CheckedPairs[K].set(Idx); 8461 Optional<int> Diff = getPointersDiff( 8462 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), 8463 Stores[Idx]->getValueOperand()->getType(), 8464 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); 8465 if (!Diff || *Diff == 0) 8466 return false; 8467 int Val = *Diff; 8468 if (Val < 0) { 8469 if (ConsecutiveChain[Idx].second > -Val) { 8470 Tails.set(K); 8471 ConsecutiveChain[Idx] = std::make_pair(K, -Val); 8472 } 8473 return false; 8474 } 8475 if (ConsecutiveChain[K].second <= Val) 8476 return false; 8477 8478 Tails.set(Idx); 8479 ConsecutiveChain[K] = std::make_pair(Idx, Val); 8480 return Val == 1; 8481 }; 8482 // Do a quadratic search on all of the given stores in reverse order and find 8483 // all of the pairs of stores that follow each other. 8484 for (int Idx = E - 1; Idx >= 0; --Idx) { 8485 // If a store has multiple consecutive store candidates, search according 8486 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 8487 // This is because usually pairing with immediate succeeding or preceding 8488 // candidate create the best chance to find slp vectorization opportunity. 8489 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 8490 IterCnt = 0; 8491 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 8492 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 8493 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 8494 break; 8495 } 8496 8497 // Tracks if we tried to vectorize stores starting from the given tail 8498 // already. 8499 SmallBitVector TriedTails(E, false); 8500 // For stores that start but don't end a link in the chain: 8501 for (int Cnt = E; Cnt > 0; --Cnt) { 8502 int I = Cnt - 1; 8503 if (ConsecutiveChain[I].first == E || Tails.test(I)) 8504 continue; 8505 // We found a store instr that starts a chain. Now follow the chain and try 8506 // to vectorize it. 8507 BoUpSLP::ValueList Operands; 8508 // Collect the chain into a list. 8509 while (I != E && !VectorizedStores.count(Stores[I])) { 8510 Operands.push_back(Stores[I]); 8511 Tails.set(I); 8512 if (ConsecutiveChain[I].second != 1) { 8513 // Mark the new end in the chain and go back, if required. It might be 8514 // required if the original stores come in reversed order, for example. 8515 if (ConsecutiveChain[I].first != E && 8516 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && 8517 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { 8518 TriedTails.set(I); 8519 Tails.reset(ConsecutiveChain[I].first); 8520 if (Cnt < ConsecutiveChain[I].first + 2) 8521 Cnt = ConsecutiveChain[I].first + 2; 8522 } 8523 break; 8524 } 8525 // Move to the next value in the chain. 8526 I = ConsecutiveChain[I].first; 8527 } 8528 assert(!Operands.empty() && "Expected non-empty list of stores."); 8529 8530 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 8531 unsigned EltSize = R.getVectorElementSize(Operands[0]); 8532 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); 8533 8534 unsigned MinVF = R.getMinVF(EltSize); 8535 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), 8536 MaxElts); 8537 8538 // FIXME: Is division-by-2 the correct step? Should we assert that the 8539 // register size is a power-of-2? 8540 unsigned StartIdx = 0; 8541 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { 8542 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 8543 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 8544 if (!VectorizedStores.count(Slice.front()) && 8545 !VectorizedStores.count(Slice.back()) && 8546 vectorizeStoreChain(Slice, R, Cnt)) { 8547 // Mark the vectorized stores so that we don't vectorize them again. 8548 VectorizedStores.insert(Slice.begin(), Slice.end()); 8549 Changed = true; 8550 // If we vectorized initial block, no need to try to vectorize it 8551 // again. 8552 if (Cnt == StartIdx) 8553 StartIdx += Size; 8554 Cnt += Size; 8555 continue; 8556 } 8557 ++Cnt; 8558 } 8559 // Check if the whole array was vectorized already - exit. 8560 if (StartIdx >= Operands.size()) 8561 break; 8562 } 8563 } 8564 8565 return Changed; 8566 } 8567 8568 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 8569 // Initialize the collections. We will make a single pass over the block. 8570 Stores.clear(); 8571 GEPs.clear(); 8572 8573 // Visit the store and getelementptr instructions in BB and organize them in 8574 // Stores and GEPs according to the underlying objects of their pointer 8575 // operands. 8576 for (Instruction &I : *BB) { 8577 // Ignore store instructions that are volatile or have a pointer operand 8578 // that doesn't point to a scalar type. 8579 if (auto *SI = dyn_cast<StoreInst>(&I)) { 8580 if (!SI->isSimple()) 8581 continue; 8582 if (!isValidElementType(SI->getValueOperand()->getType())) 8583 continue; 8584 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); 8585 } 8586 8587 // Ignore getelementptr instructions that have more than one index, a 8588 // constant index, or a pointer operand that doesn't point to a scalar 8589 // type. 8590 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 8591 auto Idx = GEP->idx_begin()->get(); 8592 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 8593 continue; 8594 if (!isValidElementType(Idx->getType())) 8595 continue; 8596 if (GEP->getType()->isVectorTy()) 8597 continue; 8598 GEPs[GEP->getPointerOperand()].push_back(GEP); 8599 } 8600 } 8601 } 8602 8603 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 8604 if (!A || !B) 8605 return false; 8606 if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B)) 8607 return false; 8608 Value *VL[] = {A, B}; 8609 return tryToVectorizeList(VL, R); 8610 } 8611 8612 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 8613 bool LimitForRegisterSize) { 8614 if (VL.size() < 2) 8615 return false; 8616 8617 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 8618 << VL.size() << ".\n"); 8619 8620 // Check that all of the parts are instructions of the same type, 8621 // we permit an alternate opcode via InstructionsState. 8622 InstructionsState S = getSameOpcode(VL); 8623 if (!S.getOpcode()) 8624 return false; 8625 8626 Instruction *I0 = cast<Instruction>(S.OpValue); 8627 // Make sure invalid types (including vector type) are rejected before 8628 // determining vectorization factor for scalar instructions. 8629 for (Value *V : VL) { 8630 Type *Ty = V->getType(); 8631 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { 8632 // NOTE: the following will give user internal llvm type name, which may 8633 // not be useful. 8634 R.getORE()->emit([&]() { 8635 std::string type_str; 8636 llvm::raw_string_ostream rso(type_str); 8637 Ty->print(rso); 8638 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 8639 << "Cannot SLP vectorize list: type " 8640 << rso.str() + " is unsupported by vectorizer"; 8641 }); 8642 return false; 8643 } 8644 } 8645 8646 unsigned Sz = R.getVectorElementSize(I0); 8647 unsigned MinVF = R.getMinVF(Sz); 8648 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 8649 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); 8650 if (MaxVF < 2) { 8651 R.getORE()->emit([&]() { 8652 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 8653 << "Cannot SLP vectorize list: vectorization factor " 8654 << "less than 2 is not supported"; 8655 }); 8656 return false; 8657 } 8658 8659 bool Changed = false; 8660 bool CandidateFound = false; 8661 InstructionCost MinCost = SLPCostThreshold.getValue(); 8662 Type *ScalarTy = VL[0]->getType(); 8663 if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 8664 ScalarTy = IE->getOperand(1)->getType(); 8665 8666 unsigned NextInst = 0, MaxInst = VL.size(); 8667 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 8668 // No actual vectorization should happen, if number of parts is the same as 8669 // provided vectorization factor (i.e. the scalar type is used for vector 8670 // code during codegen). 8671 auto *VecTy = FixedVectorType::get(ScalarTy, VF); 8672 if (TTI->getNumberOfParts(VecTy) == VF) 8673 continue; 8674 for (unsigned I = NextInst; I < MaxInst; ++I) { 8675 unsigned OpsWidth = 0; 8676 8677 if (I + VF > MaxInst) 8678 OpsWidth = MaxInst - I; 8679 else 8680 OpsWidth = VF; 8681 8682 if (!isPowerOf2_32(OpsWidth)) 8683 continue; 8684 8685 if ((LimitForRegisterSize && OpsWidth < MaxVF) || 8686 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) 8687 break; 8688 8689 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 8690 // Check that a previous iteration of this loop did not delete the Value. 8691 if (llvm::any_of(Ops, [&R](Value *V) { 8692 auto *I = dyn_cast<Instruction>(V); 8693 return I && R.isDeleted(I); 8694 })) 8695 continue; 8696 8697 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 8698 << "\n"); 8699 8700 R.buildTree(Ops); 8701 if (R.isTreeTinyAndNotFullyVectorizable()) 8702 continue; 8703 R.reorderTopToBottom(); 8704 R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front())); 8705 R.buildExternalUses(); 8706 8707 R.computeMinimumValueSizes(); 8708 InstructionCost Cost = R.getTreeCost(); 8709 CandidateFound = true; 8710 MinCost = std::min(MinCost, Cost); 8711 8712 if (Cost < -SLPCostThreshold) { 8713 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 8714 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 8715 cast<Instruction>(Ops[0])) 8716 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 8717 << " and with tree size " 8718 << ore::NV("TreeSize", R.getTreeSize())); 8719 8720 R.vectorizeTree(); 8721 // Move to the next bundle. 8722 I += VF - 1; 8723 NextInst = I + 1; 8724 Changed = true; 8725 } 8726 } 8727 } 8728 8729 if (!Changed && CandidateFound) { 8730 R.getORE()->emit([&]() { 8731 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 8732 << "List vectorization was possible but not beneficial with cost " 8733 << ore::NV("Cost", MinCost) << " >= " 8734 << ore::NV("Treshold", -SLPCostThreshold); 8735 }); 8736 } else if (!Changed) { 8737 R.getORE()->emit([&]() { 8738 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 8739 << "Cannot SLP vectorize list: vectorization was impossible" 8740 << " with available vectorization factors"; 8741 }); 8742 } 8743 return Changed; 8744 } 8745 8746 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 8747 if (!I) 8748 return false; 8749 8750 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) 8751 return false; 8752 8753 Value *P = I->getParent(); 8754 8755 // Vectorize in current basic block only. 8756 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 8757 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 8758 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 8759 return false; 8760 8761 // Try to vectorize V. 8762 if (tryToVectorizePair(Op0, Op1, R)) 8763 return true; 8764 8765 auto *A = dyn_cast<BinaryOperator>(Op0); 8766 auto *B = dyn_cast<BinaryOperator>(Op1); 8767 // Try to skip B. 8768 if (B && B->hasOneUse()) { 8769 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 8770 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 8771 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R)) 8772 return true; 8773 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R)) 8774 return true; 8775 } 8776 8777 // Try to skip A. 8778 if (A && A->hasOneUse()) { 8779 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 8780 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 8781 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R)) 8782 return true; 8783 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R)) 8784 return true; 8785 } 8786 return false; 8787 } 8788 8789 namespace { 8790 8791 /// Model horizontal reductions. 8792 /// 8793 /// A horizontal reduction is a tree of reduction instructions that has values 8794 /// that can be put into a vector as its leaves. For example: 8795 /// 8796 /// mul mul mul mul 8797 /// \ / \ / 8798 /// + + 8799 /// \ / 8800 /// + 8801 /// This tree has "mul" as its leaf values and "+" as its reduction 8802 /// instructions. A reduction can feed into a store or a binary operation 8803 /// feeding a phi. 8804 /// ... 8805 /// \ / 8806 /// + 8807 /// | 8808 /// phi += 8809 /// 8810 /// Or: 8811 /// ... 8812 /// \ / 8813 /// + 8814 /// | 8815 /// *p = 8816 /// 8817 class HorizontalReduction { 8818 using ReductionOpsType = SmallVector<Value *, 16>; 8819 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 8820 ReductionOpsListType ReductionOps; 8821 SmallVector<Value *, 32> ReducedVals; 8822 // Use map vector to make stable output. 8823 MapVector<Instruction *, Value *> ExtraArgs; 8824 WeakTrackingVH ReductionRoot; 8825 /// The type of reduction operation. 8826 RecurKind RdxKind; 8827 8828 const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max(); 8829 8830 static bool isCmpSelMinMax(Instruction *I) { 8831 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && 8832 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); 8833 } 8834 8835 // And/or are potentially poison-safe logical patterns like: 8836 // select x, y, false 8837 // select x, true, y 8838 static bool isBoolLogicOp(Instruction *I) { 8839 return match(I, m_LogicalAnd(m_Value(), m_Value())) || 8840 match(I, m_LogicalOr(m_Value(), m_Value())); 8841 } 8842 8843 /// Checks if instruction is associative and can be vectorized. 8844 static bool isVectorizable(RecurKind Kind, Instruction *I) { 8845 if (Kind == RecurKind::None) 8846 return false; 8847 8848 // Integer ops that map to select instructions or intrinsics are fine. 8849 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || 8850 isBoolLogicOp(I)) 8851 return true; 8852 8853 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { 8854 // FP min/max are associative except for NaN and -0.0. We do not 8855 // have to rule out -0.0 here because the intrinsic semantics do not 8856 // specify a fixed result for it. 8857 return I->getFastMathFlags().noNaNs(); 8858 } 8859 8860 return I->isAssociative(); 8861 } 8862 8863 static Value *getRdxOperand(Instruction *I, unsigned Index) { 8864 // Poison-safe 'or' takes the form: select X, true, Y 8865 // To make that work with the normal operand processing, we skip the 8866 // true value operand. 8867 // TODO: Change the code and data structures to handle this without a hack. 8868 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) 8869 return I->getOperand(2); 8870 return I->getOperand(Index); 8871 } 8872 8873 /// Checks if the ParentStackElem.first should be marked as a reduction 8874 /// operation with an extra argument or as extra argument itself. 8875 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem, 8876 Value *ExtraArg) { 8877 if (ExtraArgs.count(ParentStackElem.first)) { 8878 ExtraArgs[ParentStackElem.first] = nullptr; 8879 // We ran into something like: 8880 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg. 8881 // The whole ParentStackElem.first should be considered as an extra value 8882 // in this case. 8883 // Do not perform analysis of remaining operands of ParentStackElem.first 8884 // instruction, this whole instruction is an extra argument. 8885 ParentStackElem.second = INVALID_OPERAND_INDEX; 8886 } else { 8887 // We ran into something like: 8888 // ParentStackElem.first += ... + ExtraArg + ... 8889 ExtraArgs[ParentStackElem.first] = ExtraArg; 8890 } 8891 } 8892 8893 /// Creates reduction operation with the current opcode. 8894 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, 8895 Value *RHS, const Twine &Name, bool UseSelect) { 8896 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); 8897 switch (Kind) { 8898 case RecurKind::Or: 8899 if (UseSelect && 8900 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8901 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); 8902 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8903 Name); 8904 case RecurKind::And: 8905 if (UseSelect && 8906 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8907 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); 8908 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8909 Name); 8910 case RecurKind::Add: 8911 case RecurKind::Mul: 8912 case RecurKind::Xor: 8913 case RecurKind::FAdd: 8914 case RecurKind::FMul: 8915 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8916 Name); 8917 case RecurKind::FMax: 8918 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); 8919 case RecurKind::FMin: 8920 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); 8921 case RecurKind::SMax: 8922 if (UseSelect) { 8923 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); 8924 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8925 } 8926 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); 8927 case RecurKind::SMin: 8928 if (UseSelect) { 8929 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); 8930 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8931 } 8932 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); 8933 case RecurKind::UMax: 8934 if (UseSelect) { 8935 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); 8936 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8937 } 8938 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); 8939 case RecurKind::UMin: 8940 if (UseSelect) { 8941 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); 8942 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8943 } 8944 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); 8945 default: 8946 llvm_unreachable("Unknown reduction operation."); 8947 } 8948 } 8949 8950 /// Creates reduction operation with the current opcode with the IR flags 8951 /// from \p ReductionOps. 8952 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 8953 Value *RHS, const Twine &Name, 8954 const ReductionOpsListType &ReductionOps) { 8955 bool UseSelect = ReductionOps.size() == 2 || 8956 // Logical or/and. 8957 (ReductionOps.size() == 1 && 8958 isa<SelectInst>(ReductionOps.front().front())); 8959 assert((!UseSelect || ReductionOps.size() != 2 || 8960 isa<SelectInst>(ReductionOps[1][0])) && 8961 "Expected cmp + select pairs for reduction"); 8962 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); 8963 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 8964 if (auto *Sel = dyn_cast<SelectInst>(Op)) { 8965 propagateIRFlags(Sel->getCondition(), ReductionOps[0]); 8966 propagateIRFlags(Op, ReductionOps[1]); 8967 return Op; 8968 } 8969 } 8970 propagateIRFlags(Op, ReductionOps[0]); 8971 return Op; 8972 } 8973 8974 /// Creates reduction operation with the current opcode with the IR flags 8975 /// from \p I. 8976 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 8977 Value *RHS, const Twine &Name, Instruction *I) { 8978 auto *SelI = dyn_cast<SelectInst>(I); 8979 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr); 8980 if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 8981 if (auto *Sel = dyn_cast<SelectInst>(Op)) 8982 propagateIRFlags(Sel->getCondition(), SelI->getCondition()); 8983 } 8984 propagateIRFlags(Op, I); 8985 return Op; 8986 } 8987 8988 static RecurKind getRdxKind(Instruction *I) { 8989 assert(I && "Expected instruction for reduction matching"); 8990 if (match(I, m_Add(m_Value(), m_Value()))) 8991 return RecurKind::Add; 8992 if (match(I, m_Mul(m_Value(), m_Value()))) 8993 return RecurKind::Mul; 8994 if (match(I, m_And(m_Value(), m_Value())) || 8995 match(I, m_LogicalAnd(m_Value(), m_Value()))) 8996 return RecurKind::And; 8997 if (match(I, m_Or(m_Value(), m_Value())) || 8998 match(I, m_LogicalOr(m_Value(), m_Value()))) 8999 return RecurKind::Or; 9000 if (match(I, m_Xor(m_Value(), m_Value()))) 9001 return RecurKind::Xor; 9002 if (match(I, m_FAdd(m_Value(), m_Value()))) 9003 return RecurKind::FAdd; 9004 if (match(I, m_FMul(m_Value(), m_Value()))) 9005 return RecurKind::FMul; 9006 9007 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 9008 return RecurKind::FMax; 9009 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 9010 return RecurKind::FMin; 9011 9012 // This matches either cmp+select or intrinsics. SLP is expected to handle 9013 // either form. 9014 // TODO: If we are canonicalizing to intrinsics, we can remove several 9015 // special-case paths that deal with selects. 9016 if (match(I, m_SMax(m_Value(), m_Value()))) 9017 return RecurKind::SMax; 9018 if (match(I, m_SMin(m_Value(), m_Value()))) 9019 return RecurKind::SMin; 9020 if (match(I, m_UMax(m_Value(), m_Value()))) 9021 return RecurKind::UMax; 9022 if (match(I, m_UMin(m_Value(), m_Value()))) 9023 return RecurKind::UMin; 9024 9025 if (auto *Select = dyn_cast<SelectInst>(I)) { 9026 // Try harder: look for min/max pattern based on instructions producing 9027 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 9028 // During the intermediate stages of SLP, it's very common to have 9029 // pattern like this (since optimizeGatherSequence is run only once 9030 // at the end): 9031 // %1 = extractelement <2 x i32> %a, i32 0 9032 // %2 = extractelement <2 x i32> %a, i32 1 9033 // %cond = icmp sgt i32 %1, %2 9034 // %3 = extractelement <2 x i32> %a, i32 0 9035 // %4 = extractelement <2 x i32> %a, i32 1 9036 // %select = select i1 %cond, i32 %3, i32 %4 9037 CmpInst::Predicate Pred; 9038 Instruction *L1; 9039 Instruction *L2; 9040 9041 Value *LHS = Select->getTrueValue(); 9042 Value *RHS = Select->getFalseValue(); 9043 Value *Cond = Select->getCondition(); 9044 9045 // TODO: Support inverse predicates. 9046 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 9047 if (!isa<ExtractElementInst>(RHS) || 9048 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9049 return RecurKind::None; 9050 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 9051 if (!isa<ExtractElementInst>(LHS) || 9052 !L1->isIdenticalTo(cast<Instruction>(LHS))) 9053 return RecurKind::None; 9054 } else { 9055 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 9056 return RecurKind::None; 9057 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 9058 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 9059 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9060 return RecurKind::None; 9061 } 9062 9063 switch (Pred) { 9064 default: 9065 return RecurKind::None; 9066 case CmpInst::ICMP_SGT: 9067 case CmpInst::ICMP_SGE: 9068 return RecurKind::SMax; 9069 case CmpInst::ICMP_SLT: 9070 case CmpInst::ICMP_SLE: 9071 return RecurKind::SMin; 9072 case CmpInst::ICMP_UGT: 9073 case CmpInst::ICMP_UGE: 9074 return RecurKind::UMax; 9075 case CmpInst::ICMP_ULT: 9076 case CmpInst::ICMP_ULE: 9077 return RecurKind::UMin; 9078 } 9079 } 9080 return RecurKind::None; 9081 } 9082 9083 /// Get the index of the first operand. 9084 static unsigned getFirstOperandIndex(Instruction *I) { 9085 return isCmpSelMinMax(I) ? 1 : 0; 9086 } 9087 9088 /// Total number of operands in the reduction operation. 9089 static unsigned getNumberOfOperands(Instruction *I) { 9090 return isCmpSelMinMax(I) ? 3 : 2; 9091 } 9092 9093 /// Checks if the instruction is in basic block \p BB. 9094 /// For a cmp+sel min/max reduction check that both ops are in \p BB. 9095 static bool hasSameParent(Instruction *I, BasicBlock *BB) { 9096 if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) { 9097 auto *Sel = cast<SelectInst>(I); 9098 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); 9099 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; 9100 } 9101 return I->getParent() == BB; 9102 } 9103 9104 /// Expected number of uses for reduction operations/reduced values. 9105 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { 9106 if (IsCmpSelMinMax) { 9107 // SelectInst must be used twice while the condition op must have single 9108 // use only. 9109 if (auto *Sel = dyn_cast<SelectInst>(I)) 9110 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); 9111 return I->hasNUses(2); 9112 } 9113 9114 // Arithmetic reduction operation must be used once only. 9115 return I->hasOneUse(); 9116 } 9117 9118 /// Initializes the list of reduction operations. 9119 void initReductionOps(Instruction *I) { 9120 if (isCmpSelMinMax(I)) 9121 ReductionOps.assign(2, ReductionOpsType()); 9122 else 9123 ReductionOps.assign(1, ReductionOpsType()); 9124 } 9125 9126 /// Add all reduction operations for the reduction instruction \p I. 9127 void addReductionOps(Instruction *I) { 9128 if (isCmpSelMinMax(I)) { 9129 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 9130 ReductionOps[1].emplace_back(I); 9131 } else { 9132 ReductionOps[0].emplace_back(I); 9133 } 9134 } 9135 9136 static Value *getLHS(RecurKind Kind, Instruction *I) { 9137 if (Kind == RecurKind::None) 9138 return nullptr; 9139 return I->getOperand(getFirstOperandIndex(I)); 9140 } 9141 static Value *getRHS(RecurKind Kind, Instruction *I) { 9142 if (Kind == RecurKind::None) 9143 return nullptr; 9144 return I->getOperand(getFirstOperandIndex(I) + 1); 9145 } 9146 9147 public: 9148 HorizontalReduction() = default; 9149 9150 /// Try to find a reduction tree. 9151 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) { 9152 assert((!Phi || is_contained(Phi->operands(), Inst)) && 9153 "Phi needs to use the binary operator"); 9154 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || 9155 isa<IntrinsicInst>(Inst)) && 9156 "Expected binop, select, or intrinsic for reduction matching"); 9157 RdxKind = getRdxKind(Inst); 9158 9159 // We could have a initial reductions that is not an add. 9160 // r *= v1 + v2 + v3 + v4 9161 // In such a case start looking for a tree rooted in the first '+'. 9162 if (Phi) { 9163 if (getLHS(RdxKind, Inst) == Phi) { 9164 Phi = nullptr; 9165 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); 9166 if (!Inst) 9167 return false; 9168 RdxKind = getRdxKind(Inst); 9169 } else if (getRHS(RdxKind, Inst) == Phi) { 9170 Phi = nullptr; 9171 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); 9172 if (!Inst) 9173 return false; 9174 RdxKind = getRdxKind(Inst); 9175 } 9176 } 9177 9178 if (!isVectorizable(RdxKind, Inst)) 9179 return false; 9180 9181 // Analyze "regular" integer/FP types for reductions - no target-specific 9182 // types or pointers. 9183 Type *Ty = Inst->getType(); 9184 if (!isValidElementType(Ty) || Ty->isPointerTy()) 9185 return false; 9186 9187 // Though the ultimate reduction may have multiple uses, its condition must 9188 // have only single use. 9189 if (auto *Sel = dyn_cast<SelectInst>(Inst)) 9190 if (!Sel->getCondition()->hasOneUse()) 9191 return false; 9192 9193 ReductionRoot = Inst; 9194 9195 // The opcode for leaf values that we perform a reduction on. 9196 // For example: load(x) + load(y) + load(z) + fptoui(w) 9197 // The leaf opcode for 'w' does not match, so we don't include it as a 9198 // potential candidate for the reduction. 9199 unsigned LeafOpcode = 0; 9200 9201 // Post-order traverse the reduction tree starting at Inst. We only handle 9202 // true trees containing binary operators or selects. 9203 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack; 9204 Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst))); 9205 initReductionOps(Inst); 9206 while (!Stack.empty()) { 9207 Instruction *TreeN = Stack.back().first; 9208 unsigned EdgeToVisit = Stack.back().second++; 9209 const RecurKind TreeRdxKind = getRdxKind(TreeN); 9210 bool IsReducedValue = TreeRdxKind != RdxKind; 9211 9212 // Postorder visit. 9213 if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) { 9214 if (IsReducedValue) 9215 ReducedVals.push_back(TreeN); 9216 else { 9217 auto ExtraArgsIter = ExtraArgs.find(TreeN); 9218 if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) { 9219 // Check if TreeN is an extra argument of its parent operation. 9220 if (Stack.size() <= 1) { 9221 // TreeN can't be an extra argument as it is a root reduction 9222 // operation. 9223 return false; 9224 } 9225 // Yes, TreeN is an extra argument, do not add it to a list of 9226 // reduction operations. 9227 // Stack[Stack.size() - 2] always points to the parent operation. 9228 markExtraArg(Stack[Stack.size() - 2], TreeN); 9229 ExtraArgs.erase(TreeN); 9230 } else 9231 addReductionOps(TreeN); 9232 } 9233 // Retract. 9234 Stack.pop_back(); 9235 continue; 9236 } 9237 9238 // Visit operands. 9239 Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit); 9240 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); 9241 if (!EdgeInst) { 9242 // Edge value is not a reduction instruction or a leaf instruction. 9243 // (It may be a constant, function argument, or something else.) 9244 markExtraArg(Stack.back(), EdgeVal); 9245 continue; 9246 } 9247 RecurKind EdgeRdxKind = getRdxKind(EdgeInst); 9248 // Continue analysis if the next operand is a reduction operation or 9249 // (possibly) a leaf value. If the leaf value opcode is not set, 9250 // the first met operation != reduction operation is considered as the 9251 // leaf opcode. 9252 // Only handle trees in the current basic block. 9253 // Each tree node needs to have minimal number of users except for the 9254 // ultimate reduction. 9255 const bool IsRdxInst = EdgeRdxKind == RdxKind; 9256 if (EdgeInst != Phi && EdgeInst != Inst && 9257 hasSameParent(EdgeInst, Inst->getParent()) && 9258 hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) && 9259 (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) { 9260 if (IsRdxInst) { 9261 // We need to be able to reassociate the reduction operations. 9262 if (!isVectorizable(EdgeRdxKind, EdgeInst)) { 9263 // I is an extra argument for TreeN (its parent operation). 9264 markExtraArg(Stack.back(), EdgeInst); 9265 continue; 9266 } 9267 } else if (!LeafOpcode) { 9268 LeafOpcode = EdgeInst->getOpcode(); 9269 } 9270 Stack.push_back( 9271 std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst))); 9272 continue; 9273 } 9274 // I is an extra argument for TreeN (its parent operation). 9275 markExtraArg(Stack.back(), EdgeInst); 9276 } 9277 return true; 9278 } 9279 9280 /// Attempt to vectorize the tree found by matchAssociativeReduction. 9281 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 9282 // If there are a sufficient number of reduction values, reduce 9283 // to a nearby power-of-2. We can safely generate oversized 9284 // vectors and rely on the backend to split them to legal sizes. 9285 unsigned NumReducedVals = ReducedVals.size(); 9286 if (NumReducedVals < 4) 9287 return nullptr; 9288 9289 // Intersect the fast-math-flags from all reduction operations. 9290 FastMathFlags RdxFMF; 9291 RdxFMF.set(); 9292 for (ReductionOpsType &RdxOp : ReductionOps) { 9293 for (Value *RdxVal : RdxOp) { 9294 if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal)) 9295 RdxFMF &= FPMO->getFastMathFlags(); 9296 } 9297 } 9298 9299 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 9300 Builder.setFastMathFlags(RdxFMF); 9301 9302 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 9303 // The same extra argument may be used several times, so log each attempt 9304 // to use it. 9305 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { 9306 assert(Pair.first && "DebugLoc must be set."); 9307 ExternallyUsedValues[Pair.second].push_back(Pair.first); 9308 } 9309 9310 // The compare instruction of a min/max is the insertion point for new 9311 // instructions and may be replaced with a new compare instruction. 9312 auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 9313 assert(isa<SelectInst>(RdxRootInst) && 9314 "Expected min/max reduction to have select root instruction"); 9315 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 9316 assert(isa<Instruction>(ScalarCond) && 9317 "Expected min/max reduction to have compare condition"); 9318 return cast<Instruction>(ScalarCond); 9319 }; 9320 9321 // The reduction root is used as the insertion point for new instructions, 9322 // so set it as externally used to prevent it from being deleted. 9323 ExternallyUsedValues[ReductionRoot]; 9324 SmallVector<Value *, 16> IgnoreList; 9325 for (ReductionOpsType &RdxOp : ReductionOps) 9326 IgnoreList.append(RdxOp.begin(), RdxOp.end()); 9327 9328 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals); 9329 if (NumReducedVals > ReduxWidth) { 9330 // In the loop below, we are building a tree based on a window of 9331 // 'ReduxWidth' values. 9332 // If the operands of those values have common traits (compare predicate, 9333 // constant operand, etc), then we want to group those together to 9334 // minimize the cost of the reduction. 9335 9336 // TODO: This should be extended to count common operands for 9337 // compares and binops. 9338 9339 // Step 1: Count the number of times each compare predicate occurs. 9340 SmallDenseMap<unsigned, unsigned> PredCountMap; 9341 for (Value *RdxVal : ReducedVals) { 9342 CmpInst::Predicate Pred; 9343 if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value()))) 9344 ++PredCountMap[Pred]; 9345 } 9346 // Step 2: Sort the values so the most common predicates come first. 9347 stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) { 9348 CmpInst::Predicate PredA, PredB; 9349 if (match(A, m_Cmp(PredA, m_Value(), m_Value())) && 9350 match(B, m_Cmp(PredB, m_Value(), m_Value()))) { 9351 return PredCountMap[PredA] > PredCountMap[PredB]; 9352 } 9353 return false; 9354 }); 9355 } 9356 9357 Value *VectorizedTree = nullptr; 9358 unsigned i = 0; 9359 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) { 9360 ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth); 9361 V.buildTree(VL, IgnoreList); 9362 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) 9363 break; 9364 if (V.isLoadCombineReductionCandidate(RdxKind)) 9365 break; 9366 V.reorderTopToBottom(); 9367 V.reorderBottomToTop(/*IgnoreReorder=*/true); 9368 V.buildExternalUses(ExternallyUsedValues); 9369 9370 // For a poison-safe boolean logic reduction, do not replace select 9371 // instructions with logic ops. All reduced values will be frozen (see 9372 // below) to prevent leaking poison. 9373 if (isa<SelectInst>(ReductionRoot) && 9374 isBoolLogicOp(cast<Instruction>(ReductionRoot)) && 9375 NumReducedVals != ReduxWidth) 9376 break; 9377 9378 V.computeMinimumValueSizes(); 9379 9380 // Estimate cost. 9381 InstructionCost TreeCost = 9382 V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth)); 9383 InstructionCost ReductionCost = 9384 getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF); 9385 InstructionCost Cost = TreeCost + ReductionCost; 9386 if (!Cost.isValid()) { 9387 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n"); 9388 return nullptr; 9389 } 9390 if (Cost >= -SLPCostThreshold) { 9391 V.getORE()->emit([&]() { 9392 return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial", 9393 cast<Instruction>(VL[0])) 9394 << "Vectorizing horizontal reduction is possible" 9395 << "but not beneficial with cost " << ore::NV("Cost", Cost) 9396 << " and threshold " 9397 << ore::NV("Threshold", -SLPCostThreshold); 9398 }); 9399 break; 9400 } 9401 9402 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 9403 << Cost << ". (HorRdx)\n"); 9404 V.getORE()->emit([&]() { 9405 return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", 9406 cast<Instruction>(VL[0])) 9407 << "Vectorized horizontal reduction with cost " 9408 << ore::NV("Cost", Cost) << " and with tree size " 9409 << ore::NV("TreeSize", V.getTreeSize()); 9410 }); 9411 9412 // Vectorize a tree. 9413 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); 9414 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues); 9415 9416 // Emit a reduction. If the root is a select (min/max idiom), the insert 9417 // point is the compare condition of that select. 9418 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 9419 if (isCmpSelMinMax(RdxRootInst)) 9420 Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst)); 9421 else 9422 Builder.SetInsertPoint(RdxRootInst); 9423 9424 // To prevent poison from leaking across what used to be sequential, safe, 9425 // scalar boolean logic operations, the reduction operand must be frozen. 9426 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst)) 9427 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); 9428 9429 Value *ReducedSubTree = 9430 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 9431 9432 if (!VectorizedTree) { 9433 // Initialize the final value in the reduction. 9434 VectorizedTree = ReducedSubTree; 9435 } else { 9436 // Update the final value in the reduction. 9437 Builder.SetCurrentDebugLocation(Loc); 9438 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9439 ReducedSubTree, "op.rdx", ReductionOps); 9440 } 9441 i += ReduxWidth; 9442 ReduxWidth = PowerOf2Floor(NumReducedVals - i); 9443 } 9444 9445 if (VectorizedTree) { 9446 // Finish the reduction. 9447 for (; i < NumReducedVals; ++i) { 9448 auto *I = cast<Instruction>(ReducedVals[i]); 9449 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9450 VectorizedTree = 9451 createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps); 9452 } 9453 for (auto &Pair : ExternallyUsedValues) { 9454 // Add each externally used value to the final reduction. 9455 for (auto *I : Pair.second) { 9456 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9457 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9458 Pair.first, "op.extra", I); 9459 } 9460 } 9461 9462 ReductionRoot->replaceAllUsesWith(VectorizedTree); 9463 9464 // Mark all scalar reduction ops for deletion, they are replaced by the 9465 // vector reductions. 9466 V.eraseInstructions(IgnoreList); 9467 } 9468 return VectorizedTree; 9469 } 9470 9471 unsigned numReductionValues() const { return ReducedVals.size(); } 9472 9473 private: 9474 /// Calculate the cost of a reduction. 9475 InstructionCost getReductionCost(TargetTransformInfo *TTI, 9476 Value *FirstReducedVal, unsigned ReduxWidth, 9477 FastMathFlags FMF) { 9478 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 9479 Type *ScalarTy = FirstReducedVal->getType(); 9480 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); 9481 InstructionCost VectorCost, ScalarCost; 9482 switch (RdxKind) { 9483 case RecurKind::Add: 9484 case RecurKind::Mul: 9485 case RecurKind::Or: 9486 case RecurKind::And: 9487 case RecurKind::Xor: 9488 case RecurKind::FAdd: 9489 case RecurKind::FMul: { 9490 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); 9491 VectorCost = 9492 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); 9493 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); 9494 break; 9495 } 9496 case RecurKind::FMax: 9497 case RecurKind::FMin: { 9498 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9499 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9500 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 9501 /*IsUnsigned=*/false, CostKind); 9502 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9503 ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, 9504 SclCondTy, RdxPred, CostKind) + 9505 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9506 SclCondTy, RdxPred, CostKind); 9507 break; 9508 } 9509 case RecurKind::SMax: 9510 case RecurKind::SMin: 9511 case RecurKind::UMax: 9512 case RecurKind::UMin: { 9513 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9514 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9515 bool IsUnsigned = 9516 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; 9517 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned, 9518 CostKind); 9519 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9520 ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, 9521 SclCondTy, RdxPred, CostKind) + 9522 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9523 SclCondTy, RdxPred, CostKind); 9524 break; 9525 } 9526 default: 9527 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 9528 } 9529 9530 // Scalar cost is repeated for N-1 elements. 9531 ScalarCost *= (ReduxWidth - 1); 9532 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost 9533 << " for reduction that starts with " << *FirstReducedVal 9534 << " (It is a splitting reduction)\n"); 9535 return VectorCost - ScalarCost; 9536 } 9537 9538 /// Emit a horizontal reduction of the vectorized value. 9539 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 9540 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 9541 assert(VectorizedValue && "Need to have a vectorized tree node"); 9542 assert(isPowerOf2_32(ReduxWidth) && 9543 "We only handle power-of-two reductions for now"); 9544 assert(RdxKind != RecurKind::FMulAdd && 9545 "A call to the llvm.fmuladd intrinsic is not handled yet"); 9546 9547 ++NumVectorInstructions; 9548 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind); 9549 } 9550 }; 9551 9552 } // end anonymous namespace 9553 9554 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { 9555 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) 9556 return cast<FixedVectorType>(IE->getType())->getNumElements(); 9557 9558 unsigned AggregateSize = 1; 9559 auto *IV = cast<InsertValueInst>(InsertInst); 9560 Type *CurrentType = IV->getType(); 9561 do { 9562 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 9563 for (auto *Elt : ST->elements()) 9564 if (Elt != ST->getElementType(0)) // check homogeneity 9565 return None; 9566 AggregateSize *= ST->getNumElements(); 9567 CurrentType = ST->getElementType(0); 9568 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 9569 AggregateSize *= AT->getNumElements(); 9570 CurrentType = AT->getElementType(); 9571 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { 9572 AggregateSize *= VT->getNumElements(); 9573 return AggregateSize; 9574 } else if (CurrentType->isSingleValueType()) { 9575 return AggregateSize; 9576 } else { 9577 return None; 9578 } 9579 } while (true); 9580 } 9581 9582 static void findBuildAggregate_rec(Instruction *LastInsertInst, 9583 TargetTransformInfo *TTI, 9584 SmallVectorImpl<Value *> &BuildVectorOpds, 9585 SmallVectorImpl<Value *> &InsertElts, 9586 unsigned OperandOffset) { 9587 do { 9588 Value *InsertedOperand = LastInsertInst->getOperand(1); 9589 Optional<unsigned> OperandIndex = 9590 getInsertIndex(LastInsertInst, OperandOffset); 9591 if (!OperandIndex) 9592 return; 9593 if (isa<InsertElementInst>(InsertedOperand) || 9594 isa<InsertValueInst>(InsertedOperand)) { 9595 findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, 9596 BuildVectorOpds, InsertElts, *OperandIndex); 9597 9598 } else { 9599 BuildVectorOpds[*OperandIndex] = InsertedOperand; 9600 InsertElts[*OperandIndex] = LastInsertInst; 9601 } 9602 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); 9603 } while (LastInsertInst != nullptr && 9604 (isa<InsertValueInst>(LastInsertInst) || 9605 isa<InsertElementInst>(LastInsertInst)) && 9606 LastInsertInst->hasOneUse()); 9607 } 9608 9609 /// Recognize construction of vectors like 9610 /// %ra = insertelement <4 x float> poison, float %s0, i32 0 9611 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 9612 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 9613 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 9614 /// starting from the last insertelement or insertvalue instruction. 9615 /// 9616 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, 9617 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 9618 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 9619 /// 9620 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 9621 /// 9622 /// \return true if it matches. 9623 static bool findBuildAggregate(Instruction *LastInsertInst, 9624 TargetTransformInfo *TTI, 9625 SmallVectorImpl<Value *> &BuildVectorOpds, 9626 SmallVectorImpl<Value *> &InsertElts) { 9627 9628 assert((isa<InsertElementInst>(LastInsertInst) || 9629 isa<InsertValueInst>(LastInsertInst)) && 9630 "Expected insertelement or insertvalue instruction!"); 9631 9632 assert((BuildVectorOpds.empty() && InsertElts.empty()) && 9633 "Expected empty result vectors!"); 9634 9635 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); 9636 if (!AggregateSize) 9637 return false; 9638 BuildVectorOpds.resize(*AggregateSize); 9639 InsertElts.resize(*AggregateSize); 9640 9641 findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0); 9642 llvm::erase_value(BuildVectorOpds, nullptr); 9643 llvm::erase_value(InsertElts, nullptr); 9644 if (BuildVectorOpds.size() >= 2) 9645 return true; 9646 9647 return false; 9648 } 9649 9650 /// Try and get a reduction value from a phi node. 9651 /// 9652 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 9653 /// if they come from either \p ParentBB or a containing loop latch. 9654 /// 9655 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 9656 /// if not possible. 9657 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 9658 BasicBlock *ParentBB, LoopInfo *LI) { 9659 // There are situations where the reduction value is not dominated by the 9660 // reduction phi. Vectorizing such cases has been reported to cause 9661 // miscompiles. See PR25787. 9662 auto DominatedReduxValue = [&](Value *R) { 9663 return isa<Instruction>(R) && 9664 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 9665 }; 9666 9667 Value *Rdx = nullptr; 9668 9669 // Return the incoming value if it comes from the same BB as the phi node. 9670 if (P->getIncomingBlock(0) == ParentBB) { 9671 Rdx = P->getIncomingValue(0); 9672 } else if (P->getIncomingBlock(1) == ParentBB) { 9673 Rdx = P->getIncomingValue(1); 9674 } 9675 9676 if (Rdx && DominatedReduxValue(Rdx)) 9677 return Rdx; 9678 9679 // Otherwise, check whether we have a loop latch to look at. 9680 Loop *BBL = LI->getLoopFor(ParentBB); 9681 if (!BBL) 9682 return nullptr; 9683 BasicBlock *BBLatch = BBL->getLoopLatch(); 9684 if (!BBLatch) 9685 return nullptr; 9686 9687 // There is a loop latch, return the incoming value if it comes from 9688 // that. This reduction pattern occasionally turns up. 9689 if (P->getIncomingBlock(0) == BBLatch) { 9690 Rdx = P->getIncomingValue(0); 9691 } else if (P->getIncomingBlock(1) == BBLatch) { 9692 Rdx = P->getIncomingValue(1); 9693 } 9694 9695 if (Rdx && DominatedReduxValue(Rdx)) 9696 return Rdx; 9697 9698 return nullptr; 9699 } 9700 9701 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { 9702 if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) 9703 return true; 9704 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) 9705 return true; 9706 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) 9707 return true; 9708 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) 9709 return true; 9710 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) 9711 return true; 9712 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) 9713 return true; 9714 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) 9715 return true; 9716 return false; 9717 } 9718 9719 /// Attempt to reduce a horizontal reduction. 9720 /// If it is legal to match a horizontal reduction feeding the phi node \a P 9721 /// with reduction operators \a Root (or one of its operands) in a basic block 9722 /// \a BB, then check if it can be done. If horizontal reduction is not found 9723 /// and root instruction is a binary operation, vectorization of the operands is 9724 /// attempted. 9725 /// \returns true if a horizontal reduction was matched and reduced or operands 9726 /// of one of the binary instruction were vectorized. 9727 /// \returns false if a horizontal reduction was not matched (or not possible) 9728 /// or no vectorization of any binary operation feeding \a Root instruction was 9729 /// performed. 9730 static bool tryToVectorizeHorReductionOrInstOperands( 9731 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 9732 TargetTransformInfo *TTI, 9733 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 9734 if (!ShouldVectorizeHor) 9735 return false; 9736 9737 if (!Root) 9738 return false; 9739 9740 if (Root->getParent() != BB || isa<PHINode>(Root)) 9741 return false; 9742 // Start analysis starting from Root instruction. If horizontal reduction is 9743 // found, try to vectorize it. If it is not a horizontal reduction or 9744 // vectorization is not possible or not effective, and currently analyzed 9745 // instruction is a binary operation, try to vectorize the operands, using 9746 // pre-order DFS traversal order. If the operands were not vectorized, repeat 9747 // the same procedure considering each operand as a possible root of the 9748 // horizontal reduction. 9749 // Interrupt the process if the Root instruction itself was vectorized or all 9750 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 9751 // Skip the analysis of CmpInsts.Compiler implements postanalysis of the 9752 // CmpInsts so we can skip extra attempts in 9753 // tryToVectorizeHorReductionOrInstOperands and save compile time. 9754 std::queue<std::pair<Instruction *, unsigned>> Stack; 9755 Stack.emplace(Root, 0); 9756 SmallPtrSet<Value *, 8> VisitedInstrs; 9757 SmallVector<WeakTrackingVH> PostponedInsts; 9758 bool Res = false; 9759 auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0, 9760 Value *&B1) -> Value * { 9761 bool IsBinop = matchRdxBop(Inst, B0, B1); 9762 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); 9763 if (IsBinop || IsSelect) { 9764 HorizontalReduction HorRdx; 9765 if (HorRdx.matchAssociativeReduction(P, Inst)) 9766 return HorRdx.tryToReduce(R, TTI); 9767 } 9768 return nullptr; 9769 }; 9770 while (!Stack.empty()) { 9771 Instruction *Inst; 9772 unsigned Level; 9773 std::tie(Inst, Level) = Stack.front(); 9774 Stack.pop(); 9775 // Do not try to analyze instruction that has already been vectorized. 9776 // This may happen when we vectorize instruction operands on a previous 9777 // iteration while stack was populated before that happened. 9778 if (R.isDeleted(Inst)) 9779 continue; 9780 Value *B0 = nullptr, *B1 = nullptr; 9781 if (Value *V = TryToReduce(Inst, B0, B1)) { 9782 Res = true; 9783 // Set P to nullptr to avoid re-analysis of phi node in 9784 // matchAssociativeReduction function unless this is the root node. 9785 P = nullptr; 9786 if (auto *I = dyn_cast<Instruction>(V)) { 9787 // Try to find another reduction. 9788 Stack.emplace(I, Level); 9789 continue; 9790 } 9791 } else { 9792 bool IsBinop = B0 && B1; 9793 if (P && IsBinop) { 9794 Inst = dyn_cast<Instruction>(B0); 9795 if (Inst == P) 9796 Inst = dyn_cast<Instruction>(B1); 9797 if (!Inst) { 9798 // Set P to nullptr to avoid re-analysis of phi node in 9799 // matchAssociativeReduction function unless this is the root node. 9800 P = nullptr; 9801 continue; 9802 } 9803 } 9804 // Set P to nullptr to avoid re-analysis of phi node in 9805 // matchAssociativeReduction function unless this is the root node. 9806 P = nullptr; 9807 // Do not try to vectorize CmpInst operands, this is done separately. 9808 // Final attempt for binop args vectorization should happen after the loop 9809 // to try to find reductions. 9810 if (!isa<CmpInst>(Inst)) 9811 PostponedInsts.push_back(Inst); 9812 } 9813 9814 // Try to vectorize operands. 9815 // Continue analysis for the instruction from the same basic block only to 9816 // save compile time. 9817 if (++Level < RecursionMaxDepth) 9818 for (auto *Op : Inst->operand_values()) 9819 if (VisitedInstrs.insert(Op).second) 9820 if (auto *I = dyn_cast<Instruction>(Op)) 9821 // Do not try to vectorize CmpInst operands, this is done 9822 // separately. 9823 if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) && 9824 I->getParent() == BB) 9825 Stack.emplace(I, Level); 9826 } 9827 // Try to vectorized binops where reductions were not found. 9828 for (Value *V : PostponedInsts) 9829 if (auto *Inst = dyn_cast<Instruction>(V)) 9830 if (!R.isDeleted(Inst)) 9831 Res |= Vectorize(Inst, R); 9832 return Res; 9833 } 9834 9835 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 9836 BasicBlock *BB, BoUpSLP &R, 9837 TargetTransformInfo *TTI) { 9838 auto *I = dyn_cast_or_null<Instruction>(V); 9839 if (!I) 9840 return false; 9841 9842 if (!isa<BinaryOperator>(I)) 9843 P = nullptr; 9844 // Try to match and vectorize a horizontal reduction. 9845 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 9846 return tryToVectorize(I, R); 9847 }; 9848 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, 9849 ExtraVectorization); 9850 } 9851 9852 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 9853 BasicBlock *BB, BoUpSLP &R) { 9854 const DataLayout &DL = BB->getModule()->getDataLayout(); 9855 if (!R.canMapToVector(IVI->getType(), DL)) 9856 return false; 9857 9858 SmallVector<Value *, 16> BuildVectorOpds; 9859 SmallVector<Value *, 16> BuildVectorInsts; 9860 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) 9861 return false; 9862 9863 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 9864 // Aggregate value is unlikely to be processed in vector register. 9865 return tryToVectorizeList(BuildVectorOpds, R); 9866 } 9867 9868 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 9869 BasicBlock *BB, BoUpSLP &R) { 9870 SmallVector<Value *, 16> BuildVectorInsts; 9871 SmallVector<Value *, 16> BuildVectorOpds; 9872 SmallVector<int> Mask; 9873 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || 9874 (llvm::all_of( 9875 BuildVectorOpds, 9876 [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) && 9877 isFixedVectorShuffle(BuildVectorOpds, Mask))) 9878 return false; 9879 9880 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"); 9881 return tryToVectorizeList(BuildVectorInsts, R); 9882 } 9883 9884 template <typename T> 9885 static bool 9886 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, 9887 function_ref<unsigned(T *)> Limit, 9888 function_ref<bool(T *, T *)> Comparator, 9889 function_ref<bool(T *, T *)> AreCompatible, 9890 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper, 9891 bool LimitForRegisterSize) { 9892 bool Changed = false; 9893 // Sort by type, parent, operands. 9894 stable_sort(Incoming, Comparator); 9895 9896 // Try to vectorize elements base on their type. 9897 SmallVector<T *> Candidates; 9898 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { 9899 // Look for the next elements with the same type, parent and operand 9900 // kinds. 9901 auto *SameTypeIt = IncIt; 9902 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) 9903 ++SameTypeIt; 9904 9905 // Try to vectorize them. 9906 unsigned NumElts = (SameTypeIt - IncIt); 9907 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes (" 9908 << NumElts << ")\n"); 9909 // The vectorization is a 3-state attempt: 9910 // 1. Try to vectorize instructions with the same/alternate opcodes with the 9911 // size of maximal register at first. 9912 // 2. Try to vectorize remaining instructions with the same type, if 9913 // possible. This may result in the better vectorization results rather than 9914 // if we try just to vectorize instructions with the same/alternate opcodes. 9915 // 3. Final attempt to try to vectorize all instructions with the 9916 // same/alternate ops only, this may result in some extra final 9917 // vectorization. 9918 if (NumElts > 1 && 9919 TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { 9920 // Success start over because instructions might have been changed. 9921 Changed = true; 9922 } else if (NumElts < Limit(*IncIt) && 9923 (Candidates.empty() || 9924 Candidates.front()->getType() == (*IncIt)->getType())) { 9925 Candidates.append(IncIt, std::next(IncIt, NumElts)); 9926 } 9927 // Final attempt to vectorize instructions with the same types. 9928 if (Candidates.size() > 1 && 9929 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { 9930 if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) { 9931 // Success start over because instructions might have been changed. 9932 Changed = true; 9933 } else if (LimitForRegisterSize) { 9934 // Try to vectorize using small vectors. 9935 for (auto *It = Candidates.begin(), *End = Candidates.end(); 9936 It != End;) { 9937 auto *SameTypeIt = It; 9938 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) 9939 ++SameTypeIt; 9940 unsigned NumElts = (SameTypeIt - It); 9941 if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts), 9942 /*LimitForRegisterSize=*/false)) 9943 Changed = true; 9944 It = SameTypeIt; 9945 } 9946 } 9947 Candidates.clear(); 9948 } 9949 9950 // Start over at the next instruction of a different type (or the end). 9951 IncIt = SameTypeIt; 9952 } 9953 return Changed; 9954 } 9955 9956 /// Compare two cmp instructions. If IsCompatibility is true, function returns 9957 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding 9958 /// operands. If IsCompatibility is false, function implements strict weak 9959 /// ordering relation between two cmp instructions, returning true if the first 9960 /// instruction is "less" than the second, i.e. its predicate is less than the 9961 /// predicate of the second or the operands IDs are less than the operands IDs 9962 /// of the second cmp instruction. 9963 template <bool IsCompatibility> 9964 static bool compareCmp(Value *V, Value *V2, 9965 function_ref<bool(Instruction *)> IsDeleted) { 9966 auto *CI1 = cast<CmpInst>(V); 9967 auto *CI2 = cast<CmpInst>(V2); 9968 if (IsDeleted(CI2) || !isValidElementType(CI2->getType())) 9969 return false; 9970 if (CI1->getOperand(0)->getType()->getTypeID() < 9971 CI2->getOperand(0)->getType()->getTypeID()) 9972 return !IsCompatibility; 9973 if (CI1->getOperand(0)->getType()->getTypeID() > 9974 CI2->getOperand(0)->getType()->getTypeID()) 9975 return false; 9976 CmpInst::Predicate Pred1 = CI1->getPredicate(); 9977 CmpInst::Predicate Pred2 = CI2->getPredicate(); 9978 CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1); 9979 CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2); 9980 CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1); 9981 CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2); 9982 if (BasePred1 < BasePred2) 9983 return !IsCompatibility; 9984 if (BasePred1 > BasePred2) 9985 return false; 9986 // Compare operands. 9987 bool LEPreds = Pred1 <= Pred2; 9988 bool GEPreds = Pred1 >= Pred2; 9989 for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) { 9990 auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1); 9991 auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1); 9992 if (Op1->getValueID() < Op2->getValueID()) 9993 return !IsCompatibility; 9994 if (Op1->getValueID() > Op2->getValueID()) 9995 return false; 9996 if (auto *I1 = dyn_cast<Instruction>(Op1)) 9997 if (auto *I2 = dyn_cast<Instruction>(Op2)) { 9998 if (I1->getParent() != I2->getParent()) 9999 return false; 10000 InstructionsState S = getSameOpcode({I1, I2}); 10001 if (S.getOpcode()) 10002 continue; 10003 return false; 10004 } 10005 } 10006 return IsCompatibility; 10007 } 10008 10009 bool SLPVectorizerPass::vectorizeSimpleInstructions( 10010 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R, 10011 bool AtTerminator) { 10012 bool OpsChanged = false; 10013 SmallVector<Instruction *, 4> PostponedCmps; 10014 for (auto *I : reverse(Instructions)) { 10015 if (R.isDeleted(I)) 10016 continue; 10017 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) 10018 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 10019 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) 10020 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 10021 else if (isa<CmpInst>(I)) 10022 PostponedCmps.push_back(I); 10023 } 10024 if (AtTerminator) { 10025 // Try to find reductions first. 10026 for (Instruction *I : PostponedCmps) { 10027 if (R.isDeleted(I)) 10028 continue; 10029 for (Value *Op : I->operands()) 10030 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); 10031 } 10032 // Try to vectorize operands as vector bundles. 10033 for (Instruction *I : PostponedCmps) { 10034 if (R.isDeleted(I)) 10035 continue; 10036 OpsChanged |= tryToVectorize(I, R); 10037 } 10038 // Try to vectorize list of compares. 10039 // Sort by type, compare predicate, etc. 10040 auto &&CompareSorter = [&R](Value *V, Value *V2) { 10041 return compareCmp<false>(V, V2, 10042 [&R](Instruction *I) { return R.isDeleted(I); }); 10043 }; 10044 10045 auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) { 10046 if (V1 == V2) 10047 return true; 10048 return compareCmp<true>(V1, V2, 10049 [&R](Instruction *I) { return R.isDeleted(I); }); 10050 }; 10051 auto Limit = [&R](Value *V) { 10052 unsigned EltSize = R.getVectorElementSize(V); 10053 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10054 }; 10055 10056 SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end()); 10057 OpsChanged |= tryToVectorizeSequence<Value>( 10058 Vals, Limit, CompareSorter, AreCompatibleCompares, 10059 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10060 // Exclude possible reductions from other blocks. 10061 bool ArePossiblyReducedInOtherBlock = 10062 any_of(Candidates, [](Value *V) { 10063 return any_of(V->users(), [V](User *U) { 10064 return isa<SelectInst>(U) && 10065 cast<SelectInst>(U)->getParent() != 10066 cast<Instruction>(V)->getParent(); 10067 }); 10068 }); 10069 if (ArePossiblyReducedInOtherBlock) 10070 return false; 10071 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10072 }, 10073 /*LimitForRegisterSize=*/true); 10074 Instructions.clear(); 10075 } else { 10076 // Insert in reverse order since the PostponedCmps vector was filled in 10077 // reverse order. 10078 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend()); 10079 } 10080 return OpsChanged; 10081 } 10082 10083 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 10084 bool Changed = false; 10085 SmallVector<Value *, 4> Incoming; 10086 SmallPtrSet<Value *, 16> VisitedInstrs; 10087 // Maps phi nodes to the non-phi nodes found in the use tree for each phi 10088 // node. Allows better to identify the chains that can be vectorized in the 10089 // better way. 10090 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; 10091 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { 10092 assert(isValidElementType(V1->getType()) && 10093 isValidElementType(V2->getType()) && 10094 "Expected vectorizable types only."); 10095 // It is fine to compare type IDs here, since we expect only vectorizable 10096 // types, like ints, floats and pointers, we don't care about other type. 10097 if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) 10098 return true; 10099 if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) 10100 return false; 10101 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10102 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10103 if (Opcodes1.size() < Opcodes2.size()) 10104 return true; 10105 if (Opcodes1.size() > Opcodes2.size()) 10106 return false; 10107 Optional<bool> ConstOrder; 10108 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10109 // Undefs are compatible with any other value. 10110 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) { 10111 if (!ConstOrder) 10112 ConstOrder = 10113 !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]); 10114 continue; 10115 } 10116 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10117 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10118 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); 10119 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); 10120 if (!NodeI1) 10121 return NodeI2 != nullptr; 10122 if (!NodeI2) 10123 return false; 10124 assert((NodeI1 == NodeI2) == 10125 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10126 "Different nodes should have different DFS numbers"); 10127 if (NodeI1 != NodeI2) 10128 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10129 InstructionsState S = getSameOpcode({I1, I2}); 10130 if (S.getOpcode()) 10131 continue; 10132 return I1->getOpcode() < I2->getOpcode(); 10133 } 10134 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) { 10135 if (!ConstOrder) 10136 ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID(); 10137 continue; 10138 } 10139 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) 10140 return true; 10141 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) 10142 return false; 10143 } 10144 return ConstOrder && *ConstOrder; 10145 }; 10146 auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) { 10147 if (V1 == V2) 10148 return true; 10149 if (V1->getType() != V2->getType()) 10150 return false; 10151 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10152 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10153 if (Opcodes1.size() != Opcodes2.size()) 10154 return false; 10155 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10156 // Undefs are compatible with any other value. 10157 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 10158 continue; 10159 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10160 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10161 if (I1->getParent() != I2->getParent()) 10162 return false; 10163 InstructionsState S = getSameOpcode({I1, I2}); 10164 if (S.getOpcode()) 10165 continue; 10166 return false; 10167 } 10168 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 10169 continue; 10170 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) 10171 return false; 10172 } 10173 return true; 10174 }; 10175 auto Limit = [&R](Value *V) { 10176 unsigned EltSize = R.getVectorElementSize(V); 10177 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10178 }; 10179 10180 bool HaveVectorizedPhiNodes = false; 10181 do { 10182 // Collect the incoming values from the PHIs. 10183 Incoming.clear(); 10184 for (Instruction &I : *BB) { 10185 PHINode *P = dyn_cast<PHINode>(&I); 10186 if (!P) 10187 break; 10188 10189 // No need to analyze deleted, vectorized and non-vectorizable 10190 // instructions. 10191 if (!VisitedInstrs.count(P) && !R.isDeleted(P) && 10192 isValidElementType(P->getType())) 10193 Incoming.push_back(P); 10194 } 10195 10196 // Find the corresponding non-phi nodes for better matching when trying to 10197 // build the tree. 10198 for (Value *V : Incoming) { 10199 SmallVectorImpl<Value *> &Opcodes = 10200 PHIToOpcodes.try_emplace(V).first->getSecond(); 10201 if (!Opcodes.empty()) 10202 continue; 10203 SmallVector<Value *, 4> Nodes(1, V); 10204 SmallPtrSet<Value *, 4> Visited; 10205 while (!Nodes.empty()) { 10206 auto *PHI = cast<PHINode>(Nodes.pop_back_val()); 10207 if (!Visited.insert(PHI).second) 10208 continue; 10209 for (Value *V : PHI->incoming_values()) { 10210 if (auto *PHI1 = dyn_cast<PHINode>((V))) { 10211 Nodes.push_back(PHI1); 10212 continue; 10213 } 10214 Opcodes.emplace_back(V); 10215 } 10216 } 10217 } 10218 10219 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( 10220 Incoming, Limit, PHICompare, AreCompatiblePHIs, 10221 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10222 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10223 }, 10224 /*LimitForRegisterSize=*/true); 10225 Changed |= HaveVectorizedPhiNodes; 10226 VisitedInstrs.insert(Incoming.begin(), Incoming.end()); 10227 } while (HaveVectorizedPhiNodes); 10228 10229 VisitedInstrs.clear(); 10230 10231 SmallVector<Instruction *, 8> PostProcessInstructions; 10232 SmallDenseSet<Instruction *, 4> KeyNodes; 10233 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 10234 // Skip instructions with scalable type. The num of elements is unknown at 10235 // compile-time for scalable type. 10236 if (isa<ScalableVectorType>(it->getType())) 10237 continue; 10238 10239 // Skip instructions marked for the deletion. 10240 if (R.isDeleted(&*it)) 10241 continue; 10242 // We may go through BB multiple times so skip the one we have checked. 10243 if (!VisitedInstrs.insert(&*it).second) { 10244 if (it->use_empty() && KeyNodes.contains(&*it) && 10245 vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10246 it->isTerminator())) { 10247 // We would like to start over since some instructions are deleted 10248 // and the iterator may become invalid value. 10249 Changed = true; 10250 it = BB->begin(); 10251 e = BB->end(); 10252 } 10253 continue; 10254 } 10255 10256 if (isa<DbgInfoIntrinsic>(it)) 10257 continue; 10258 10259 // Try to vectorize reductions that use PHINodes. 10260 if (PHINode *P = dyn_cast<PHINode>(it)) { 10261 // Check that the PHI is a reduction PHI. 10262 if (P->getNumIncomingValues() == 2) { 10263 // Try to match and vectorize a horizontal reduction. 10264 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 10265 TTI)) { 10266 Changed = true; 10267 it = BB->begin(); 10268 e = BB->end(); 10269 continue; 10270 } 10271 } 10272 // Try to vectorize the incoming values of the PHI, to catch reductions 10273 // that feed into PHIs. 10274 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { 10275 // Skip if the incoming block is the current BB for now. Also, bypass 10276 // unreachable IR for efficiency and to avoid crashing. 10277 // TODO: Collect the skipped incoming values and try to vectorize them 10278 // after processing BB. 10279 if (BB == P->getIncomingBlock(I) || 10280 !DT->isReachableFromEntry(P->getIncomingBlock(I))) 10281 continue; 10282 10283 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), 10284 P->getIncomingBlock(I), R, TTI); 10285 } 10286 continue; 10287 } 10288 10289 // Ran into an instruction without users, like terminator, or function call 10290 // with ignored return value, store. Ignore unused instructions (basing on 10291 // instruction type, except for CallInst and InvokeInst). 10292 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 10293 isa<InvokeInst>(it))) { 10294 KeyNodes.insert(&*it); 10295 bool OpsChanged = false; 10296 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 10297 for (auto *V : it->operand_values()) { 10298 // Try to match and vectorize a horizontal reduction. 10299 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 10300 } 10301 } 10302 // Start vectorization of post-process list of instructions from the 10303 // top-tree instructions to try to vectorize as many instructions as 10304 // possible. 10305 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10306 it->isTerminator()); 10307 if (OpsChanged) { 10308 // We would like to start over since some instructions are deleted 10309 // and the iterator may become invalid value. 10310 Changed = true; 10311 it = BB->begin(); 10312 e = BB->end(); 10313 continue; 10314 } 10315 } 10316 10317 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 10318 isa<InsertValueInst>(it)) 10319 PostProcessInstructions.push_back(&*it); 10320 } 10321 10322 return Changed; 10323 } 10324 10325 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 10326 auto Changed = false; 10327 for (auto &Entry : GEPs) { 10328 // If the getelementptr list has fewer than two elements, there's nothing 10329 // to do. 10330 if (Entry.second.size() < 2) 10331 continue; 10332 10333 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 10334 << Entry.second.size() << ".\n"); 10335 10336 // Process the GEP list in chunks suitable for the target's supported 10337 // vector size. If a vector register can't hold 1 element, we are done. We 10338 // are trying to vectorize the index computations, so the maximum number of 10339 // elements is based on the size of the index expression, rather than the 10340 // size of the GEP itself (the target's pointer size). 10341 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 10342 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); 10343 if (MaxVecRegSize < EltSize) 10344 continue; 10345 10346 unsigned MaxElts = MaxVecRegSize / EltSize; 10347 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 10348 auto Len = std::min<unsigned>(BE - BI, MaxElts); 10349 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); 10350 10351 // Initialize a set a candidate getelementptrs. Note that we use a 10352 // SetVector here to preserve program order. If the index computations 10353 // are vectorizable and begin with loads, we want to minimize the chance 10354 // of having to reorder them later. 10355 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 10356 10357 // Some of the candidates may have already been vectorized after we 10358 // initially collected them. If so, they are marked as deleted, so remove 10359 // them from the set of candidates. 10360 Candidates.remove_if( 10361 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 10362 10363 // Remove from the set of candidates all pairs of getelementptrs with 10364 // constant differences. Such getelementptrs are likely not good 10365 // candidates for vectorization in a bottom-up phase since one can be 10366 // computed from the other. We also ensure all candidate getelementptr 10367 // indices are unique. 10368 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 10369 auto *GEPI = GEPList[I]; 10370 if (!Candidates.count(GEPI)) 10371 continue; 10372 auto *SCEVI = SE->getSCEV(GEPList[I]); 10373 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 10374 auto *GEPJ = GEPList[J]; 10375 auto *SCEVJ = SE->getSCEV(GEPList[J]); 10376 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 10377 Candidates.remove(GEPI); 10378 Candidates.remove(GEPJ); 10379 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 10380 Candidates.remove(GEPJ); 10381 } 10382 } 10383 } 10384 10385 // We break out of the above computation as soon as we know there are 10386 // fewer than two candidates remaining. 10387 if (Candidates.size() < 2) 10388 continue; 10389 10390 // Add the single, non-constant index of each candidate to the bundle. We 10391 // ensured the indices met these constraints when we originally collected 10392 // the getelementptrs. 10393 SmallVector<Value *, 16> Bundle(Candidates.size()); 10394 auto BundleIndex = 0u; 10395 for (auto *V : Candidates) { 10396 auto *GEP = cast<GetElementPtrInst>(V); 10397 auto *GEPIdx = GEP->idx_begin()->get(); 10398 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 10399 Bundle[BundleIndex++] = GEPIdx; 10400 } 10401 10402 // Try and vectorize the indices. We are currently only interested in 10403 // gather-like cases of the form: 10404 // 10405 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 10406 // 10407 // where the loads of "a", the loads of "b", and the subtractions can be 10408 // performed in parallel. It's likely that detecting this pattern in a 10409 // bottom-up phase will be simpler and less costly than building a 10410 // full-blown top-down phase beginning at the consecutive loads. 10411 Changed |= tryToVectorizeList(Bundle, R); 10412 } 10413 } 10414 return Changed; 10415 } 10416 10417 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 10418 bool Changed = false; 10419 // Sort by type, base pointers and values operand. Value operands must be 10420 // compatible (have the same opcode, same parent), otherwise it is 10421 // definitely not profitable to try to vectorize them. 10422 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { 10423 if (V->getPointerOperandType()->getTypeID() < 10424 V2->getPointerOperandType()->getTypeID()) 10425 return true; 10426 if (V->getPointerOperandType()->getTypeID() > 10427 V2->getPointerOperandType()->getTypeID()) 10428 return false; 10429 // UndefValues are compatible with all other values. 10430 if (isa<UndefValue>(V->getValueOperand()) || 10431 isa<UndefValue>(V2->getValueOperand())) 10432 return false; 10433 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) 10434 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10435 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = 10436 DT->getNode(I1->getParent()); 10437 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = 10438 DT->getNode(I2->getParent()); 10439 assert(NodeI1 && "Should only process reachable instructions"); 10440 assert(NodeI1 && "Should only process reachable instructions"); 10441 assert((NodeI1 == NodeI2) == 10442 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10443 "Different nodes should have different DFS numbers"); 10444 if (NodeI1 != NodeI2) 10445 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10446 InstructionsState S = getSameOpcode({I1, I2}); 10447 if (S.getOpcode()) 10448 return false; 10449 return I1->getOpcode() < I2->getOpcode(); 10450 } 10451 if (isa<Constant>(V->getValueOperand()) && 10452 isa<Constant>(V2->getValueOperand())) 10453 return false; 10454 return V->getValueOperand()->getValueID() < 10455 V2->getValueOperand()->getValueID(); 10456 }; 10457 10458 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) { 10459 if (V1 == V2) 10460 return true; 10461 if (V1->getPointerOperandType() != V2->getPointerOperandType()) 10462 return false; 10463 // Undefs are compatible with any other value. 10464 if (isa<UndefValue>(V1->getValueOperand()) || 10465 isa<UndefValue>(V2->getValueOperand())) 10466 return true; 10467 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) 10468 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10469 if (I1->getParent() != I2->getParent()) 10470 return false; 10471 InstructionsState S = getSameOpcode({I1, I2}); 10472 return S.getOpcode() > 0; 10473 } 10474 if (isa<Constant>(V1->getValueOperand()) && 10475 isa<Constant>(V2->getValueOperand())) 10476 return true; 10477 return V1->getValueOperand()->getValueID() == 10478 V2->getValueOperand()->getValueID(); 10479 }; 10480 auto Limit = [&R, this](StoreInst *SI) { 10481 unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 10482 return R.getMinVF(EltSize); 10483 }; 10484 10485 // Attempt to sort and vectorize each of the store-groups. 10486 for (auto &Pair : Stores) { 10487 if (Pair.second.size() < 2) 10488 continue; 10489 10490 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 10491 << Pair.second.size() << ".\n"); 10492 10493 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) 10494 continue; 10495 10496 Changed |= tryToVectorizeSequence<StoreInst>( 10497 Pair.second, Limit, StoreSorter, AreCompatibleStores, 10498 [this, &R](ArrayRef<StoreInst *> Candidates, bool) { 10499 return vectorizeStores(Candidates, R); 10500 }, 10501 /*LimitForRegisterSize=*/false); 10502 } 10503 return Changed; 10504 } 10505 10506 char SLPVectorizer::ID = 0; 10507 10508 static const char lv_name[] = "SLP Vectorizer"; 10509 10510 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 10511 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 10512 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 10513 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10514 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 10515 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 10516 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 10517 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 10518 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 10519 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 10520 10521 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 10522