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/ArrayRef.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/DenseSet.h" 23 #include "llvm/ADT/MapVector.h" 24 #include "llvm/ADT/None.h" 25 #include "llvm/ADT/Optional.h" 26 #include "llvm/ADT/PostOrderIterator.h" 27 #include "llvm/ADT/STLExtras.h" 28 #include "llvm/ADT/SetVector.h" 29 #include "llvm/ADT/SmallBitVector.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallSet.h" 32 #include "llvm/ADT/SmallVector.h" 33 #include "llvm/ADT/Statistic.h" 34 #include "llvm/ADT/iterator.h" 35 #include "llvm/ADT/iterator_range.h" 36 #include "llvm/Analysis/AliasAnalysis.h" 37 #include "llvm/Analysis/CodeMetrics.h" 38 #include "llvm/Analysis/DemandedBits.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/LoopAccessAnalysis.h" 41 #include "llvm/Analysis/LoopInfo.h" 42 #include "llvm/Analysis/MemoryLocation.h" 43 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 44 #include "llvm/Analysis/ScalarEvolution.h" 45 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 46 #include "llvm/Analysis/TargetLibraryInfo.h" 47 #include "llvm/Analysis/TargetTransformInfo.h" 48 #include "llvm/Analysis/ValueTracking.h" 49 #include "llvm/Analysis/VectorUtils.h" 50 #include "llvm/IR/Attributes.h" 51 #include "llvm/IR/BasicBlock.h" 52 #include "llvm/IR/Constant.h" 53 #include "llvm/IR/Constants.h" 54 #include "llvm/IR/DataLayout.h" 55 #include "llvm/IR/DebugLoc.h" 56 #include "llvm/IR/DerivedTypes.h" 57 #include "llvm/IR/Dominators.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/IRBuilder.h" 60 #include "llvm/IR/InstrTypes.h" 61 #include "llvm/IR/Instruction.h" 62 #include "llvm/IR/Instructions.h" 63 #include "llvm/IR/IntrinsicInst.h" 64 #include "llvm/IR/Intrinsics.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/NoFolder.h" 67 #include "llvm/IR/Operator.h" 68 #include "llvm/IR/PassManager.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/KnownBits.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 89 #include "llvm/Transforms/Utils/LoopUtils.h" 90 #include "llvm/Transforms/Vectorize.h" 91 #include <algorithm> 92 #include <cassert> 93 #include <cstdint> 94 #include <iterator> 95 #include <memory> 96 #include <set> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 using namespace llvm::PatternMatch; 104 using namespace slpvectorizer; 105 106 #define SV_NAME "slp-vectorizer" 107 #define DEBUG_TYPE "SLP" 108 109 STATISTIC(NumVectorInstructions, "Number of vector instructions generated"); 110 111 cl::opt<bool> 112 llvm::RunSLPVectorization("vectorize-slp", cl::init(false), 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<int> 134 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden, 135 cl::desc("Maximum depth of the lookup for consecutive stores.")); 136 137 /// Limits the size of scheduling regions in a block. 138 /// It avoid long compile times for _very_ large blocks where vector 139 /// instructions are spread over a wide range. 140 /// This limit is way higher than needed by real-world functions. 141 static cl::opt<int> 142 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, 143 cl::desc("Limit the size of the SLP scheduling region per block")); 144 145 static cl::opt<int> MinVectorRegSizeOption( 146 "slp-min-reg-size", cl::init(128), cl::Hidden, 147 cl::desc("Attempt to vectorize for this register size in bits")); 148 149 static cl::opt<unsigned> RecursionMaxDepth( 150 "slp-recursion-max-depth", cl::init(12), cl::Hidden, 151 cl::desc("Limit the recursion depth when building a vectorizable tree")); 152 153 static cl::opt<unsigned> MinTreeSize( 154 "slp-min-tree-size", cl::init(3), cl::Hidden, 155 cl::desc("Only vectorize small trees if they are fully vectorizable")); 156 157 // The maximum depth that the look-ahead score heuristic will explore. 158 // The higher this value, the higher the compilation time overhead. 159 static cl::opt<int> LookAheadMaxDepth( 160 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden, 161 cl::desc("The maximum look-ahead depth for operand reordering scores")); 162 163 // The Look-ahead heuristic goes through the users of the bundle to calculate 164 // the users cost in getExternalUsesCost(). To avoid compilation time increase 165 // we limit the number of users visited to this value. 166 static cl::opt<unsigned> LookAheadUsersBudget( 167 "slp-look-ahead-users-budget", cl::init(2), cl::Hidden, 168 cl::desc("The maximum number of users to visit while visiting the " 169 "predecessors. This prevents compilation time increase.")); 170 171 static cl::opt<bool> 172 ViewSLPTree("view-slp-tree", cl::Hidden, 173 cl::desc("Display the SLP trees with Graphviz")); 174 175 // Limit the number of alias checks. The limit is chosen so that 176 // it has no negative effect on the llvm benchmarks. 177 static const unsigned AliasedCheckLimit = 10; 178 179 // Another limit for the alias checks: The maximum distance between load/store 180 // instructions where alias checks are done. 181 // This limit is useful for very large basic blocks. 182 static const unsigned MaxMemDepDistance = 160; 183 184 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling 185 /// regions to be handled. 186 static const int MinScheduleRegionSize = 16; 187 188 /// Predicate for the element types that the SLP vectorizer supports. 189 /// 190 /// The most important thing to filter here are types which are invalid in LLVM 191 /// vectors. We also filter target specific types which have absolutely no 192 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just 193 /// avoids spending time checking the cost model and realizing that they will 194 /// be inevitably scalarized. 195 static bool isValidElementType(Type *Ty) { 196 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && 197 !Ty->isPPC_FP128Ty(); 198 } 199 200 /// \returns true if all of the instructions in \p VL are in the same block or 201 /// false otherwise. 202 static bool allSameBlock(ArrayRef<Value *> VL) { 203 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 204 if (!I0) 205 return false; 206 BasicBlock *BB = I0->getParent(); 207 for (int i = 1, e = VL.size(); i < e; i++) { 208 Instruction *I = dyn_cast<Instruction>(VL[i]); 209 if (!I) 210 return false; 211 212 if (BB != I->getParent()) 213 return false; 214 } 215 return true; 216 } 217 218 /// \returns True if all of the values in \p VL are constants (but not 219 /// globals/constant expressions). 220 static bool allConstant(ArrayRef<Value *> VL) { 221 // Constant expressions and globals can't be vectorized like normal integer/FP 222 // constants. 223 for (Value *i : VL) 224 if (!isa<Constant>(i) || isa<ConstantExpr>(i) || isa<GlobalValue>(i)) 225 return false; 226 return true; 227 } 228 229 /// \returns True if all of the values in \p VL are identical. 230 static bool isSplat(ArrayRef<Value *> VL) { 231 for (unsigned i = 1, e = VL.size(); i < e; ++i) 232 if (VL[i] != VL[0]) 233 return false; 234 return true; 235 } 236 237 /// \returns True if \p I is commutative, handles CmpInst as well as Instruction. 238 static bool isCommutative(Instruction *I) { 239 if (auto *IC = dyn_cast<CmpInst>(I)) 240 return IC->isCommutative(); 241 return I->isCommutative(); 242 } 243 244 /// Checks if the vector of instructions can be represented as a shuffle, like: 245 /// %x0 = extractelement <4 x i8> %x, i32 0 246 /// %x3 = extractelement <4 x i8> %x, i32 3 247 /// %y1 = extractelement <4 x i8> %y, i32 1 248 /// %y2 = extractelement <4 x i8> %y, i32 2 249 /// %x0x0 = mul i8 %x0, %x0 250 /// %x3x3 = mul i8 %x3, %x3 251 /// %y1y1 = mul i8 %y1, %y1 252 /// %y2y2 = mul i8 %y2, %y2 253 /// %ins1 = insertelement <4 x i8> undef, i8 %x0x0, i32 0 254 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1 255 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2 256 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3 257 /// ret <4 x i8> %ins4 258 /// can be transformed into: 259 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5, 260 /// i32 6> 261 /// %2 = mul <4 x i8> %1, %1 262 /// ret <4 x i8> %2 263 /// We convert this initially to something like: 264 /// %x0 = extractelement <4 x i8> %x, i32 0 265 /// %x3 = extractelement <4 x i8> %x, i32 3 266 /// %y1 = extractelement <4 x i8> %y, i32 1 267 /// %y2 = extractelement <4 x i8> %y, i32 2 268 /// %1 = insertelement <4 x i8> undef, i8 %x0, i32 0 269 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1 270 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2 271 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3 272 /// %5 = mul <4 x i8> %4, %4 273 /// %6 = extractelement <4 x i8> %5, i32 0 274 /// %ins1 = insertelement <4 x i8> undef, i8 %6, i32 0 275 /// %7 = extractelement <4 x i8> %5, i32 1 276 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1 277 /// %8 = extractelement <4 x i8> %5, i32 2 278 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2 279 /// %9 = extractelement <4 x i8> %5, i32 3 280 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3 281 /// ret <4 x i8> %ins4 282 /// InstCombiner transforms this into a shuffle and vector mul 283 /// TODO: Can we split off and reuse the shuffle mask detection from 284 /// TargetTransformInfo::getInstructionThroughput? 285 static Optional<TargetTransformInfo::ShuffleKind> 286 isShuffle(ArrayRef<Value *> VL) { 287 auto *EI0 = cast<ExtractElementInst>(VL[0]); 288 unsigned Size = EI0->getVectorOperandType()->getVectorNumElements(); 289 Value *Vec1 = nullptr; 290 Value *Vec2 = nullptr; 291 enum ShuffleMode { Unknown, Select, Permute }; 292 ShuffleMode CommonShuffleMode = Unknown; 293 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 294 auto *EI = cast<ExtractElementInst>(VL[I]); 295 auto *Vec = EI->getVectorOperand(); 296 // All vector operands must have the same number of vector elements. 297 if (Vec->getType()->getVectorNumElements() != Size) 298 return None; 299 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand()); 300 if (!Idx) 301 return None; 302 // Undefined behavior if Idx is negative or >= Size. 303 if (Idx->getValue().uge(Size)) 304 continue; 305 unsigned IntIdx = Idx->getValue().getZExtValue(); 306 // We can extractelement from undef vector. 307 if (isa<UndefValue>(Vec)) 308 continue; 309 // For correct shuffling we have to have at most 2 different vector operands 310 // in all extractelement instructions. 311 if (!Vec1 || Vec1 == Vec) 312 Vec1 = Vec; 313 else if (!Vec2 || Vec2 == Vec) 314 Vec2 = Vec; 315 else 316 return None; 317 if (CommonShuffleMode == Permute) 318 continue; 319 // If the extract index is not the same as the operation number, it is a 320 // permutation. 321 if (IntIdx != I) { 322 CommonShuffleMode = Permute; 323 continue; 324 } 325 CommonShuffleMode = Select; 326 } 327 // If we're not crossing lanes in different vectors, consider it as blending. 328 if (CommonShuffleMode == Select && Vec2) 329 return TargetTransformInfo::SK_Select; 330 // If Vec2 was never used, we have a permutation of a single vector, otherwise 331 // we have permutation of 2 vectors. 332 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc 333 : TargetTransformInfo::SK_PermuteSingleSrc; 334 } 335 336 namespace { 337 338 /// Main data required for vectorization of instructions. 339 struct InstructionsState { 340 /// The very first instruction in the list with the main opcode. 341 Value *OpValue = nullptr; 342 343 /// The main/alternate instruction. 344 Instruction *MainOp = nullptr; 345 Instruction *AltOp = nullptr; 346 347 /// The main/alternate opcodes for the list of instructions. 348 unsigned getOpcode() const { 349 return MainOp ? MainOp->getOpcode() : 0; 350 } 351 352 unsigned getAltOpcode() const { 353 return AltOp ? AltOp->getOpcode() : 0; 354 } 355 356 /// Some of the instructions in the list have alternate opcodes. 357 bool isAltShuffle() const { return getOpcode() != getAltOpcode(); } 358 359 bool isOpcodeOrAlt(Instruction *I) const { 360 unsigned CheckedOpcode = I->getOpcode(); 361 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode; 362 } 363 364 InstructionsState() = delete; 365 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp) 366 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {} 367 }; 368 369 } // end anonymous namespace 370 371 /// Chooses the correct key for scheduling data. If \p Op has the same (or 372 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p 373 /// OpValue. 374 static Value *isOneOf(const InstructionsState &S, Value *Op) { 375 auto *I = dyn_cast<Instruction>(Op); 376 if (I && S.isOpcodeOrAlt(I)) 377 return Op; 378 return S.OpValue; 379 } 380 381 /// \returns true if \p Opcode is allowed as part of of the main/alternate 382 /// instruction for SLP vectorization. 383 /// 384 /// Example of unsupported opcode is SDIV that can potentially cause UB if the 385 /// "shuffled out" lane would result in division by zero. 386 static bool isValidForAlternation(unsigned Opcode) { 387 if (Instruction::isIntDivRem(Opcode)) 388 return false; 389 390 return true; 391 } 392 393 /// \returns analysis of the Instructions in \p VL described in 394 /// InstructionsState, the Opcode that we suppose the whole list 395 /// could be vectorized even if its structure is diverse. 396 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 397 unsigned BaseIndex = 0) { 398 // Make sure these are all Instructions. 399 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); })) 400 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 401 402 bool IsCastOp = isa<CastInst>(VL[BaseIndex]); 403 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]); 404 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode(); 405 unsigned AltOpcode = Opcode; 406 unsigned AltIndex = BaseIndex; 407 408 // Check for one alternate opcode from another BinaryOperator. 409 // TODO - generalize to support all operators (types, calls etc.). 410 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) { 411 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode(); 412 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) { 413 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 414 continue; 415 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) && 416 isValidForAlternation(Opcode)) { 417 AltOpcode = InstOpcode; 418 AltIndex = Cnt; 419 continue; 420 } 421 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) { 422 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType(); 423 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType(); 424 if (Ty0 == Ty1) { 425 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 426 continue; 427 if (Opcode == AltOpcode) { 428 assert(isValidForAlternation(Opcode) && 429 isValidForAlternation(InstOpcode) && 430 "Cast isn't safe for alternation, logic needs to be updated!"); 431 AltOpcode = InstOpcode; 432 AltIndex = Cnt; 433 continue; 434 } 435 } 436 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) 437 continue; 438 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 439 } 440 441 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]), 442 cast<Instruction>(VL[AltIndex])); 443 } 444 445 /// \returns true if all of the values in \p VL have the same type or false 446 /// otherwise. 447 static bool allSameType(ArrayRef<Value *> VL) { 448 Type *Ty = VL[0]->getType(); 449 for (int i = 1, e = VL.size(); i < e; i++) 450 if (VL[i]->getType() != Ty) 451 return false; 452 453 return true; 454 } 455 456 /// \returns True if Extract{Value,Element} instruction extracts element Idx. 457 static Optional<unsigned> getExtractIndex(Instruction *E) { 458 unsigned Opcode = E->getOpcode(); 459 assert((Opcode == Instruction::ExtractElement || 460 Opcode == Instruction::ExtractValue) && 461 "Expected extractelement or extractvalue instruction."); 462 if (Opcode == Instruction::ExtractElement) { 463 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 464 if (!CI) 465 return None; 466 return CI->getZExtValue(); 467 } 468 ExtractValueInst *EI = cast<ExtractValueInst>(E); 469 if (EI->getNumIndices() != 1) 470 return None; 471 return *EI->idx_begin(); 472 } 473 474 /// \returns True if in-tree use also needs extract. This refers to 475 /// possible scalar operand in vectorized instruction. 476 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, 477 TargetLibraryInfo *TLI) { 478 unsigned Opcode = UserInst->getOpcode(); 479 switch (Opcode) { 480 case Instruction::Load: { 481 LoadInst *LI = cast<LoadInst>(UserInst); 482 return (LI->getPointerOperand() == Scalar); 483 } 484 case Instruction::Store: { 485 StoreInst *SI = cast<StoreInst>(UserInst); 486 return (SI->getPointerOperand() == Scalar); 487 } 488 case Instruction::Call: { 489 CallInst *CI = cast<CallInst>(UserInst); 490 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 491 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) { 492 if (hasVectorInstrinsicScalarOpd(ID, i)) 493 return (CI->getArgOperand(i) == Scalar); 494 } 495 LLVM_FALLTHROUGH; 496 } 497 default: 498 return false; 499 } 500 } 501 502 /// \returns the AA location that is being access by the instruction. 503 static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) { 504 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 505 return MemoryLocation::get(SI); 506 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 507 return MemoryLocation::get(LI); 508 return MemoryLocation(); 509 } 510 511 /// \returns True if the instruction is not a volatile or atomic load/store. 512 static bool isSimple(Instruction *I) { 513 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 514 return LI->isSimple(); 515 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 516 return SI->isSimple(); 517 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 518 return !MI->isVolatile(); 519 return true; 520 } 521 522 namespace llvm { 523 524 namespace slpvectorizer { 525 526 /// Bottom Up SLP Vectorizer. 527 class BoUpSLP { 528 struct TreeEntry; 529 struct ScheduleData; 530 531 public: 532 using ValueList = SmallVector<Value *, 8>; 533 using InstrList = SmallVector<Instruction *, 16>; 534 using ValueSet = SmallPtrSet<Value *, 16>; 535 using StoreList = SmallVector<StoreInst *, 8>; 536 using ExtraValueToDebugLocsMap = 537 MapVector<Value *, SmallVector<Instruction *, 2>>; 538 539 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, 540 TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li, 541 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, 542 const DataLayout *DL, OptimizationRemarkEmitter *ORE) 543 : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), 544 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) { 545 CodeMetrics::collectEphemeralValues(F, AC, EphValues); 546 // Use the vector register size specified by the target unless overridden 547 // by a command-line option. 548 // TODO: It would be better to limit the vectorization factor based on 549 // data type rather than just register size. For example, x86 AVX has 550 // 256-bit registers, but it does not support integer operations 551 // at that width (that requires AVX2). 552 if (MaxVectorRegSizeOption.getNumOccurrences()) 553 MaxVecRegSize = MaxVectorRegSizeOption; 554 else 555 MaxVecRegSize = TTI->getRegisterBitWidth(true); 556 557 if (MinVectorRegSizeOption.getNumOccurrences()) 558 MinVecRegSize = MinVectorRegSizeOption; 559 else 560 MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); 561 } 562 563 /// Vectorize the tree that starts with the elements in \p VL. 564 /// Returns the vectorized root. 565 Value *vectorizeTree(); 566 567 /// Vectorize the tree but with the list of externally used values \p 568 /// ExternallyUsedValues. Values in this MapVector can be replaced but the 569 /// generated extractvalue instructions. 570 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues); 571 572 /// \returns the cost incurred by unwanted spills and fills, caused by 573 /// holding live values over call sites. 574 int getSpillCost() const; 575 576 /// \returns the vectorization cost of the subtree that starts at \p VL. 577 /// A negative number means that this is profitable. 578 int getTreeCost(); 579 580 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 581 /// the purpose of scheduling and extraction in the \p UserIgnoreLst. 582 void buildTree(ArrayRef<Value *> Roots, 583 ArrayRef<Value *> UserIgnoreLst = None); 584 585 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 586 /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking 587 /// into account (and updating it, if required) list of externally used 588 /// values stored in \p ExternallyUsedValues. 589 void buildTree(ArrayRef<Value *> Roots, 590 ExtraValueToDebugLocsMap &ExternallyUsedValues, 591 ArrayRef<Value *> UserIgnoreLst = None); 592 593 /// Clear the internal data structures that are created by 'buildTree'. 594 void deleteTree() { 595 VectorizableTree.clear(); 596 ScalarToTreeEntry.clear(); 597 MustGather.clear(); 598 ExternalUses.clear(); 599 NumOpsWantToKeepOrder.clear(); 600 NumOpsWantToKeepOriginalOrder = 0; 601 for (auto &Iter : BlocksSchedules) { 602 BlockScheduling *BS = Iter.second.get(); 603 BS->clear(); 604 } 605 MinBWs.clear(); 606 } 607 608 unsigned getTreeSize() const { return VectorizableTree.size(); } 609 610 /// Perform LICM and CSE on the newly generated gather sequences. 611 void optimizeGatherSequence(); 612 613 /// \returns The best order of instructions for vectorization. 614 Optional<ArrayRef<unsigned>> bestOrder() const { 615 auto I = std::max_element( 616 NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(), 617 [](const decltype(NumOpsWantToKeepOrder)::value_type &D1, 618 const decltype(NumOpsWantToKeepOrder)::value_type &D2) { 619 return D1.second < D2.second; 620 }); 621 if (I == NumOpsWantToKeepOrder.end() || 622 I->getSecond() <= NumOpsWantToKeepOriginalOrder) 623 return None; 624 625 return makeArrayRef(I->getFirst()); 626 } 627 628 /// \return The vector element size in bits to use when vectorizing the 629 /// expression tree ending at \p V. If V is a store, the size is the width of 630 /// the stored value. Otherwise, the size is the width of the largest loaded 631 /// value reaching V. This method is used by the vectorizer to calculate 632 /// vectorization factors. 633 unsigned getVectorElementSize(Value *V) const; 634 635 /// Compute the minimum type sizes required to represent the entries in a 636 /// vectorizable tree. 637 void computeMinimumValueSizes(); 638 639 // \returns maximum vector register size as set by TTI or overridden by cl::opt. 640 unsigned getMaxVecRegSize() const { 641 return MaxVecRegSize; 642 } 643 644 // \returns minimum vector register size as set by cl::opt. 645 unsigned getMinVecRegSize() const { 646 return MinVecRegSize; 647 } 648 649 /// Check if homogeneous aggregate is isomorphic to some VectorType. 650 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like 651 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> }, 652 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on. 653 /// 654 /// \returns number of elements in vector if isomorphism exists, 0 otherwise. 655 unsigned canMapToVector(Type *T, const DataLayout &DL) const; 656 657 /// \returns True if the VectorizableTree is both tiny and not fully 658 /// vectorizable. We do not vectorize such trees. 659 bool isTreeTinyAndNotFullyVectorizable() const; 660 661 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values 662 /// can be load combined in the backend. Load combining may not be allowed in 663 /// the IR optimizer, so we do not want to alter the pattern. For example, 664 /// partially transforming a scalar bswap() pattern into vector code is 665 /// effectively impossible for the backend to undo. 666 /// TODO: If load combining is allowed in the IR optimizer, this analysis 667 /// may not be necessary. 668 bool isLoadCombineReductionCandidate(unsigned ReductionOpcode) const; 669 670 OptimizationRemarkEmitter *getORE() { return ORE; } 671 672 /// This structure holds any data we need about the edges being traversed 673 /// during buildTree_rec(). We keep track of: 674 /// (i) the user TreeEntry index, and 675 /// (ii) the index of the edge. 676 struct EdgeInfo { 677 EdgeInfo() = default; 678 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx) 679 : UserTE(UserTE), EdgeIdx(EdgeIdx) {} 680 /// The user TreeEntry. 681 TreeEntry *UserTE = nullptr; 682 /// The operand index of the use. 683 unsigned EdgeIdx = UINT_MAX; 684 #ifndef NDEBUG 685 friend inline raw_ostream &operator<<(raw_ostream &OS, 686 const BoUpSLP::EdgeInfo &EI) { 687 EI.dump(OS); 688 return OS; 689 } 690 /// Debug print. 691 void dump(raw_ostream &OS) const { 692 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null") 693 << " EdgeIdx:" << EdgeIdx << "}"; 694 } 695 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); } 696 #endif 697 }; 698 699 /// A helper data structure to hold the operands of a vector of instructions. 700 /// This supports a fixed vector length for all operand vectors. 701 class VLOperands { 702 /// For each operand we need (i) the value, and (ii) the opcode that it 703 /// would be attached to if the expression was in a left-linearized form. 704 /// This is required to avoid illegal operand reordering. 705 /// For example: 706 /// \verbatim 707 /// 0 Op1 708 /// |/ 709 /// Op1 Op2 Linearized + Op2 710 /// \ / ----------> |/ 711 /// - - 712 /// 713 /// Op1 - Op2 (0 + Op1) - Op2 714 /// \endverbatim 715 /// 716 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'. 717 /// 718 /// Another way to think of this is to track all the operations across the 719 /// path from the operand all the way to the root of the tree and to 720 /// calculate the operation that corresponds to this path. For example, the 721 /// path from Op2 to the root crosses the RHS of the '-', therefore the 722 /// corresponding operation is a '-' (which matches the one in the 723 /// linearized tree, as shown above). 724 /// 725 /// For lack of a better term, we refer to this operation as Accumulated 726 /// Path Operation (APO). 727 struct OperandData { 728 OperandData() = default; 729 OperandData(Value *V, bool APO, bool IsUsed) 730 : V(V), APO(APO), IsUsed(IsUsed) {} 731 /// The operand value. 732 Value *V = nullptr; 733 /// TreeEntries only allow a single opcode, or an alternate sequence of 734 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the 735 /// APO. It is set to 'true' if 'V' is attached to an inverse operation 736 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise 737 /// (e.g., Add/Mul) 738 bool APO = false; 739 /// Helper data for the reordering function. 740 bool IsUsed = false; 741 }; 742 743 /// During operand reordering, we are trying to select the operand at lane 744 /// that matches best with the operand at the neighboring lane. Our 745 /// selection is based on the type of value we are looking for. For example, 746 /// if the neighboring lane has a load, we need to look for a load that is 747 /// accessing a consecutive address. These strategies are summarized in the 748 /// 'ReorderingMode' enumerator. 749 enum class ReorderingMode { 750 Load, ///< Matching loads to consecutive memory addresses 751 Opcode, ///< Matching instructions based on opcode (same or alternate) 752 Constant, ///< Matching constants 753 Splat, ///< Matching the same instruction multiple times (broadcast) 754 Failed, ///< We failed to create a vectorizable group 755 }; 756 757 using OperandDataVec = SmallVector<OperandData, 2>; 758 759 /// A vector of operand vectors. 760 SmallVector<OperandDataVec, 4> OpsVec; 761 762 const DataLayout &DL; 763 ScalarEvolution &SE; 764 const BoUpSLP &R; 765 766 /// \returns the operand data at \p OpIdx and \p Lane. 767 OperandData &getData(unsigned OpIdx, unsigned Lane) { 768 return OpsVec[OpIdx][Lane]; 769 } 770 771 /// \returns the operand data at \p OpIdx and \p Lane. Const version. 772 const OperandData &getData(unsigned OpIdx, unsigned Lane) const { 773 return OpsVec[OpIdx][Lane]; 774 } 775 776 /// Clears the used flag for all entries. 777 void clearUsed() { 778 for (unsigned OpIdx = 0, NumOperands = getNumOperands(); 779 OpIdx != NumOperands; ++OpIdx) 780 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 781 ++Lane) 782 OpsVec[OpIdx][Lane].IsUsed = false; 783 } 784 785 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2. 786 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) { 787 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]); 788 } 789 790 // The hard-coded scores listed here are not very important. When computing 791 // the scores of matching one sub-tree with another, we are basically 792 // counting the number of values that are matching. So even if all scores 793 // are set to 1, we would still get a decent matching result. 794 // However, sometimes we have to break ties. For example we may have to 795 // choose between matching loads vs matching opcodes. This is what these 796 // scores are helping us with: they provide the order of preference. 797 798 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]). 799 static const int ScoreConsecutiveLoads = 3; 800 /// ExtractElementInst from same vector and consecutive indexes. 801 static const int ScoreConsecutiveExtracts = 3; 802 /// Constants. 803 static const int ScoreConstants = 2; 804 /// Instructions with the same opcode. 805 static const int ScoreSameOpcode = 2; 806 /// Instructions with alt opcodes (e.g, add + sub). 807 static const int ScoreAltOpcodes = 1; 808 /// Identical instructions (a.k.a. splat or broadcast). 809 static const int ScoreSplat = 1; 810 /// Matching with an undef is preferable to failing. 811 static const int ScoreUndef = 1; 812 /// Score for failing to find a decent match. 813 static const int ScoreFail = 0; 814 /// User exteranl to the vectorized code. 815 static const int ExternalUseCost = 1; 816 /// The user is internal but in a different lane. 817 static const int UserInDiffLaneCost = ExternalUseCost; 818 819 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes. 820 static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL, 821 ScalarEvolution &SE) { 822 auto *LI1 = dyn_cast<LoadInst>(V1); 823 auto *LI2 = dyn_cast<LoadInst>(V2); 824 if (LI1 && LI2) 825 return isConsecutiveAccess(LI1, LI2, DL, SE) 826 ? VLOperands::ScoreConsecutiveLoads 827 : VLOperands::ScoreFail; 828 829 auto *C1 = dyn_cast<Constant>(V1); 830 auto *C2 = dyn_cast<Constant>(V2); 831 if (C1 && C2) 832 return VLOperands::ScoreConstants; 833 834 // Extracts from consecutive indexes of the same vector better score as 835 // the extracts could be optimized away. 836 Value *EV; 837 ConstantInt *Ex1Idx, *Ex2Idx; 838 if (match(V1, m_ExtractElement(m_Value(EV), m_ConstantInt(Ex1Idx))) && 839 match(V2, m_ExtractElement(m_Deferred(EV), m_ConstantInt(Ex2Idx))) && 840 Ex1Idx->getZExtValue() + 1 == Ex2Idx->getZExtValue()) 841 return VLOperands::ScoreConsecutiveExtracts; 842 843 auto *I1 = dyn_cast<Instruction>(V1); 844 auto *I2 = dyn_cast<Instruction>(V2); 845 if (I1 && I2) { 846 if (I1 == I2) 847 return VLOperands::ScoreSplat; 848 InstructionsState S = getSameOpcode({I1, I2}); 849 // Note: Only consider instructions with <= 2 operands to avoid 850 // complexity explosion. 851 if (S.getOpcode() && S.MainOp->getNumOperands() <= 2) 852 return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes 853 : VLOperands::ScoreSameOpcode; 854 } 855 856 if (isa<UndefValue>(V2)) 857 return VLOperands::ScoreUndef; 858 859 return VLOperands::ScoreFail; 860 } 861 862 /// Holds the values and their lane that are taking part in the look-ahead 863 /// score calculation. This is used in the external uses cost calculation. 864 SmallDenseMap<Value *, int> InLookAheadValues; 865 866 /// \Returns the additinal cost due to uses of \p LHS and \p RHS that are 867 /// either external to the vectorized code, or require shuffling. 868 int getExternalUsesCost(const std::pair<Value *, int> &LHS, 869 const std::pair<Value *, int> &RHS) { 870 int Cost = 0; 871 std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}}; 872 for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) { 873 Value *V = Values[Idx].first; 874 // Calculate the absolute lane, using the minimum relative lane of LHS 875 // and RHS as base and Idx as the offset. 876 int Ln = std::min(LHS.second, RHS.second) + Idx; 877 assert(Ln >= 0 && "Bad lane calculation"); 878 unsigned UsersBudget = LookAheadUsersBudget; 879 for (User *U : V->users()) { 880 if (const TreeEntry *UserTE = R.getTreeEntry(U)) { 881 // The user is in the VectorizableTree. Check if we need to insert. 882 auto It = llvm::find(UserTE->Scalars, U); 883 assert(It != UserTE->Scalars.end() && "U is in UserTE"); 884 int UserLn = std::distance(UserTE->Scalars.begin(), It); 885 assert(UserLn >= 0 && "Bad lane"); 886 if (UserLn != Ln) 887 Cost += UserInDiffLaneCost; 888 } else { 889 // Check if the user is in the look-ahead code. 890 auto It2 = InLookAheadValues.find(U); 891 if (It2 != InLookAheadValues.end()) { 892 // The user is in the look-ahead code. Check the lane. 893 if (It2->second != Ln) 894 Cost += UserInDiffLaneCost; 895 } else { 896 // The user is neither in SLP tree nor in the look-ahead code. 897 Cost += ExternalUseCost; 898 } 899 } 900 // Limit the number of visited uses to cap compilation time. 901 if (--UsersBudget == 0) 902 break; 903 } 904 } 905 return Cost; 906 } 907 908 /// Go through the operands of \p LHS and \p RHS recursively until \p 909 /// MaxLevel, and return the cummulative score. For example: 910 /// \verbatim 911 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1] 912 /// \ / \ / \ / \ / 913 /// + + + + 914 /// G1 G2 G3 G4 915 /// \endverbatim 916 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at 917 /// each level recursively, accumulating the score. It starts from matching 918 /// the additions at level 0, then moves on to the loads (level 1). The 919 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and 920 /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while 921 /// {A[0],C[0]} has a score of VLOperands::ScoreFail. 922 /// Please note that the order of the operands does not matter, as we 923 /// evaluate the score of all profitable combinations of operands. In 924 /// other words the score of G1 and G4 is the same as G1 and G2. This 925 /// heuristic is based on ideas described in: 926 /// Look-ahead SLP: Auto-vectorization in the presence of commutative 927 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha, 928 /// Luís F. W. Góes 929 int getScoreAtLevelRec(const std::pair<Value *, int> &LHS, 930 const std::pair<Value *, int> &RHS, int CurrLevel, 931 int MaxLevel) { 932 933 Value *V1 = LHS.first; 934 Value *V2 = RHS.first; 935 // Get the shallow score of V1 and V2. 936 int ShallowScoreAtThisLevel = 937 std::max((int)ScoreFail, getShallowScore(V1, V2, DL, SE) - 938 getExternalUsesCost(LHS, RHS)); 939 int Lane1 = LHS.second; 940 int Lane2 = RHS.second; 941 942 // If reached MaxLevel, 943 // or if V1 and V2 are not instructions, 944 // or if they are SPLAT, 945 // or if they are not consecutive, early return the current cost. 946 auto *I1 = dyn_cast<Instruction>(V1); 947 auto *I2 = dyn_cast<Instruction>(V2); 948 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 || 949 ShallowScoreAtThisLevel == VLOperands::ScoreFail || 950 (isa<LoadInst>(I1) && isa<LoadInst>(I2) && ShallowScoreAtThisLevel)) 951 return ShallowScoreAtThisLevel; 952 assert(I1 && I2 && "Should have early exited."); 953 954 // Keep track of in-tree values for determining the external-use cost. 955 InLookAheadValues[V1] = Lane1; 956 InLookAheadValues[V2] = Lane2; 957 958 // Contains the I2 operand indexes that got matched with I1 operands. 959 SmallSet<unsigned, 4> Op2Used; 960 961 // Recursion towards the operands of I1 and I2. We are trying all possbile 962 // operand pairs, and keeping track of the best score. 963 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands(); 964 OpIdx1 != NumOperands1; ++OpIdx1) { 965 // Try to pair op1I with the best operand of I2. 966 int MaxTmpScore = 0; 967 unsigned MaxOpIdx2 = 0; 968 bool FoundBest = false; 969 // If I2 is commutative try all combinations. 970 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1; 971 unsigned ToIdx = isCommutative(I2) 972 ? I2->getNumOperands() 973 : std::min(I2->getNumOperands(), OpIdx1 + 1); 974 assert(FromIdx <= ToIdx && "Bad index"); 975 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) { 976 // Skip operands already paired with OpIdx1. 977 if (Op2Used.count(OpIdx2)) 978 continue; 979 // Recursively calculate the cost at each level 980 int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1}, 981 {I2->getOperand(OpIdx2), Lane2}, 982 CurrLevel + 1, MaxLevel); 983 // Look for the best score. 984 if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) { 985 MaxTmpScore = TmpScore; 986 MaxOpIdx2 = OpIdx2; 987 FoundBest = true; 988 } 989 } 990 if (FoundBest) { 991 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it. 992 Op2Used.insert(MaxOpIdx2); 993 ShallowScoreAtThisLevel += MaxTmpScore; 994 } 995 } 996 return ShallowScoreAtThisLevel; 997 } 998 999 /// \Returns the look-ahead score, which tells us how much the sub-trees 1000 /// rooted at \p LHS and \p RHS match, the more they match the higher the 1001 /// score. This helps break ties in an informed way when we cannot decide on 1002 /// the order of the operands by just considering the immediate 1003 /// predecessors. 1004 int getLookAheadScore(const std::pair<Value *, int> &LHS, 1005 const std::pair<Value *, int> &RHS) { 1006 InLookAheadValues.clear(); 1007 return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth); 1008 } 1009 1010 // Search all operands in Ops[*][Lane] for the one that matches best 1011 // Ops[OpIdx][LastLane] and return its opreand index. 1012 // If no good match can be found, return None. 1013 Optional<unsigned> 1014 getBestOperand(unsigned OpIdx, int Lane, int LastLane, 1015 ArrayRef<ReorderingMode> ReorderingModes) { 1016 unsigned NumOperands = getNumOperands(); 1017 1018 // The operand of the previous lane at OpIdx. 1019 Value *OpLastLane = getData(OpIdx, LastLane).V; 1020 1021 // Our strategy mode for OpIdx. 1022 ReorderingMode RMode = ReorderingModes[OpIdx]; 1023 1024 // The linearized opcode of the operand at OpIdx, Lane. 1025 bool OpIdxAPO = getData(OpIdx, Lane).APO; 1026 1027 // The best operand index and its score. 1028 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we 1029 // are using the score to differentiate between the two. 1030 struct BestOpData { 1031 Optional<unsigned> Idx = None; 1032 unsigned Score = 0; 1033 } BestOp; 1034 1035 // Iterate through all unused operands and look for the best. 1036 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) { 1037 // Get the operand at Idx and Lane. 1038 OperandData &OpData = getData(Idx, Lane); 1039 Value *Op = OpData.V; 1040 bool OpAPO = OpData.APO; 1041 1042 // Skip already selected operands. 1043 if (OpData.IsUsed) 1044 continue; 1045 1046 // Skip if we are trying to move the operand to a position with a 1047 // different opcode in the linearized tree form. This would break the 1048 // semantics. 1049 if (OpAPO != OpIdxAPO) 1050 continue; 1051 1052 // Look for an operand that matches the current mode. 1053 switch (RMode) { 1054 case ReorderingMode::Load: 1055 case ReorderingMode::Constant: 1056 case ReorderingMode::Opcode: { 1057 bool LeftToRight = Lane > LastLane; 1058 Value *OpLeft = (LeftToRight) ? OpLastLane : Op; 1059 Value *OpRight = (LeftToRight) ? Op : OpLastLane; 1060 unsigned Score = 1061 getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane}); 1062 if (Score > BestOp.Score) { 1063 BestOp.Idx = Idx; 1064 BestOp.Score = Score; 1065 } 1066 break; 1067 } 1068 case ReorderingMode::Splat: 1069 if (Op == OpLastLane) 1070 BestOp.Idx = Idx; 1071 break; 1072 case ReorderingMode::Failed: 1073 return None; 1074 } 1075 } 1076 1077 if (BestOp.Idx) { 1078 getData(BestOp.Idx.getValue(), Lane).IsUsed = true; 1079 return BestOp.Idx; 1080 } 1081 // If we could not find a good match return None. 1082 return None; 1083 } 1084 1085 /// Helper for reorderOperandVecs. \Returns the lane that we should start 1086 /// reordering from. This is the one which has the least number of operands 1087 /// that can freely move about. 1088 unsigned getBestLaneToStartReordering() const { 1089 unsigned BestLane = 0; 1090 unsigned Min = UINT_MAX; 1091 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 1092 ++Lane) { 1093 unsigned NumFreeOps = getMaxNumOperandsThatCanBeReordered(Lane); 1094 if (NumFreeOps < Min) { 1095 Min = NumFreeOps; 1096 BestLane = Lane; 1097 } 1098 } 1099 return BestLane; 1100 } 1101 1102 /// \Returns the maximum number of operands that are allowed to be reordered 1103 /// for \p Lane. This is used as a heuristic for selecting the first lane to 1104 /// start operand reordering. 1105 unsigned getMaxNumOperandsThatCanBeReordered(unsigned Lane) const { 1106 unsigned CntTrue = 0; 1107 unsigned NumOperands = getNumOperands(); 1108 // Operands with the same APO can be reordered. We therefore need to count 1109 // how many of them we have for each APO, like this: Cnt[APO] = x. 1110 // Since we only have two APOs, namely true and false, we can avoid using 1111 // a map. Instead we can simply count the number of operands that 1112 // correspond to one of them (in this case the 'true' APO), and calculate 1113 // the other by subtracting it from the total number of operands. 1114 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) 1115 if (getData(OpIdx, Lane).APO) 1116 ++CntTrue; 1117 unsigned CntFalse = NumOperands - CntTrue; 1118 return std::max(CntTrue, CntFalse); 1119 } 1120 1121 /// Go through the instructions in VL and append their operands. 1122 void appendOperandsOfVL(ArrayRef<Value *> VL) { 1123 assert(!VL.empty() && "Bad VL"); 1124 assert((empty() || VL.size() == getNumLanes()) && 1125 "Expected same number of lanes"); 1126 assert(isa<Instruction>(VL[0]) && "Expected instruction"); 1127 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands(); 1128 OpsVec.resize(NumOperands); 1129 unsigned NumLanes = VL.size(); 1130 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1131 OpsVec[OpIdx].resize(NumLanes); 1132 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1133 assert(isa<Instruction>(VL[Lane]) && "Expected instruction"); 1134 // Our tree has just 3 nodes: the root and two operands. 1135 // It is therefore trivial to get the APO. We only need to check the 1136 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or 1137 // RHS operand. The LHS operand of both add and sub is never attached 1138 // to an inversese operation in the linearized form, therefore its APO 1139 // is false. The RHS is true only if VL[Lane] is an inverse operation. 1140 1141 // Since operand reordering is performed on groups of commutative 1142 // operations or alternating sequences (e.g., +, -), we can safely 1143 // tell the inverse operations by checking commutativity. 1144 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane])); 1145 bool APO = (OpIdx == 0) ? false : IsInverseOperation; 1146 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx), 1147 APO, false}; 1148 } 1149 } 1150 } 1151 1152 /// \returns the number of operands. 1153 unsigned getNumOperands() const { return OpsVec.size(); } 1154 1155 /// \returns the number of lanes. 1156 unsigned getNumLanes() const { return OpsVec[0].size(); } 1157 1158 /// \returns the operand value at \p OpIdx and \p Lane. 1159 Value *getValue(unsigned OpIdx, unsigned Lane) const { 1160 return getData(OpIdx, Lane).V; 1161 } 1162 1163 /// \returns true if the data structure is empty. 1164 bool empty() const { return OpsVec.empty(); } 1165 1166 /// Clears the data. 1167 void clear() { OpsVec.clear(); } 1168 1169 /// \Returns true if there are enough operands identical to \p Op to fill 1170 /// the whole vector. 1171 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow. 1172 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) { 1173 bool OpAPO = getData(OpIdx, Lane).APO; 1174 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) { 1175 if (Ln == Lane) 1176 continue; 1177 // This is set to true if we found a candidate for broadcast at Lane. 1178 bool FoundCandidate = false; 1179 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) { 1180 OperandData &Data = getData(OpI, Ln); 1181 if (Data.APO != OpAPO || Data.IsUsed) 1182 continue; 1183 if (Data.V == Op) { 1184 FoundCandidate = true; 1185 Data.IsUsed = true; 1186 break; 1187 } 1188 } 1189 if (!FoundCandidate) 1190 return false; 1191 } 1192 return true; 1193 } 1194 1195 public: 1196 /// Initialize with all the operands of the instruction vector \p RootVL. 1197 VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL, 1198 ScalarEvolution &SE, const BoUpSLP &R) 1199 : DL(DL), SE(SE), R(R) { 1200 // Append all the operands of RootVL. 1201 appendOperandsOfVL(RootVL); 1202 } 1203 1204 /// \Returns a value vector with the operands across all lanes for the 1205 /// opearnd at \p OpIdx. 1206 ValueList getVL(unsigned OpIdx) const { 1207 ValueList OpVL(OpsVec[OpIdx].size()); 1208 assert(OpsVec[OpIdx].size() == getNumLanes() && 1209 "Expected same num of lanes across all operands"); 1210 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane) 1211 OpVL[Lane] = OpsVec[OpIdx][Lane].V; 1212 return OpVL; 1213 } 1214 1215 // Performs operand reordering for 2 or more operands. 1216 // The original operands are in OrigOps[OpIdx][Lane]. 1217 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'. 1218 void reorder() { 1219 unsigned NumOperands = getNumOperands(); 1220 unsigned NumLanes = getNumLanes(); 1221 // Each operand has its own mode. We are using this mode to help us select 1222 // the instructions for each lane, so that they match best with the ones 1223 // we have selected so far. 1224 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands); 1225 1226 // This is a greedy single-pass algorithm. We are going over each lane 1227 // once and deciding on the best order right away with no back-tracking. 1228 // However, in order to increase its effectiveness, we start with the lane 1229 // that has operands that can move the least. For example, given the 1230 // following lanes: 1231 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd 1232 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st 1233 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd 1234 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th 1235 // we will start at Lane 1, since the operands of the subtraction cannot 1236 // be reordered. Then we will visit the rest of the lanes in a circular 1237 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3. 1238 1239 // Find the first lane that we will start our search from. 1240 unsigned FirstLane = getBestLaneToStartReordering(); 1241 1242 // Initialize the modes. 1243 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1244 Value *OpLane0 = getValue(OpIdx, FirstLane); 1245 // Keep track if we have instructions with all the same opcode on one 1246 // side. 1247 if (isa<LoadInst>(OpLane0)) 1248 ReorderingModes[OpIdx] = ReorderingMode::Load; 1249 else if (isa<Instruction>(OpLane0)) { 1250 // Check if OpLane0 should be broadcast. 1251 if (shouldBroadcast(OpLane0, OpIdx, FirstLane)) 1252 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1253 else 1254 ReorderingModes[OpIdx] = ReorderingMode::Opcode; 1255 } 1256 else if (isa<Constant>(OpLane0)) 1257 ReorderingModes[OpIdx] = ReorderingMode::Constant; 1258 else if (isa<Argument>(OpLane0)) 1259 // Our best hope is a Splat. It may save some cost in some cases. 1260 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1261 else 1262 // NOTE: This should be unreachable. 1263 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1264 } 1265 1266 // If the initial strategy fails for any of the operand indexes, then we 1267 // perform reordering again in a second pass. This helps avoid assigning 1268 // high priority to the failed strategy, and should improve reordering for 1269 // the non-failed operand indexes. 1270 for (int Pass = 0; Pass != 2; ++Pass) { 1271 // Skip the second pass if the first pass did not fail. 1272 bool StrategyFailed = false; 1273 // Mark all operand data as free to use. 1274 clearUsed(); 1275 // We keep the original operand order for the FirstLane, so reorder the 1276 // rest of the lanes. We are visiting the nodes in a circular fashion, 1277 // using FirstLane as the center point and increasing the radius 1278 // distance. 1279 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) { 1280 // Visit the lane on the right and then the lane on the left. 1281 for (int Direction : {+1, -1}) { 1282 int Lane = FirstLane + Direction * Distance; 1283 if (Lane < 0 || Lane >= (int)NumLanes) 1284 continue; 1285 int LastLane = Lane - Direction; 1286 assert(LastLane >= 0 && LastLane < (int)NumLanes && 1287 "Out of bounds"); 1288 // Look for a good match for each operand. 1289 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1290 // Search for the operand that matches SortedOps[OpIdx][Lane-1]. 1291 Optional<unsigned> BestIdx = 1292 getBestOperand(OpIdx, Lane, LastLane, ReorderingModes); 1293 // By not selecting a value, we allow the operands that follow to 1294 // select a better matching value. We will get a non-null value in 1295 // the next run of getBestOperand(). 1296 if (BestIdx) { 1297 // Swap the current operand with the one returned by 1298 // getBestOperand(). 1299 swap(OpIdx, BestIdx.getValue(), Lane); 1300 } else { 1301 // We failed to find a best operand, set mode to 'Failed'. 1302 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1303 // Enable the second pass. 1304 StrategyFailed = true; 1305 } 1306 } 1307 } 1308 } 1309 // Skip second pass if the strategy did not fail. 1310 if (!StrategyFailed) 1311 break; 1312 } 1313 } 1314 1315 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1316 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) { 1317 switch (RMode) { 1318 case ReorderingMode::Load: 1319 return "Load"; 1320 case ReorderingMode::Opcode: 1321 return "Opcode"; 1322 case ReorderingMode::Constant: 1323 return "Constant"; 1324 case ReorderingMode::Splat: 1325 return "Splat"; 1326 case ReorderingMode::Failed: 1327 return "Failed"; 1328 } 1329 llvm_unreachable("Unimplemented Reordering Type"); 1330 } 1331 1332 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode, 1333 raw_ostream &OS) { 1334 return OS << getModeStr(RMode); 1335 } 1336 1337 /// Debug print. 1338 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) { 1339 printMode(RMode, dbgs()); 1340 } 1341 1342 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) { 1343 return printMode(RMode, OS); 1344 } 1345 1346 LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const { 1347 const unsigned Indent = 2; 1348 unsigned Cnt = 0; 1349 for (const OperandDataVec &OpDataVec : OpsVec) { 1350 OS << "Operand " << Cnt++ << "\n"; 1351 for (const OperandData &OpData : OpDataVec) { 1352 OS.indent(Indent) << "{"; 1353 if (Value *V = OpData.V) 1354 OS << *V; 1355 else 1356 OS << "null"; 1357 OS << ", APO:" << OpData.APO << "}\n"; 1358 } 1359 OS << "\n"; 1360 } 1361 return OS; 1362 } 1363 1364 /// Debug print. 1365 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 1366 #endif 1367 }; 1368 1369 /// Checks if the instruction is marked for deletion. 1370 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); } 1371 1372 /// Marks values operands for later deletion by replacing them with Undefs. 1373 void eraseInstructions(ArrayRef<Value *> AV); 1374 1375 ~BoUpSLP(); 1376 1377 private: 1378 /// Checks if all users of \p I are the part of the vectorization tree. 1379 bool areAllUsersVectorized(Instruction *I) const; 1380 1381 /// \returns the cost of the vectorizable entry. 1382 int getEntryCost(TreeEntry *E); 1383 1384 /// This is the recursive part of buildTree. 1385 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, 1386 const EdgeInfo &EI); 1387 1388 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can 1389 /// be vectorized to use the original vector (or aggregate "bitcast" to a 1390 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise 1391 /// returns false, setting \p CurrentOrder to either an empty vector or a 1392 /// non-identity permutation that allows to reuse extract instructions. 1393 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 1394 SmallVectorImpl<unsigned> &CurrentOrder) const; 1395 1396 /// Vectorize a single entry in the tree. 1397 Value *vectorizeTree(TreeEntry *E); 1398 1399 /// Vectorize a single entry in the tree, starting in \p VL. 1400 Value *vectorizeTree(ArrayRef<Value *> VL); 1401 1402 /// \returns the scalarization cost for this type. Scalarization in this 1403 /// context means the creation of vectors from a group of scalars. 1404 int getGatherCost(Type *Ty, const DenseSet<unsigned> &ShuffledIndices) const; 1405 1406 /// \returns the scalarization cost for this list of values. Assuming that 1407 /// this subtree gets vectorized, we may need to extract the values from the 1408 /// roots. This method calculates the cost of extracting the values. 1409 int getGatherCost(ArrayRef<Value *> VL) const; 1410 1411 /// Set the Builder insert point to one after the last instruction in 1412 /// the bundle 1413 void setInsertPointAfterBundle(TreeEntry *E); 1414 1415 /// \returns a vector from a collection of scalars in \p VL. 1416 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty); 1417 1418 /// \returns whether the VectorizableTree is fully vectorizable and will 1419 /// be beneficial even the tree height is tiny. 1420 bool isFullyVectorizableTinyTree() const; 1421 1422 /// Reorder commutative or alt operands to get better probability of 1423 /// generating vectorized code. 1424 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 1425 SmallVectorImpl<Value *> &Left, 1426 SmallVectorImpl<Value *> &Right, 1427 const DataLayout &DL, 1428 ScalarEvolution &SE, 1429 const BoUpSLP &R); 1430 struct TreeEntry { 1431 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>; 1432 TreeEntry(VecTreeTy &Container) : Container(Container) {} 1433 1434 /// \returns true if the scalars in VL are equal to this entry. 1435 bool isSame(ArrayRef<Value *> VL) const { 1436 if (VL.size() == Scalars.size()) 1437 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 1438 return VL.size() == ReuseShuffleIndices.size() && 1439 std::equal( 1440 VL.begin(), VL.end(), ReuseShuffleIndices.begin(), 1441 [this](Value *V, unsigned Idx) { return V == Scalars[Idx]; }); 1442 } 1443 1444 /// A vector of scalars. 1445 ValueList Scalars; 1446 1447 /// The Scalars are vectorized into this value. It is initialized to Null. 1448 Value *VectorizedValue = nullptr; 1449 1450 /// Do we need to gather this sequence ? 1451 enum EntryState { Vectorize, NeedToGather }; 1452 EntryState State; 1453 1454 /// Does this sequence require some shuffling? 1455 SmallVector<unsigned, 4> ReuseShuffleIndices; 1456 1457 /// Does this entry require reordering? 1458 ArrayRef<unsigned> ReorderIndices; 1459 1460 /// Points back to the VectorizableTree. 1461 /// 1462 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has 1463 /// to be a pointer and needs to be able to initialize the child iterator. 1464 /// Thus we need a reference back to the container to translate the indices 1465 /// to entries. 1466 VecTreeTy &Container; 1467 1468 /// The TreeEntry index containing the user of this entry. We can actually 1469 /// have multiple users so the data structure is not truly a tree. 1470 SmallVector<EdgeInfo, 1> UserTreeIndices; 1471 1472 /// The index of this treeEntry in VectorizableTree. 1473 int Idx = -1; 1474 1475 private: 1476 /// The operands of each instruction in each lane Operands[op_index][lane]. 1477 /// Note: This helps avoid the replication of the code that performs the 1478 /// reordering of operands during buildTree_rec() and vectorizeTree(). 1479 SmallVector<ValueList, 2> Operands; 1480 1481 /// The main/alternate instruction. 1482 Instruction *MainOp = nullptr; 1483 Instruction *AltOp = nullptr; 1484 1485 public: 1486 /// Set this bundle's \p OpIdx'th operand to \p OpVL. 1487 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) { 1488 if (Operands.size() < OpIdx + 1) 1489 Operands.resize(OpIdx + 1); 1490 assert(Operands[OpIdx].size() == 0 && "Already resized?"); 1491 Operands[OpIdx].resize(Scalars.size()); 1492 for (unsigned Lane = 0, E = Scalars.size(); Lane != E; ++Lane) 1493 Operands[OpIdx][Lane] = OpVL[Lane]; 1494 } 1495 1496 /// Set the operands of this bundle in their original order. 1497 void setOperandsInOrder() { 1498 assert(Operands.empty() && "Already initialized?"); 1499 auto *I0 = cast<Instruction>(Scalars[0]); 1500 Operands.resize(I0->getNumOperands()); 1501 unsigned NumLanes = Scalars.size(); 1502 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands(); 1503 OpIdx != NumOperands; ++OpIdx) { 1504 Operands[OpIdx].resize(NumLanes); 1505 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1506 auto *I = cast<Instruction>(Scalars[Lane]); 1507 assert(I->getNumOperands() == NumOperands && 1508 "Expected same number of operands"); 1509 Operands[OpIdx][Lane] = I->getOperand(OpIdx); 1510 } 1511 } 1512 } 1513 1514 /// \returns the \p OpIdx operand of this TreeEntry. 1515 ValueList &getOperand(unsigned OpIdx) { 1516 assert(OpIdx < Operands.size() && "Off bounds"); 1517 return Operands[OpIdx]; 1518 } 1519 1520 /// \returns the number of operands. 1521 unsigned getNumOperands() const { return Operands.size(); } 1522 1523 /// \return the single \p OpIdx operand. 1524 Value *getSingleOperand(unsigned OpIdx) const { 1525 assert(OpIdx < Operands.size() && "Off bounds"); 1526 assert(!Operands[OpIdx].empty() && "No operand available"); 1527 return Operands[OpIdx][0]; 1528 } 1529 1530 /// Some of the instructions in the list have alternate opcodes. 1531 bool isAltShuffle() const { 1532 return getOpcode() != getAltOpcode(); 1533 } 1534 1535 bool isOpcodeOrAlt(Instruction *I) const { 1536 unsigned CheckedOpcode = I->getOpcode(); 1537 return (getOpcode() == CheckedOpcode || 1538 getAltOpcode() == CheckedOpcode); 1539 } 1540 1541 /// Chooses the correct key for scheduling data. If \p Op has the same (or 1542 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is 1543 /// \p OpValue. 1544 Value *isOneOf(Value *Op) const { 1545 auto *I = dyn_cast<Instruction>(Op); 1546 if (I && isOpcodeOrAlt(I)) 1547 return Op; 1548 return MainOp; 1549 } 1550 1551 void setOperations(const InstructionsState &S) { 1552 MainOp = S.MainOp; 1553 AltOp = S.AltOp; 1554 } 1555 1556 Instruction *getMainOp() const { 1557 return MainOp; 1558 } 1559 1560 Instruction *getAltOp() const { 1561 return AltOp; 1562 } 1563 1564 /// The main/alternate opcodes for the list of instructions. 1565 unsigned getOpcode() const { 1566 return MainOp ? MainOp->getOpcode() : 0; 1567 } 1568 1569 unsigned getAltOpcode() const { 1570 return AltOp ? AltOp->getOpcode() : 0; 1571 } 1572 1573 /// Update operations state of this entry if reorder occurred. 1574 bool updateStateIfReorder() { 1575 if (ReorderIndices.empty()) 1576 return false; 1577 InstructionsState S = getSameOpcode(Scalars, ReorderIndices.front()); 1578 setOperations(S); 1579 return true; 1580 } 1581 1582 #ifndef NDEBUG 1583 /// Debug printer. 1584 LLVM_DUMP_METHOD void dump() const { 1585 dbgs() << Idx << ".\n"; 1586 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) { 1587 dbgs() << "Operand " << OpI << ":\n"; 1588 for (const Value *V : Operands[OpI]) 1589 dbgs().indent(2) << *V << "\n"; 1590 } 1591 dbgs() << "Scalars: \n"; 1592 for (Value *V : Scalars) 1593 dbgs().indent(2) << *V << "\n"; 1594 dbgs() << "State: "; 1595 switch (State) { 1596 case Vectorize: 1597 dbgs() << "Vectorize\n"; 1598 break; 1599 case NeedToGather: 1600 dbgs() << "NeedToGather\n"; 1601 break; 1602 } 1603 dbgs() << "MainOp: "; 1604 if (MainOp) 1605 dbgs() << *MainOp << "\n"; 1606 else 1607 dbgs() << "NULL\n"; 1608 dbgs() << "AltOp: "; 1609 if (AltOp) 1610 dbgs() << *AltOp << "\n"; 1611 else 1612 dbgs() << "NULL\n"; 1613 dbgs() << "VectorizedValue: "; 1614 if (VectorizedValue) 1615 dbgs() << *VectorizedValue << "\n"; 1616 else 1617 dbgs() << "NULL\n"; 1618 dbgs() << "ReuseShuffleIndices: "; 1619 if (ReuseShuffleIndices.empty()) 1620 dbgs() << "Emtpy"; 1621 else 1622 for (unsigned ReuseIdx : ReuseShuffleIndices) 1623 dbgs() << ReuseIdx << ", "; 1624 dbgs() << "\n"; 1625 dbgs() << "ReorderIndices: "; 1626 for (unsigned ReorderIdx : ReorderIndices) 1627 dbgs() << ReorderIdx << ", "; 1628 dbgs() << "\n"; 1629 dbgs() << "UserTreeIndices: "; 1630 for (const auto &EInfo : UserTreeIndices) 1631 dbgs() << EInfo << ", "; 1632 dbgs() << "\n"; 1633 } 1634 #endif 1635 }; 1636 1637 /// Create a new VectorizableTree entry. 1638 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle, 1639 const InstructionsState &S, 1640 const EdgeInfo &UserTreeIdx, 1641 ArrayRef<unsigned> ReuseShuffleIndices = None, 1642 ArrayRef<unsigned> ReorderIndices = None) { 1643 bool Vectorized = (bool)Bundle; 1644 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree)); 1645 TreeEntry *Last = VectorizableTree.back().get(); 1646 Last->Idx = VectorizableTree.size() - 1; 1647 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end()); 1648 Last->State = Vectorized ? TreeEntry::Vectorize : TreeEntry::NeedToGather; 1649 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), 1650 ReuseShuffleIndices.end()); 1651 Last->ReorderIndices = ReorderIndices; 1652 Last->setOperations(S); 1653 if (Vectorized) { 1654 for (int i = 0, e = VL.size(); i != e; ++i) { 1655 assert(!getTreeEntry(VL[i]) && "Scalar already in tree!"); 1656 ScalarToTreeEntry[VL[i]] = Last; 1657 } 1658 // Update the scheduler bundle to point to this TreeEntry. 1659 unsigned Lane = 0; 1660 for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember; 1661 BundleMember = BundleMember->NextInBundle) { 1662 BundleMember->TE = Last; 1663 BundleMember->Lane = Lane; 1664 ++Lane; 1665 } 1666 assert((!Bundle.getValue() || Lane == VL.size()) && 1667 "Bundle and VL out of sync"); 1668 } else { 1669 MustGather.insert(VL.begin(), VL.end()); 1670 } 1671 1672 if (UserTreeIdx.UserTE) 1673 Last->UserTreeIndices.push_back(UserTreeIdx); 1674 1675 return Last; 1676 } 1677 1678 /// -- Vectorization State -- 1679 /// Holds all of the tree entries. 1680 TreeEntry::VecTreeTy VectorizableTree; 1681 1682 #ifndef NDEBUG 1683 /// Debug printer. 1684 LLVM_DUMP_METHOD void dumpVectorizableTree() const { 1685 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) { 1686 VectorizableTree[Id]->dump(); 1687 dbgs() << "\n"; 1688 } 1689 } 1690 #endif 1691 1692 TreeEntry *getTreeEntry(Value *V) { 1693 auto I = ScalarToTreeEntry.find(V); 1694 if (I != ScalarToTreeEntry.end()) 1695 return I->second; 1696 return nullptr; 1697 } 1698 1699 const TreeEntry *getTreeEntry(Value *V) const { 1700 auto I = ScalarToTreeEntry.find(V); 1701 if (I != ScalarToTreeEntry.end()) 1702 return I->second; 1703 return nullptr; 1704 } 1705 1706 /// Maps a specific scalar to its tree entry. 1707 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry; 1708 1709 /// A list of scalars that we found that we need to keep as scalars. 1710 ValueSet MustGather; 1711 1712 /// This POD struct describes one external user in the vectorized tree. 1713 struct ExternalUser { 1714 ExternalUser(Value *S, llvm::User *U, int L) 1715 : Scalar(S), User(U), Lane(L) {} 1716 1717 // Which scalar in our function. 1718 Value *Scalar; 1719 1720 // Which user that uses the scalar. 1721 llvm::User *User; 1722 1723 // Which lane does the scalar belong to. 1724 int Lane; 1725 }; 1726 using UserList = SmallVector<ExternalUser, 16>; 1727 1728 /// Checks if two instructions may access the same memory. 1729 /// 1730 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it 1731 /// is invariant in the calling loop. 1732 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, 1733 Instruction *Inst2) { 1734 // First check if the result is already in the cache. 1735 AliasCacheKey key = std::make_pair(Inst1, Inst2); 1736 Optional<bool> &result = AliasCache[key]; 1737 if (result.hasValue()) { 1738 return result.getValue(); 1739 } 1740 MemoryLocation Loc2 = getLocation(Inst2, AA); 1741 bool aliased = true; 1742 if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) { 1743 // Do the alias check. 1744 aliased = AA->alias(Loc1, Loc2); 1745 } 1746 // Store the result in the cache. 1747 result = aliased; 1748 return aliased; 1749 } 1750 1751 using AliasCacheKey = std::pair<Instruction *, Instruction *>; 1752 1753 /// Cache for alias results. 1754 /// TODO: consider moving this to the AliasAnalysis itself. 1755 DenseMap<AliasCacheKey, Optional<bool>> AliasCache; 1756 1757 /// Removes an instruction from its block and eventually deletes it. 1758 /// It's like Instruction::eraseFromParent() except that the actual deletion 1759 /// is delayed until BoUpSLP is destructed. 1760 /// This is required to ensure that there are no incorrect collisions in the 1761 /// AliasCache, which can happen if a new instruction is allocated at the 1762 /// same address as a previously deleted instruction. 1763 void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) { 1764 auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first; 1765 It->getSecond() = It->getSecond() && ReplaceOpsWithUndef; 1766 } 1767 1768 /// Temporary store for deleted instructions. Instructions will be deleted 1769 /// eventually when the BoUpSLP is destructed. 1770 DenseMap<Instruction *, bool> DeletedInstructions; 1771 1772 /// A list of values that need to extracted out of the tree. 1773 /// This list holds pairs of (Internal Scalar : External User). External User 1774 /// can be nullptr, it means that this Internal Scalar will be used later, 1775 /// after vectorization. 1776 UserList ExternalUses; 1777 1778 /// Values used only by @llvm.assume calls. 1779 SmallPtrSet<const Value *, 32> EphValues; 1780 1781 /// Holds all of the instructions that we gathered. 1782 SetVector<Instruction *> GatherSeq; 1783 1784 /// A list of blocks that we are going to CSE. 1785 SetVector<BasicBlock *> CSEBlocks; 1786 1787 /// Contains all scheduling relevant data for an instruction. 1788 /// A ScheduleData either represents a single instruction or a member of an 1789 /// instruction bundle (= a group of instructions which is combined into a 1790 /// vector instruction). 1791 struct ScheduleData { 1792 // The initial value for the dependency counters. It means that the 1793 // dependencies are not calculated yet. 1794 enum { InvalidDeps = -1 }; 1795 1796 ScheduleData() = default; 1797 1798 void init(int BlockSchedulingRegionID, Value *OpVal) { 1799 FirstInBundle = this; 1800 NextInBundle = nullptr; 1801 NextLoadStore = nullptr; 1802 IsScheduled = false; 1803 SchedulingRegionID = BlockSchedulingRegionID; 1804 UnscheduledDepsInBundle = UnscheduledDeps; 1805 clearDependencies(); 1806 OpValue = OpVal; 1807 TE = nullptr; 1808 Lane = -1; 1809 } 1810 1811 /// Returns true if the dependency information has been calculated. 1812 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 1813 1814 /// Returns true for single instructions and for bundle representatives 1815 /// (= the head of a bundle). 1816 bool isSchedulingEntity() const { return FirstInBundle == this; } 1817 1818 /// Returns true if it represents an instruction bundle and not only a 1819 /// single instruction. 1820 bool isPartOfBundle() const { 1821 return NextInBundle != nullptr || FirstInBundle != this; 1822 } 1823 1824 /// Returns true if it is ready for scheduling, i.e. it has no more 1825 /// unscheduled depending instructions/bundles. 1826 bool isReady() const { 1827 assert(isSchedulingEntity() && 1828 "can't consider non-scheduling entity for ready list"); 1829 return UnscheduledDepsInBundle == 0 && !IsScheduled; 1830 } 1831 1832 /// Modifies the number of unscheduled dependencies, also updating it for 1833 /// the whole bundle. 1834 int incrementUnscheduledDeps(int Incr) { 1835 UnscheduledDeps += Incr; 1836 return FirstInBundle->UnscheduledDepsInBundle += Incr; 1837 } 1838 1839 /// Sets the number of unscheduled dependencies to the number of 1840 /// dependencies. 1841 void resetUnscheduledDeps() { 1842 incrementUnscheduledDeps(Dependencies - UnscheduledDeps); 1843 } 1844 1845 /// Clears all dependency information. 1846 void clearDependencies() { 1847 Dependencies = InvalidDeps; 1848 resetUnscheduledDeps(); 1849 MemoryDependencies.clear(); 1850 } 1851 1852 void dump(raw_ostream &os) const { 1853 if (!isSchedulingEntity()) { 1854 os << "/ " << *Inst; 1855 } else if (NextInBundle) { 1856 os << '[' << *Inst; 1857 ScheduleData *SD = NextInBundle; 1858 while (SD) { 1859 os << ';' << *SD->Inst; 1860 SD = SD->NextInBundle; 1861 } 1862 os << ']'; 1863 } else { 1864 os << *Inst; 1865 } 1866 } 1867 1868 Instruction *Inst = nullptr; 1869 1870 /// Points to the head in an instruction bundle (and always to this for 1871 /// single instructions). 1872 ScheduleData *FirstInBundle = nullptr; 1873 1874 /// Single linked list of all instructions in a bundle. Null if it is a 1875 /// single instruction. 1876 ScheduleData *NextInBundle = nullptr; 1877 1878 /// Single linked list of all memory instructions (e.g. load, store, call) 1879 /// in the block - until the end of the scheduling region. 1880 ScheduleData *NextLoadStore = nullptr; 1881 1882 /// The dependent memory instructions. 1883 /// This list is derived on demand in calculateDependencies(). 1884 SmallVector<ScheduleData *, 4> MemoryDependencies; 1885 1886 /// This ScheduleData is in the current scheduling region if this matches 1887 /// the current SchedulingRegionID of BlockScheduling. 1888 int SchedulingRegionID = 0; 1889 1890 /// Used for getting a "good" final ordering of instructions. 1891 int SchedulingPriority = 0; 1892 1893 /// The number of dependencies. Constitutes of the number of users of the 1894 /// instruction plus the number of dependent memory instructions (if any). 1895 /// This value is calculated on demand. 1896 /// If InvalidDeps, the number of dependencies is not calculated yet. 1897 int Dependencies = InvalidDeps; 1898 1899 /// The number of dependencies minus the number of dependencies of scheduled 1900 /// instructions. As soon as this is zero, the instruction/bundle gets ready 1901 /// for scheduling. 1902 /// Note that this is negative as long as Dependencies is not calculated. 1903 int UnscheduledDeps = InvalidDeps; 1904 1905 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for 1906 /// single instructions. 1907 int UnscheduledDepsInBundle = InvalidDeps; 1908 1909 /// True if this instruction is scheduled (or considered as scheduled in the 1910 /// dry-run). 1911 bool IsScheduled = false; 1912 1913 /// Opcode of the current instruction in the schedule data. 1914 Value *OpValue = nullptr; 1915 1916 /// The TreeEntry that this instruction corresponds to. 1917 TreeEntry *TE = nullptr; 1918 1919 /// The lane of this node in the TreeEntry. 1920 int Lane = -1; 1921 }; 1922 1923 #ifndef NDEBUG 1924 friend inline raw_ostream &operator<<(raw_ostream &os, 1925 const BoUpSLP::ScheduleData &SD) { 1926 SD.dump(os); 1927 return os; 1928 } 1929 #endif 1930 1931 friend struct GraphTraits<BoUpSLP *>; 1932 friend struct DOTGraphTraits<BoUpSLP *>; 1933 1934 /// Contains all scheduling data for a basic block. 1935 struct BlockScheduling { 1936 BlockScheduling(BasicBlock *BB) 1937 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} 1938 1939 void clear() { 1940 ReadyInsts.clear(); 1941 ScheduleStart = nullptr; 1942 ScheduleEnd = nullptr; 1943 FirstLoadStoreInRegion = nullptr; 1944 LastLoadStoreInRegion = nullptr; 1945 1946 // Reduce the maximum schedule region size by the size of the 1947 // previous scheduling run. 1948 ScheduleRegionSizeLimit -= ScheduleRegionSize; 1949 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 1950 ScheduleRegionSizeLimit = MinScheduleRegionSize; 1951 ScheduleRegionSize = 0; 1952 1953 // Make a new scheduling region, i.e. all existing ScheduleData is not 1954 // in the new region yet. 1955 ++SchedulingRegionID; 1956 } 1957 1958 ScheduleData *getScheduleData(Value *V) { 1959 ScheduleData *SD = ScheduleDataMap[V]; 1960 if (SD && SD->SchedulingRegionID == SchedulingRegionID) 1961 return SD; 1962 return nullptr; 1963 } 1964 1965 ScheduleData *getScheduleData(Value *V, Value *Key) { 1966 if (V == Key) 1967 return getScheduleData(V); 1968 auto I = ExtraScheduleDataMap.find(V); 1969 if (I != ExtraScheduleDataMap.end()) { 1970 ScheduleData *SD = I->second[Key]; 1971 if (SD && SD->SchedulingRegionID == SchedulingRegionID) 1972 return SD; 1973 } 1974 return nullptr; 1975 } 1976 1977 bool isInSchedulingRegion(ScheduleData *SD) const { 1978 return SD->SchedulingRegionID == SchedulingRegionID; 1979 } 1980 1981 /// Marks an instruction as scheduled and puts all dependent ready 1982 /// instructions into the ready-list. 1983 template <typename ReadyListType> 1984 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 1985 SD->IsScheduled = true; 1986 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 1987 1988 ScheduleData *BundleMember = SD; 1989 while (BundleMember) { 1990 if (BundleMember->Inst != BundleMember->OpValue) { 1991 BundleMember = BundleMember->NextInBundle; 1992 continue; 1993 } 1994 // Handle the def-use chain dependencies. 1995 1996 // Decrement the unscheduled counter and insert to ready list if ready. 1997 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { 1998 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { 1999 if (OpDef && OpDef->hasValidDependencies() && 2000 OpDef->incrementUnscheduledDeps(-1) == 0) { 2001 // There are no more unscheduled dependencies after 2002 // decrementing, so we can put the dependent instruction 2003 // into the ready list. 2004 ScheduleData *DepBundle = OpDef->FirstInBundle; 2005 assert(!DepBundle->IsScheduled && 2006 "already scheduled bundle gets ready"); 2007 ReadyList.insert(DepBundle); 2008 LLVM_DEBUG(dbgs() 2009 << "SLP: gets ready (def): " << *DepBundle << "\n"); 2010 } 2011 }); 2012 }; 2013 2014 // If BundleMember is a vector bundle, its operands may have been 2015 // reordered duiring buildTree(). We therefore need to get its operands 2016 // through the TreeEntry. 2017 if (TreeEntry *TE = BundleMember->TE) { 2018 int Lane = BundleMember->Lane; 2019 assert(Lane >= 0 && "Lane not set"); 2020 2021 // Since vectorization tree is being built recursively this assertion 2022 // ensures that the tree entry has all operands set before reaching 2023 // this code. Couple of exceptions known at the moment are extracts 2024 // where their second (immediate) operand is not added. Since 2025 // immediates do not affect scheduler behavior this is considered 2026 // okay. 2027 auto *In = TE->getMainOp(); 2028 assert(In && 2029 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) || 2030 In->getNumOperands() == TE->getNumOperands()) && 2031 "Missed TreeEntry operands?"); 2032 (void)In; // fake use to avoid build failure when assertions disabled 2033 2034 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); 2035 OpIdx != NumOperands; ++OpIdx) 2036 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) 2037 DecrUnsched(I); 2038 } else { 2039 // If BundleMember is a stand-alone instruction, no operand reordering 2040 // has taken place, so we directly access its operands. 2041 for (Use &U : BundleMember->Inst->operands()) 2042 if (auto *I = dyn_cast<Instruction>(U.get())) 2043 DecrUnsched(I); 2044 } 2045 // Handle the memory dependencies. 2046 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 2047 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 2048 // There are no more unscheduled dependencies after decrementing, 2049 // so we can put the dependent instruction into the ready list. 2050 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 2051 assert(!DepBundle->IsScheduled && 2052 "already scheduled bundle gets ready"); 2053 ReadyList.insert(DepBundle); 2054 LLVM_DEBUG(dbgs() 2055 << "SLP: gets ready (mem): " << *DepBundle << "\n"); 2056 } 2057 } 2058 BundleMember = BundleMember->NextInBundle; 2059 } 2060 } 2061 2062 void doForAllOpcodes(Value *V, 2063 function_ref<void(ScheduleData *SD)> Action) { 2064 if (ScheduleData *SD = getScheduleData(V)) 2065 Action(SD); 2066 auto I = ExtraScheduleDataMap.find(V); 2067 if (I != ExtraScheduleDataMap.end()) 2068 for (auto &P : I->second) 2069 if (P.second->SchedulingRegionID == SchedulingRegionID) 2070 Action(P.second); 2071 } 2072 2073 /// Put all instructions into the ReadyList which are ready for scheduling. 2074 template <typename ReadyListType> 2075 void initialFillReadyList(ReadyListType &ReadyList) { 2076 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2077 doForAllOpcodes(I, [&](ScheduleData *SD) { 2078 if (SD->isSchedulingEntity() && SD->isReady()) { 2079 ReadyList.insert(SD); 2080 LLVM_DEBUG(dbgs() 2081 << "SLP: initially in ready list: " << *I << "\n"); 2082 } 2083 }); 2084 } 2085 } 2086 2087 /// Checks if a bundle of instructions can be scheduled, i.e. has no 2088 /// cyclic dependencies. This is only a dry-run, no instructions are 2089 /// actually moved at this stage. 2090 /// \returns the scheduling bundle. The returned Optional value is non-None 2091 /// if \p VL is allowed to be scheduled. 2092 Optional<ScheduleData *> 2093 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 2094 const InstructionsState &S); 2095 2096 /// Un-bundles a group of instructions. 2097 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); 2098 2099 /// Allocates schedule data chunk. 2100 ScheduleData *allocateScheduleDataChunks(); 2101 2102 /// Extends the scheduling region so that V is inside the region. 2103 /// \returns true if the region size is within the limit. 2104 bool extendSchedulingRegion(Value *V, const InstructionsState &S); 2105 2106 /// Initialize the ScheduleData structures for new instructions in the 2107 /// scheduling region. 2108 void initScheduleData(Instruction *FromI, Instruction *ToI, 2109 ScheduleData *PrevLoadStore, 2110 ScheduleData *NextLoadStore); 2111 2112 /// Updates the dependency information of a bundle and of all instructions/ 2113 /// bundles which depend on the original bundle. 2114 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 2115 BoUpSLP *SLP); 2116 2117 /// Sets all instruction in the scheduling region to un-scheduled. 2118 void resetSchedule(); 2119 2120 BasicBlock *BB; 2121 2122 /// Simple memory allocation for ScheduleData. 2123 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 2124 2125 /// The size of a ScheduleData array in ScheduleDataChunks. 2126 int ChunkSize; 2127 2128 /// The allocator position in the current chunk, which is the last entry 2129 /// of ScheduleDataChunks. 2130 int ChunkPos; 2131 2132 /// Attaches ScheduleData to Instruction. 2133 /// Note that the mapping survives during all vectorization iterations, i.e. 2134 /// ScheduleData structures are recycled. 2135 DenseMap<Value *, ScheduleData *> ScheduleDataMap; 2136 2137 /// Attaches ScheduleData to Instruction with the leading key. 2138 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> 2139 ExtraScheduleDataMap; 2140 2141 struct ReadyList : SmallVector<ScheduleData *, 8> { 2142 void insert(ScheduleData *SD) { push_back(SD); } 2143 }; 2144 2145 /// The ready-list for scheduling (only used for the dry-run). 2146 ReadyList ReadyInsts; 2147 2148 /// The first instruction of the scheduling region. 2149 Instruction *ScheduleStart = nullptr; 2150 2151 /// The first instruction _after_ the scheduling region. 2152 Instruction *ScheduleEnd = nullptr; 2153 2154 /// The first memory accessing instruction in the scheduling region 2155 /// (can be null). 2156 ScheduleData *FirstLoadStoreInRegion = nullptr; 2157 2158 /// The last memory accessing instruction in the scheduling region 2159 /// (can be null). 2160 ScheduleData *LastLoadStoreInRegion = nullptr; 2161 2162 /// The current size of the scheduling region. 2163 int ScheduleRegionSize = 0; 2164 2165 /// The maximum size allowed for the scheduling region. 2166 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; 2167 2168 /// The ID of the scheduling region. For a new vectorization iteration this 2169 /// is incremented which "removes" all ScheduleData from the region. 2170 // Make sure that the initial SchedulingRegionID is greater than the 2171 // initial SchedulingRegionID in ScheduleData (which is 0). 2172 int SchedulingRegionID = 1; 2173 }; 2174 2175 /// Attaches the BlockScheduling structures to basic blocks. 2176 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 2177 2178 /// Performs the "real" scheduling. Done before vectorization is actually 2179 /// performed in a basic block. 2180 void scheduleBlock(BlockScheduling *BS); 2181 2182 /// List of users to ignore during scheduling and that don't need extracting. 2183 ArrayRef<Value *> UserIgnoreList; 2184 2185 using OrdersType = SmallVector<unsigned, 4>; 2186 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of 2187 /// sorted SmallVectors of unsigned. 2188 struct OrdersTypeDenseMapInfo { 2189 static OrdersType getEmptyKey() { 2190 OrdersType V; 2191 V.push_back(~1U); 2192 return V; 2193 } 2194 2195 static OrdersType getTombstoneKey() { 2196 OrdersType V; 2197 V.push_back(~2U); 2198 return V; 2199 } 2200 2201 static unsigned getHashValue(const OrdersType &V) { 2202 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2203 } 2204 2205 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { 2206 return LHS == RHS; 2207 } 2208 }; 2209 2210 /// Contains orders of operations along with the number of bundles that have 2211 /// operations in this order. It stores only those orders that require 2212 /// reordering, if reordering is not required it is counted using \a 2213 /// NumOpsWantToKeepOriginalOrder. 2214 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo> NumOpsWantToKeepOrder; 2215 /// Number of bundles that do not require reordering. 2216 unsigned NumOpsWantToKeepOriginalOrder = 0; 2217 2218 // Analysis and block reference. 2219 Function *F; 2220 ScalarEvolution *SE; 2221 TargetTransformInfo *TTI; 2222 TargetLibraryInfo *TLI; 2223 AliasAnalysis *AA; 2224 LoopInfo *LI; 2225 DominatorTree *DT; 2226 AssumptionCache *AC; 2227 DemandedBits *DB; 2228 const DataLayout *DL; 2229 OptimizationRemarkEmitter *ORE; 2230 2231 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 2232 unsigned MinVecRegSize; // Set by cl::opt (default: 128). 2233 2234 /// Instruction builder to construct the vectorized tree. 2235 IRBuilder<> Builder; 2236 2237 /// A map of scalar integer values to the smallest bit width with which they 2238 /// can legally be represented. The values map to (width, signed) pairs, 2239 /// where "width" indicates the minimum bit width and "signed" is True if the 2240 /// value must be signed-extended, rather than zero-extended, back to its 2241 /// original width. 2242 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; 2243 }; 2244 2245 } // end namespace slpvectorizer 2246 2247 template <> struct GraphTraits<BoUpSLP *> { 2248 using TreeEntry = BoUpSLP::TreeEntry; 2249 2250 /// NodeRef has to be a pointer per the GraphWriter. 2251 using NodeRef = TreeEntry *; 2252 2253 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; 2254 2255 /// Add the VectorizableTree to the index iterator to be able to return 2256 /// TreeEntry pointers. 2257 struct ChildIteratorType 2258 : public iterator_adaptor_base< 2259 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { 2260 ContainerTy &VectorizableTree; 2261 2262 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, 2263 ContainerTy &VT) 2264 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} 2265 2266 NodeRef operator*() { return I->UserTE; } 2267 }; 2268 2269 static NodeRef getEntryNode(BoUpSLP &R) { 2270 return R.VectorizableTree[0].get(); 2271 } 2272 2273 static ChildIteratorType child_begin(NodeRef N) { 2274 return {N->UserTreeIndices.begin(), N->Container}; 2275 } 2276 2277 static ChildIteratorType child_end(NodeRef N) { 2278 return {N->UserTreeIndices.end(), N->Container}; 2279 } 2280 2281 /// For the node iterator we just need to turn the TreeEntry iterator into a 2282 /// TreeEntry* iterator so that it dereferences to NodeRef. 2283 class nodes_iterator { 2284 using ItTy = ContainerTy::iterator; 2285 ItTy It; 2286 2287 public: 2288 nodes_iterator(const ItTy &It2) : It(It2) {} 2289 NodeRef operator*() { return It->get(); } 2290 nodes_iterator operator++() { 2291 ++It; 2292 return *this; 2293 } 2294 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } 2295 }; 2296 2297 static nodes_iterator nodes_begin(BoUpSLP *R) { 2298 return nodes_iterator(R->VectorizableTree.begin()); 2299 } 2300 2301 static nodes_iterator nodes_end(BoUpSLP *R) { 2302 return nodes_iterator(R->VectorizableTree.end()); 2303 } 2304 2305 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } 2306 }; 2307 2308 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { 2309 using TreeEntry = BoUpSLP::TreeEntry; 2310 2311 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 2312 2313 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { 2314 std::string Str; 2315 raw_string_ostream OS(Str); 2316 if (isSplat(Entry->Scalars)) { 2317 OS << "<splat> " << *Entry->Scalars[0]; 2318 return Str; 2319 } 2320 for (auto V : Entry->Scalars) { 2321 OS << *V; 2322 if (std::any_of( 2323 R->ExternalUses.begin(), R->ExternalUses.end(), 2324 [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; })) 2325 OS << " <extract>"; 2326 OS << "\n"; 2327 } 2328 return Str; 2329 } 2330 2331 static std::string getNodeAttributes(const TreeEntry *Entry, 2332 const BoUpSLP *) { 2333 if (Entry->State == TreeEntry::NeedToGather) 2334 return "color=red"; 2335 return ""; 2336 } 2337 }; 2338 2339 } // end namespace llvm 2340 2341 BoUpSLP::~BoUpSLP() { 2342 for (const auto &Pair : DeletedInstructions) { 2343 // Replace operands of ignored instructions with Undefs in case if they were 2344 // marked for deletion. 2345 if (Pair.getSecond()) { 2346 Value *Undef = UndefValue::get(Pair.getFirst()->getType()); 2347 Pair.getFirst()->replaceAllUsesWith(Undef); 2348 } 2349 Pair.getFirst()->dropAllReferences(); 2350 } 2351 for (const auto &Pair : DeletedInstructions) { 2352 assert(Pair.getFirst()->use_empty() && 2353 "trying to erase instruction with users."); 2354 Pair.getFirst()->eraseFromParent(); 2355 } 2356 } 2357 2358 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) { 2359 for (auto *V : AV) { 2360 if (auto *I = dyn_cast<Instruction>(V)) 2361 eraseInstruction(I, /*ReplaceWithUndef=*/true); 2362 }; 2363 } 2364 2365 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 2366 ArrayRef<Value *> UserIgnoreLst) { 2367 ExtraValueToDebugLocsMap ExternallyUsedValues; 2368 buildTree(Roots, ExternallyUsedValues, UserIgnoreLst); 2369 } 2370 2371 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 2372 ExtraValueToDebugLocsMap &ExternallyUsedValues, 2373 ArrayRef<Value *> UserIgnoreLst) { 2374 deleteTree(); 2375 UserIgnoreList = UserIgnoreLst; 2376 if (!allSameType(Roots)) 2377 return; 2378 buildTree_rec(Roots, 0, EdgeInfo()); 2379 2380 // Collect the values that we need to extract from the tree. 2381 for (auto &TEPtr : VectorizableTree) { 2382 TreeEntry *Entry = TEPtr.get(); 2383 2384 // No need to handle users of gathered values. 2385 if (Entry->State == TreeEntry::NeedToGather) 2386 continue; 2387 2388 // For each lane: 2389 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 2390 Value *Scalar = Entry->Scalars[Lane]; 2391 int FoundLane = Lane; 2392 if (!Entry->ReuseShuffleIndices.empty()) { 2393 FoundLane = 2394 std::distance(Entry->ReuseShuffleIndices.begin(), 2395 llvm::find(Entry->ReuseShuffleIndices, FoundLane)); 2396 } 2397 2398 // Check if the scalar is externally used as an extra arg. 2399 auto ExtI = ExternallyUsedValues.find(Scalar); 2400 if (ExtI != ExternallyUsedValues.end()) { 2401 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 2402 << Lane << " from " << *Scalar << ".\n"); 2403 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 2404 } 2405 for (User *U : Scalar->users()) { 2406 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 2407 2408 Instruction *UserInst = dyn_cast<Instruction>(U); 2409 if (!UserInst) 2410 continue; 2411 2412 // Skip in-tree scalars that become vectors 2413 if (TreeEntry *UseEntry = getTreeEntry(U)) { 2414 Value *UseScalar = UseEntry->Scalars[0]; 2415 // Some in-tree scalars will remain as scalar in vectorized 2416 // instructions. If that is the case, the one in Lane 0 will 2417 // be used. 2418 if (UseScalar != U || 2419 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 2420 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 2421 << ".\n"); 2422 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 2423 continue; 2424 } 2425 } 2426 2427 // Ignore users in the user ignore list. 2428 if (is_contained(UserIgnoreList, UserInst)) 2429 continue; 2430 2431 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 2432 << Lane << " from " << *Scalar << ".\n"); 2433 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 2434 } 2435 } 2436 } 2437 } 2438 2439 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 2440 const EdgeInfo &UserTreeIdx) { 2441 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 2442 2443 InstructionsState S = getSameOpcode(VL); 2444 if (Depth == RecursionMaxDepth) { 2445 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 2446 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2447 return; 2448 } 2449 2450 // Don't handle vectors. 2451 if (S.OpValue->getType()->isVectorTy()) { 2452 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 2453 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2454 return; 2455 } 2456 2457 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 2458 if (SI->getValueOperand()->getType()->isVectorTy()) { 2459 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 2460 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2461 return; 2462 } 2463 2464 // If all of the operands are identical or constant we have a simple solution. 2465 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode()) { 2466 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 2467 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2468 return; 2469 } 2470 2471 // We now know that this is a vector of instructions of the same type from 2472 // the same block. 2473 2474 // Don't vectorize ephemeral values. 2475 for (Value *V : VL) { 2476 if (EphValues.count(V)) { 2477 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 2478 << ") is ephemeral.\n"); 2479 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2480 return; 2481 } 2482 } 2483 2484 // Check if this is a duplicate of another entry. 2485 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 2486 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 2487 if (!E->isSame(VL)) { 2488 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 2489 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2490 return; 2491 } 2492 // Record the reuse of the tree node. FIXME, currently this is only used to 2493 // properly draw the graph rather than for the actual vectorization. 2494 E->UserTreeIndices.push_back(UserTreeIdx); 2495 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 2496 << ".\n"); 2497 return; 2498 } 2499 2500 // Check that none of the instructions in the bundle are already in the tree. 2501 for (Value *V : VL) { 2502 auto *I = dyn_cast<Instruction>(V); 2503 if (!I) 2504 continue; 2505 if (getTreeEntry(I)) { 2506 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 2507 << ") is already in tree.\n"); 2508 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2509 return; 2510 } 2511 } 2512 2513 // If any of the scalars is marked as a value that needs to stay scalar, then 2514 // we need to gather the scalars. 2515 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 2516 for (Value *V : VL) { 2517 if (MustGather.count(V) || is_contained(UserIgnoreList, V)) { 2518 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 2519 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2520 return; 2521 } 2522 } 2523 2524 // Check that all of the users of the scalars that we want to vectorize are 2525 // schedulable. 2526 auto *VL0 = cast<Instruction>(S.OpValue); 2527 BasicBlock *BB = VL0->getParent(); 2528 2529 if (!DT->isReachableFromEntry(BB)) { 2530 // Don't go into unreachable blocks. They may contain instructions with 2531 // dependency cycles which confuse the final scheduling. 2532 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 2533 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2534 return; 2535 } 2536 2537 // Check that every instruction appears once in this bundle. 2538 SmallVector<unsigned, 4> ReuseShuffleIndicies; 2539 SmallVector<Value *, 4> UniqueValues; 2540 DenseMap<Value *, unsigned> UniquePositions; 2541 for (Value *V : VL) { 2542 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 2543 ReuseShuffleIndicies.emplace_back(Res.first->second); 2544 if (Res.second) 2545 UniqueValues.emplace_back(V); 2546 } 2547 size_t NumUniqueScalarValues = UniqueValues.size(); 2548 if (NumUniqueScalarValues == VL.size()) { 2549 ReuseShuffleIndicies.clear(); 2550 } else { 2551 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 2552 if (NumUniqueScalarValues <= 1 || 2553 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 2554 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 2555 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 2556 return; 2557 } 2558 VL = UniqueValues; 2559 } 2560 2561 auto &BSRef = BlocksSchedules[BB]; 2562 if (!BSRef) 2563 BSRef = std::make_unique<BlockScheduling>(BB); 2564 2565 BlockScheduling &BS = *BSRef.get(); 2566 2567 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 2568 if (!Bundle) { 2569 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 2570 assert((!BS.getScheduleData(VL0) || 2571 !BS.getScheduleData(VL0)->isPartOfBundle()) && 2572 "tryScheduleBundle should cancelScheduling on failure"); 2573 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2574 ReuseShuffleIndicies); 2575 return; 2576 } 2577 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 2578 2579 unsigned ShuffleOrOp = S.isAltShuffle() ? 2580 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 2581 switch (ShuffleOrOp) { 2582 case Instruction::PHI: { 2583 auto *PH = cast<PHINode>(VL0); 2584 2585 // Check for terminator values (e.g. invoke). 2586 for (unsigned j = 0; j < VL.size(); ++j) 2587 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 2588 Instruction *Term = dyn_cast<Instruction>( 2589 cast<PHINode>(VL[j])->getIncomingValueForBlock( 2590 PH->getIncomingBlock(i))); 2591 if (Term && Term->isTerminator()) { 2592 LLVM_DEBUG(dbgs() 2593 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 2594 BS.cancelScheduling(VL, VL0); 2595 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2596 ReuseShuffleIndicies); 2597 return; 2598 } 2599 } 2600 2601 TreeEntry *TE = 2602 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 2603 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 2604 2605 // Keeps the reordered operands to avoid code duplication. 2606 SmallVector<ValueList, 2> OperandsVec; 2607 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 2608 ValueList Operands; 2609 // Prepare the operand vector. 2610 for (Value *j : VL) 2611 Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock( 2612 PH->getIncomingBlock(i))); 2613 TE->setOperand(i, Operands); 2614 OperandsVec.push_back(Operands); 2615 } 2616 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 2617 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 2618 return; 2619 } 2620 case Instruction::ExtractValue: 2621 case Instruction::ExtractElement: { 2622 OrdersType CurrentOrder; 2623 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 2624 if (Reuse) { 2625 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 2626 ++NumOpsWantToKeepOriginalOrder; 2627 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 2628 ReuseShuffleIndicies); 2629 // This is a special case, as it does not gather, but at the same time 2630 // we are not extending buildTree_rec() towards the operands. 2631 ValueList Op0; 2632 Op0.assign(VL.size(), VL0->getOperand(0)); 2633 VectorizableTree.back()->setOperand(0, Op0); 2634 return; 2635 } 2636 if (!CurrentOrder.empty()) { 2637 LLVM_DEBUG({ 2638 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 2639 "with order"; 2640 for (unsigned Idx : CurrentOrder) 2641 dbgs() << " " << Idx; 2642 dbgs() << "\n"; 2643 }); 2644 // Insert new order with initial value 0, if it does not exist, 2645 // otherwise return the iterator to the existing one. 2646 auto StoredCurrentOrderAndNum = 2647 NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first; 2648 ++StoredCurrentOrderAndNum->getSecond(); 2649 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 2650 ReuseShuffleIndicies, 2651 StoredCurrentOrderAndNum->getFirst()); 2652 // This is a special case, as it does not gather, but at the same time 2653 // we are not extending buildTree_rec() towards the operands. 2654 ValueList Op0; 2655 Op0.assign(VL.size(), VL0->getOperand(0)); 2656 VectorizableTree.back()->setOperand(0, Op0); 2657 return; 2658 } 2659 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 2660 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2661 ReuseShuffleIndicies); 2662 BS.cancelScheduling(VL, VL0); 2663 return; 2664 } 2665 case Instruction::Load: { 2666 // Check that a vectorized load would load the same memory as a scalar 2667 // load. For example, we don't want to vectorize loads that are smaller 2668 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 2669 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 2670 // from such a struct, we read/write packed bits disagreeing with the 2671 // unvectorized version. 2672 Type *ScalarTy = VL0->getType(); 2673 2674 if (DL->getTypeSizeInBits(ScalarTy) != 2675 DL->getTypeAllocSizeInBits(ScalarTy)) { 2676 BS.cancelScheduling(VL, VL0); 2677 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2678 ReuseShuffleIndicies); 2679 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 2680 return; 2681 } 2682 2683 // Make sure all loads in the bundle are simple - we can't vectorize 2684 // atomic or volatile loads. 2685 SmallVector<Value *, 4> PointerOps(VL.size()); 2686 auto POIter = PointerOps.begin(); 2687 for (Value *V : VL) { 2688 auto *L = cast<LoadInst>(V); 2689 if (!L->isSimple()) { 2690 BS.cancelScheduling(VL, VL0); 2691 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2692 ReuseShuffleIndicies); 2693 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 2694 return; 2695 } 2696 *POIter = L->getPointerOperand(); 2697 ++POIter; 2698 } 2699 2700 OrdersType CurrentOrder; 2701 // Check the order of pointer operands. 2702 if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) { 2703 Value *Ptr0; 2704 Value *PtrN; 2705 if (CurrentOrder.empty()) { 2706 Ptr0 = PointerOps.front(); 2707 PtrN = PointerOps.back(); 2708 } else { 2709 Ptr0 = PointerOps[CurrentOrder.front()]; 2710 PtrN = PointerOps[CurrentOrder.back()]; 2711 } 2712 const SCEV *Scev0 = SE->getSCEV(Ptr0); 2713 const SCEV *ScevN = SE->getSCEV(PtrN); 2714 const auto *Diff = 2715 dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0)); 2716 uint64_t Size = DL->getTypeAllocSize(ScalarTy); 2717 // Check that the sorted loads are consecutive. 2718 if (Diff && Diff->getAPInt() == (VL.size() - 1) * Size) { 2719 if (CurrentOrder.empty()) { 2720 // Original loads are consecutive and does not require reordering. 2721 ++NumOpsWantToKeepOriginalOrder; 2722 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 2723 UserTreeIdx, ReuseShuffleIndicies); 2724 TE->setOperandsInOrder(); 2725 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 2726 } else { 2727 // Need to reorder. 2728 auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first; 2729 ++I->getSecond(); 2730 TreeEntry *TE = 2731 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 2732 ReuseShuffleIndicies, I->getFirst()); 2733 TE->setOperandsInOrder(); 2734 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 2735 } 2736 return; 2737 } 2738 } 2739 2740 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 2741 BS.cancelScheduling(VL, VL0); 2742 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2743 ReuseShuffleIndicies); 2744 return; 2745 } 2746 case Instruction::ZExt: 2747 case Instruction::SExt: 2748 case Instruction::FPToUI: 2749 case Instruction::FPToSI: 2750 case Instruction::FPExt: 2751 case Instruction::PtrToInt: 2752 case Instruction::IntToPtr: 2753 case Instruction::SIToFP: 2754 case Instruction::UIToFP: 2755 case Instruction::Trunc: 2756 case Instruction::FPTrunc: 2757 case Instruction::BitCast: { 2758 Type *SrcTy = VL0->getOperand(0)->getType(); 2759 for (Value *V : VL) { 2760 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 2761 if (Ty != SrcTy || !isValidElementType(Ty)) { 2762 BS.cancelScheduling(VL, VL0); 2763 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2764 ReuseShuffleIndicies); 2765 LLVM_DEBUG(dbgs() 2766 << "SLP: Gathering casts with different src types.\n"); 2767 return; 2768 } 2769 } 2770 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 2771 ReuseShuffleIndicies); 2772 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 2773 2774 TE->setOperandsInOrder(); 2775 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 2776 ValueList Operands; 2777 // Prepare the operand vector. 2778 for (Value *V : VL) 2779 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 2780 2781 buildTree_rec(Operands, Depth + 1, {TE, i}); 2782 } 2783 return; 2784 } 2785 case Instruction::ICmp: 2786 case Instruction::FCmp: { 2787 // Check that all of the compares have the same predicate. 2788 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 2789 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 2790 Type *ComparedTy = VL0->getOperand(0)->getType(); 2791 for (Value *V : VL) { 2792 CmpInst *Cmp = cast<CmpInst>(V); 2793 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 2794 Cmp->getOperand(0)->getType() != ComparedTy) { 2795 BS.cancelScheduling(VL, VL0); 2796 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2797 ReuseShuffleIndicies); 2798 LLVM_DEBUG(dbgs() 2799 << "SLP: Gathering cmp with different predicate.\n"); 2800 return; 2801 } 2802 } 2803 2804 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 2805 ReuseShuffleIndicies); 2806 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 2807 2808 ValueList Left, Right; 2809 if (cast<CmpInst>(VL0)->isCommutative()) { 2810 // Commutative predicate - collect + sort operands of the instructions 2811 // so that each side is more likely to have the same opcode. 2812 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 2813 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 2814 } else { 2815 // Collect operands - commute if it uses the swapped predicate. 2816 for (Value *V : VL) { 2817 auto *Cmp = cast<CmpInst>(V); 2818 Value *LHS = Cmp->getOperand(0); 2819 Value *RHS = Cmp->getOperand(1); 2820 if (Cmp->getPredicate() != P0) 2821 std::swap(LHS, RHS); 2822 Left.push_back(LHS); 2823 Right.push_back(RHS); 2824 } 2825 } 2826 TE->setOperand(0, Left); 2827 TE->setOperand(1, Right); 2828 buildTree_rec(Left, Depth + 1, {TE, 0}); 2829 buildTree_rec(Right, Depth + 1, {TE, 1}); 2830 return; 2831 } 2832 case Instruction::Select: 2833 case Instruction::FNeg: 2834 case Instruction::Add: 2835 case Instruction::FAdd: 2836 case Instruction::Sub: 2837 case Instruction::FSub: 2838 case Instruction::Mul: 2839 case Instruction::FMul: 2840 case Instruction::UDiv: 2841 case Instruction::SDiv: 2842 case Instruction::FDiv: 2843 case Instruction::URem: 2844 case Instruction::SRem: 2845 case Instruction::FRem: 2846 case Instruction::Shl: 2847 case Instruction::LShr: 2848 case Instruction::AShr: 2849 case Instruction::And: 2850 case Instruction::Or: 2851 case Instruction::Xor: { 2852 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 2853 ReuseShuffleIndicies); 2854 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 2855 2856 // Sort operands of the instructions so that each side is more likely to 2857 // have the same opcode. 2858 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 2859 ValueList Left, Right; 2860 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 2861 TE->setOperand(0, Left); 2862 TE->setOperand(1, Right); 2863 buildTree_rec(Left, Depth + 1, {TE, 0}); 2864 buildTree_rec(Right, Depth + 1, {TE, 1}); 2865 return; 2866 } 2867 2868 TE->setOperandsInOrder(); 2869 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 2870 ValueList Operands; 2871 // Prepare the operand vector. 2872 for (Value *j : VL) 2873 Operands.push_back(cast<Instruction>(j)->getOperand(i)); 2874 2875 buildTree_rec(Operands, Depth + 1, {TE, i}); 2876 } 2877 return; 2878 } 2879 case Instruction::GetElementPtr: { 2880 // We don't combine GEPs with complicated (nested) indexing. 2881 for (Value *V : VL) { 2882 if (cast<Instruction>(V)->getNumOperands() != 2) { 2883 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 2884 BS.cancelScheduling(VL, VL0); 2885 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2886 ReuseShuffleIndicies); 2887 return; 2888 } 2889 } 2890 2891 // We can't combine several GEPs into one vector if they operate on 2892 // different types. 2893 Type *Ty0 = VL0->getOperand(0)->getType(); 2894 for (Value *V : VL) { 2895 Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType(); 2896 if (Ty0 != CurTy) { 2897 LLVM_DEBUG(dbgs() 2898 << "SLP: not-vectorizable GEP (different types).\n"); 2899 BS.cancelScheduling(VL, VL0); 2900 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2901 ReuseShuffleIndicies); 2902 return; 2903 } 2904 } 2905 2906 // We don't combine GEPs with non-constant indexes. 2907 Type *Ty1 = VL0->getOperand(1)->getType(); 2908 for (Value *V : VL) { 2909 auto Op = cast<Instruction>(V)->getOperand(1); 2910 if (!isa<ConstantInt>(Op) || 2911 (Op->getType() != Ty1 && 2912 Op->getType()->getScalarSizeInBits() > 2913 DL->getIndexSizeInBits( 2914 V->getType()->getPointerAddressSpace()))) { 2915 LLVM_DEBUG(dbgs() 2916 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 2917 BS.cancelScheduling(VL, VL0); 2918 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2919 ReuseShuffleIndicies); 2920 return; 2921 } 2922 } 2923 2924 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 2925 ReuseShuffleIndicies); 2926 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 2927 TE->setOperandsInOrder(); 2928 for (unsigned i = 0, e = 2; i < e; ++i) { 2929 ValueList Operands; 2930 // Prepare the operand vector. 2931 for (Value *V : VL) 2932 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 2933 2934 buildTree_rec(Operands, Depth + 1, {TE, i}); 2935 } 2936 return; 2937 } 2938 case Instruction::Store: { 2939 // Check if the stores are consecutive or if we need to swizzle them. 2940 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 2941 // Make sure all stores in the bundle are simple - we can't vectorize 2942 // atomic or volatile stores. 2943 SmallVector<Value *, 4> PointerOps(VL.size()); 2944 ValueList Operands(VL.size()); 2945 auto POIter = PointerOps.begin(); 2946 auto OIter = Operands.begin(); 2947 for (Value *V : VL) { 2948 auto *SI = cast<StoreInst>(V); 2949 if (!SI->isSimple()) { 2950 BS.cancelScheduling(VL, VL0); 2951 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 2952 ReuseShuffleIndicies); 2953 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 2954 return; 2955 } 2956 *POIter = SI->getPointerOperand(); 2957 *OIter = SI->getValueOperand(); 2958 ++POIter; 2959 ++OIter; 2960 } 2961 2962 OrdersType CurrentOrder; 2963 // Check the order of pointer operands. 2964 if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) { 2965 Value *Ptr0; 2966 Value *PtrN; 2967 if (CurrentOrder.empty()) { 2968 Ptr0 = PointerOps.front(); 2969 PtrN = PointerOps.back(); 2970 } else { 2971 Ptr0 = PointerOps[CurrentOrder.front()]; 2972 PtrN = PointerOps[CurrentOrder.back()]; 2973 } 2974 const SCEV *Scev0 = SE->getSCEV(Ptr0); 2975 const SCEV *ScevN = SE->getSCEV(PtrN); 2976 const auto *Diff = 2977 dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0)); 2978 uint64_t Size = DL->getTypeAllocSize(ScalarTy); 2979 // Check that the sorted pointer operands are consecutive. 2980 if (Diff && Diff->getAPInt() == (VL.size() - 1) * Size) { 2981 if (CurrentOrder.empty()) { 2982 // Original stores are consecutive and does not require reordering. 2983 ++NumOpsWantToKeepOriginalOrder; 2984 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 2985 UserTreeIdx, ReuseShuffleIndicies); 2986 TE->setOperandsInOrder(); 2987 buildTree_rec(Operands, Depth + 1, {TE, 0}); 2988 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 2989 } else { 2990 // Need to reorder. 2991 auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first; 2992 ++(I->getSecond()); 2993 TreeEntry *TE = 2994 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 2995 ReuseShuffleIndicies, I->getFirst()); 2996 TE->setOperandsInOrder(); 2997 buildTree_rec(Operands, Depth + 1, {TE, 0}); 2998 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 2999 } 3000 return; 3001 } 3002 } 3003 3004 BS.cancelScheduling(VL, VL0); 3005 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3006 ReuseShuffleIndicies); 3007 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 3008 return; 3009 } 3010 case Instruction::Call: { 3011 // Check if the calls are all to the same vectorizable intrinsic. 3012 CallInst *CI = cast<CallInst>(VL0); 3013 // Check if this is an Intrinsic call or something that can be 3014 // represented by an intrinsic call 3015 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 3016 if (!isTriviallyVectorizable(ID)) { 3017 BS.cancelScheduling(VL, VL0); 3018 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3019 ReuseShuffleIndicies); 3020 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 3021 return; 3022 } 3023 Function *Int = CI->getCalledFunction(); 3024 unsigned NumArgs = CI->getNumArgOperands(); 3025 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 3026 for (unsigned j = 0; j != NumArgs; ++j) 3027 if (hasVectorInstrinsicScalarOpd(ID, j)) 3028 ScalarArgs[j] = CI->getArgOperand(j); 3029 for (Value *V : VL) { 3030 CallInst *CI2 = dyn_cast<CallInst>(V); 3031 if (!CI2 || CI2->getCalledFunction() != Int || 3032 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 3033 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 3034 BS.cancelScheduling(VL, VL0); 3035 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3036 ReuseShuffleIndicies); 3037 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 3038 << "\n"); 3039 return; 3040 } 3041 // Some intrinsics have scalar arguments and should be same in order for 3042 // them to be vectorized. 3043 for (unsigned j = 0; j != NumArgs; ++j) { 3044 if (hasVectorInstrinsicScalarOpd(ID, j)) { 3045 Value *A1J = CI2->getArgOperand(j); 3046 if (ScalarArgs[j] != A1J) { 3047 BS.cancelScheduling(VL, VL0); 3048 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3049 ReuseShuffleIndicies); 3050 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 3051 << " argument " << ScalarArgs[j] << "!=" << A1J 3052 << "\n"); 3053 return; 3054 } 3055 } 3056 } 3057 // Verify that the bundle operands are identical between the two calls. 3058 if (CI->hasOperandBundles() && 3059 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 3060 CI->op_begin() + CI->getBundleOperandsEndIndex(), 3061 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 3062 BS.cancelScheduling(VL, VL0); 3063 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3064 ReuseShuffleIndicies); 3065 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 3066 << *CI << "!=" << *V << '\n'); 3067 return; 3068 } 3069 } 3070 3071 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3072 ReuseShuffleIndicies); 3073 TE->setOperandsInOrder(); 3074 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) { 3075 ValueList Operands; 3076 // Prepare the operand vector. 3077 for (Value *V : VL) { 3078 auto *CI2 = cast<CallInst>(V); 3079 Operands.push_back(CI2->getArgOperand(i)); 3080 } 3081 buildTree_rec(Operands, Depth + 1, {TE, i}); 3082 } 3083 return; 3084 } 3085 case Instruction::ShuffleVector: { 3086 // If this is not an alternate sequence of opcode like add-sub 3087 // then do not vectorize this instruction. 3088 if (!S.isAltShuffle()) { 3089 BS.cancelScheduling(VL, VL0); 3090 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3091 ReuseShuffleIndicies); 3092 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 3093 return; 3094 } 3095 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3096 ReuseShuffleIndicies); 3097 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 3098 3099 // Reorder operands if reordering would enable vectorization. 3100 if (isa<BinaryOperator>(VL0)) { 3101 ValueList Left, Right; 3102 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 3103 TE->setOperand(0, Left); 3104 TE->setOperand(1, Right); 3105 buildTree_rec(Left, Depth + 1, {TE, 0}); 3106 buildTree_rec(Right, Depth + 1, {TE, 1}); 3107 return; 3108 } 3109 3110 TE->setOperandsInOrder(); 3111 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 3112 ValueList Operands; 3113 // Prepare the operand vector. 3114 for (Value *V : VL) 3115 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 3116 3117 buildTree_rec(Operands, Depth + 1, {TE, i}); 3118 } 3119 return; 3120 } 3121 default: 3122 BS.cancelScheduling(VL, VL0); 3123 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3124 ReuseShuffleIndicies); 3125 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 3126 return; 3127 } 3128 } 3129 3130 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 3131 unsigned N = 1; 3132 Type *EltTy = T; 3133 3134 while (isa<StructType>(EltTy) || isa<SequentialType>(EltTy)) { 3135 if (auto *ST = dyn_cast<StructType>(EltTy)) { 3136 // Check that struct is homogeneous. 3137 for (const auto *Ty : ST->elements()) 3138 if (Ty != *ST->element_begin()) 3139 return 0; 3140 N *= ST->getNumElements(); 3141 EltTy = *ST->element_begin(); 3142 } else { 3143 auto *SeqT = cast<SequentialType>(EltTy); 3144 N *= SeqT->getNumElements(); 3145 EltTy = SeqT->getElementType(); 3146 } 3147 } 3148 3149 if (!isValidElementType(EltTy)) 3150 return 0; 3151 uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N)); 3152 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 3153 return 0; 3154 return N; 3155 } 3156 3157 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 3158 SmallVectorImpl<unsigned> &CurrentOrder) const { 3159 Instruction *E0 = cast<Instruction>(OpValue); 3160 assert(E0->getOpcode() == Instruction::ExtractElement || 3161 E0->getOpcode() == Instruction::ExtractValue); 3162 assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode"); 3163 // Check if all of the extracts come from the same vector and from the 3164 // correct offset. 3165 Value *Vec = E0->getOperand(0); 3166 3167 CurrentOrder.clear(); 3168 3169 // We have to extract from a vector/aggregate with the same number of elements. 3170 unsigned NElts; 3171 if (E0->getOpcode() == Instruction::ExtractValue) { 3172 const DataLayout &DL = E0->getModule()->getDataLayout(); 3173 NElts = canMapToVector(Vec->getType(), DL); 3174 if (!NElts) 3175 return false; 3176 // Check if load can be rewritten as load of vector. 3177 LoadInst *LI = dyn_cast<LoadInst>(Vec); 3178 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 3179 return false; 3180 } else { 3181 NElts = Vec->getType()->getVectorNumElements(); 3182 } 3183 3184 if (NElts != VL.size()) 3185 return false; 3186 3187 // Check that all of the indices extract from the correct offset. 3188 bool ShouldKeepOrder = true; 3189 unsigned E = VL.size(); 3190 // Assign to all items the initial value E + 1 so we can check if the extract 3191 // instruction index was used already. 3192 // Also, later we can check that all the indices are used and we have a 3193 // consecutive access in the extract instructions, by checking that no 3194 // element of CurrentOrder still has value E + 1. 3195 CurrentOrder.assign(E, E + 1); 3196 unsigned I = 0; 3197 for (; I < E; ++I) { 3198 auto *Inst = cast<Instruction>(VL[I]); 3199 if (Inst->getOperand(0) != Vec) 3200 break; 3201 Optional<unsigned> Idx = getExtractIndex(Inst); 3202 if (!Idx) 3203 break; 3204 const unsigned ExtIdx = *Idx; 3205 if (ExtIdx != I) { 3206 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1) 3207 break; 3208 ShouldKeepOrder = false; 3209 CurrentOrder[ExtIdx] = I; 3210 } else { 3211 if (CurrentOrder[I] != E + 1) 3212 break; 3213 CurrentOrder[I] = I; 3214 } 3215 } 3216 if (I < E) { 3217 CurrentOrder.clear(); 3218 return false; 3219 } 3220 3221 return ShouldKeepOrder; 3222 } 3223 3224 bool BoUpSLP::areAllUsersVectorized(Instruction *I) const { 3225 return I->hasOneUse() || 3226 std::all_of(I->user_begin(), I->user_end(), [this](User *U) { 3227 return ScalarToTreeEntry.count(U) > 0; 3228 }); 3229 } 3230 3231 static std::pair<unsigned, unsigned> 3232 getVectorCallCosts(CallInst *CI, VectorType *VecTy, TargetTransformInfo *TTI, 3233 TargetLibraryInfo *TLI) { 3234 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 3235 3236 // Calculate the cost of the scalar and vector calls. 3237 FastMathFlags FMF; 3238 if (auto *FPMO = dyn_cast<FPMathOperator>(CI)) 3239 FMF = FPMO->getFastMathFlags(); 3240 3241 SmallVector<Value *, 4> Args(CI->arg_operands()); 3242 int IntrinsicCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF, 3243 VecTy->getNumElements()); 3244 3245 auto Shape = 3246 VFShape::get(*CI, {static_cast<unsigned>(VecTy->getNumElements()), false}, 3247 false /*HasGlobalPred*/); 3248 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 3249 int LibCost = IntrinsicCost; 3250 if (!CI->isNoBuiltin() && VecFunc) { 3251 // Calculate the cost of the vector library call. 3252 SmallVector<Type *, 4> VecTys; 3253 for (Use &Arg : CI->args()) 3254 VecTys.push_back( 3255 VectorType::get(Arg->getType(), VecTy->getNumElements())); 3256 3257 // If the corresponding vector call is cheaper, return its cost. 3258 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys); 3259 } 3260 return {IntrinsicCost, LibCost}; 3261 } 3262 3263 int BoUpSLP::getEntryCost(TreeEntry *E) { 3264 ArrayRef<Value*> VL = E->Scalars; 3265 3266 Type *ScalarTy = VL[0]->getType(); 3267 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 3268 ScalarTy = SI->getValueOperand()->getType(); 3269 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 3270 ScalarTy = CI->getOperand(0)->getType(); 3271 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 3272 3273 // If we have computed a smaller type for the expression, update VecTy so 3274 // that the costs will be accurate. 3275 if (MinBWs.count(VL[0])) 3276 VecTy = VectorType::get( 3277 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 3278 3279 unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size(); 3280 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 3281 int ReuseShuffleCost = 0; 3282 if (NeedToShuffleReuses) { 3283 ReuseShuffleCost = 3284 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy); 3285 } 3286 if (E->State == TreeEntry::NeedToGather) { 3287 if (allConstant(VL)) 3288 return 0; 3289 if (isSplat(VL)) { 3290 return ReuseShuffleCost + 3291 TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0); 3292 } 3293 if (E->getOpcode() == Instruction::ExtractElement && 3294 allSameType(VL) && allSameBlock(VL)) { 3295 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = isShuffle(VL); 3296 if (ShuffleKind.hasValue()) { 3297 int Cost = TTI->getShuffleCost(ShuffleKind.getValue(), VecTy); 3298 for (auto *V : VL) { 3299 // If all users of instruction are going to be vectorized and this 3300 // instruction itself is not going to be vectorized, consider this 3301 // instruction as dead and remove its cost from the final cost of the 3302 // vectorized tree. 3303 if (areAllUsersVectorized(cast<Instruction>(V)) && 3304 !ScalarToTreeEntry.count(V)) { 3305 auto *IO = cast<ConstantInt>( 3306 cast<ExtractElementInst>(V)->getIndexOperand()); 3307 Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, 3308 IO->getZExtValue()); 3309 } 3310 } 3311 return ReuseShuffleCost + Cost; 3312 } 3313 } 3314 return ReuseShuffleCost + getGatherCost(VL); 3315 } 3316 assert(E->State == TreeEntry::Vectorize && "Unhandled state"); 3317 assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL"); 3318 Instruction *VL0 = E->getMainOp(); 3319 unsigned ShuffleOrOp = 3320 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 3321 switch (ShuffleOrOp) { 3322 case Instruction::PHI: 3323 return 0; 3324 3325 case Instruction::ExtractValue: 3326 case Instruction::ExtractElement: { 3327 if (NeedToShuffleReuses) { 3328 unsigned Idx = 0; 3329 for (unsigned I : E->ReuseShuffleIndices) { 3330 if (ShuffleOrOp == Instruction::ExtractElement) { 3331 auto *IO = cast<ConstantInt>( 3332 cast<ExtractElementInst>(VL[I])->getIndexOperand()); 3333 Idx = IO->getZExtValue(); 3334 ReuseShuffleCost -= TTI->getVectorInstrCost( 3335 Instruction::ExtractElement, VecTy, Idx); 3336 } else { 3337 ReuseShuffleCost -= TTI->getVectorInstrCost( 3338 Instruction::ExtractElement, VecTy, Idx); 3339 ++Idx; 3340 } 3341 } 3342 Idx = ReuseShuffleNumbers; 3343 for (Value *V : VL) { 3344 if (ShuffleOrOp == Instruction::ExtractElement) { 3345 auto *IO = cast<ConstantInt>( 3346 cast<ExtractElementInst>(V)->getIndexOperand()); 3347 Idx = IO->getZExtValue(); 3348 } else { 3349 --Idx; 3350 } 3351 ReuseShuffleCost += 3352 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx); 3353 } 3354 } 3355 int DeadCost = ReuseShuffleCost; 3356 if (!E->ReorderIndices.empty()) { 3357 // TODO: Merge this shuffle with the ReuseShuffleCost. 3358 DeadCost += TTI->getShuffleCost( 3359 TargetTransformInfo::SK_PermuteSingleSrc, VecTy); 3360 } 3361 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 3362 Instruction *E = cast<Instruction>(VL[i]); 3363 // If all users are going to be vectorized, instruction can be 3364 // considered as dead. 3365 // The same, if have only one user, it will be vectorized for sure. 3366 if (areAllUsersVectorized(E)) { 3367 // Take credit for instruction that will become dead. 3368 if (E->hasOneUse()) { 3369 Instruction *Ext = E->user_back(); 3370 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 3371 all_of(Ext->users(), 3372 [](User *U) { return isa<GetElementPtrInst>(U); })) { 3373 // Use getExtractWithExtendCost() to calculate the cost of 3374 // extractelement/ext pair. 3375 DeadCost -= TTI->getExtractWithExtendCost( 3376 Ext->getOpcode(), Ext->getType(), VecTy, i); 3377 // Add back the cost of s|zext which is subtracted separately. 3378 DeadCost += TTI->getCastInstrCost( 3379 Ext->getOpcode(), Ext->getType(), E->getType(), Ext); 3380 continue; 3381 } 3382 } 3383 DeadCost -= 3384 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i); 3385 } 3386 } 3387 return DeadCost; 3388 } 3389 case Instruction::ZExt: 3390 case Instruction::SExt: 3391 case Instruction::FPToUI: 3392 case Instruction::FPToSI: 3393 case Instruction::FPExt: 3394 case Instruction::PtrToInt: 3395 case Instruction::IntToPtr: 3396 case Instruction::SIToFP: 3397 case Instruction::UIToFP: 3398 case Instruction::Trunc: 3399 case Instruction::FPTrunc: 3400 case Instruction::BitCast: { 3401 Type *SrcTy = VL0->getOperand(0)->getType(); 3402 int ScalarEltCost = 3403 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, VL0); 3404 if (NeedToShuffleReuses) { 3405 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 3406 } 3407 3408 // Calculate the cost of this instruction. 3409 int ScalarCost = VL.size() * ScalarEltCost; 3410 3411 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size()); 3412 int VecCost = 0; 3413 // Check if the values are candidates to demote. 3414 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 3415 VecCost = ReuseShuffleCost + 3416 TTI->getCastInstrCost(E->getOpcode(), VecTy, SrcVecTy, VL0); 3417 } 3418 return VecCost - ScalarCost; 3419 } 3420 case Instruction::FCmp: 3421 case Instruction::ICmp: 3422 case Instruction::Select: { 3423 // Calculate the cost of this instruction. 3424 int ScalarEltCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, 3425 Builder.getInt1Ty(), VL0); 3426 if (NeedToShuffleReuses) { 3427 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 3428 } 3429 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size()); 3430 int ScalarCost = VecTy->getNumElements() * ScalarEltCost; 3431 int VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), VecTy, MaskTy, VL0); 3432 return ReuseShuffleCost + VecCost - ScalarCost; 3433 } 3434 case Instruction::FNeg: 3435 case Instruction::Add: 3436 case Instruction::FAdd: 3437 case Instruction::Sub: 3438 case Instruction::FSub: 3439 case Instruction::Mul: 3440 case Instruction::FMul: 3441 case Instruction::UDiv: 3442 case Instruction::SDiv: 3443 case Instruction::FDiv: 3444 case Instruction::URem: 3445 case Instruction::SRem: 3446 case Instruction::FRem: 3447 case Instruction::Shl: 3448 case Instruction::LShr: 3449 case Instruction::AShr: 3450 case Instruction::And: 3451 case Instruction::Or: 3452 case Instruction::Xor: { 3453 // Certain instructions can be cheaper to vectorize if they have a 3454 // constant second vector operand. 3455 TargetTransformInfo::OperandValueKind Op1VK = 3456 TargetTransformInfo::OK_AnyValue; 3457 TargetTransformInfo::OperandValueKind Op2VK = 3458 TargetTransformInfo::OK_UniformConstantValue; 3459 TargetTransformInfo::OperandValueProperties Op1VP = 3460 TargetTransformInfo::OP_None; 3461 TargetTransformInfo::OperandValueProperties Op2VP = 3462 TargetTransformInfo::OP_PowerOf2; 3463 3464 // If all operands are exactly the same ConstantInt then set the 3465 // operand kind to OK_UniformConstantValue. 3466 // If instead not all operands are constants, then set the operand kind 3467 // to OK_AnyValue. If all operands are constants but not the same, 3468 // then set the operand kind to OK_NonUniformConstantValue. 3469 ConstantInt *CInt0 = nullptr; 3470 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 3471 const Instruction *I = cast<Instruction>(VL[i]); 3472 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 3473 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 3474 if (!CInt) { 3475 Op2VK = TargetTransformInfo::OK_AnyValue; 3476 Op2VP = TargetTransformInfo::OP_None; 3477 break; 3478 } 3479 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 3480 !CInt->getValue().isPowerOf2()) 3481 Op2VP = TargetTransformInfo::OP_None; 3482 if (i == 0) { 3483 CInt0 = CInt; 3484 continue; 3485 } 3486 if (CInt0 != CInt) 3487 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 3488 } 3489 3490 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 3491 int ScalarEltCost = TTI->getArithmeticInstrCost( 3492 E->getOpcode(), ScalarTy, Op1VK, Op2VK, Op1VP, Op2VP, Operands, VL0); 3493 if (NeedToShuffleReuses) { 3494 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 3495 } 3496 int ScalarCost = VecTy->getNumElements() * ScalarEltCost; 3497 int VecCost = TTI->getArithmeticInstrCost( 3498 E->getOpcode(), VecTy, Op1VK, Op2VK, Op1VP, Op2VP, Operands, VL0); 3499 return ReuseShuffleCost + VecCost - ScalarCost; 3500 } 3501 case Instruction::GetElementPtr: { 3502 TargetTransformInfo::OperandValueKind Op1VK = 3503 TargetTransformInfo::OK_AnyValue; 3504 TargetTransformInfo::OperandValueKind Op2VK = 3505 TargetTransformInfo::OK_UniformConstantValue; 3506 3507 int ScalarEltCost = 3508 TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK); 3509 if (NeedToShuffleReuses) { 3510 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 3511 } 3512 int ScalarCost = VecTy->getNumElements() * ScalarEltCost; 3513 int VecCost = 3514 TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK); 3515 return ReuseShuffleCost + VecCost - ScalarCost; 3516 } 3517 case Instruction::Load: { 3518 // Cost of wide load - cost of scalar loads. 3519 MaybeAlign alignment(cast<LoadInst>(VL0)->getAlignment()); 3520 int ScalarEltCost = 3521 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0); 3522 if (NeedToShuffleReuses) { 3523 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 3524 } 3525 int ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 3526 int VecLdCost = 3527 TTI->getMemoryOpCost(Instruction::Load, VecTy, alignment, 0, VL0); 3528 if (!E->ReorderIndices.empty()) { 3529 // TODO: Merge this shuffle with the ReuseShuffleCost. 3530 VecLdCost += TTI->getShuffleCost( 3531 TargetTransformInfo::SK_PermuteSingleSrc, VecTy); 3532 } 3533 return ReuseShuffleCost + VecLdCost - ScalarLdCost; 3534 } 3535 case Instruction::Store: { 3536 // We know that we can merge the stores. Calculate the cost. 3537 bool IsReorder = !E->ReorderIndices.empty(); 3538 auto *SI = 3539 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 3540 MaybeAlign Alignment(SI->getAlignment()); 3541 int ScalarEltCost = 3542 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, Alignment, 0, VL0); 3543 if (NeedToShuffleReuses) 3544 ReuseShuffleCost = -(ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 3545 int ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 3546 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, 3547 VecTy, Alignment, 0, VL0); 3548 if (IsReorder) { 3549 // TODO: Merge this shuffle with the ReuseShuffleCost. 3550 VecStCost += TTI->getShuffleCost( 3551 TargetTransformInfo::SK_PermuteSingleSrc, VecTy); 3552 } 3553 return ReuseShuffleCost + VecStCost - ScalarStCost; 3554 } 3555 case Instruction::Call: { 3556 CallInst *CI = cast<CallInst>(VL0); 3557 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 3558 3559 // Calculate the cost of the scalar and vector calls. 3560 SmallVector<Type *, 4> ScalarTys; 3561 for (unsigned op = 0, opc = CI->getNumArgOperands(); op != opc; ++op) 3562 ScalarTys.push_back(CI->getArgOperand(op)->getType()); 3563 3564 FastMathFlags FMF; 3565 if (auto *FPMO = dyn_cast<FPMathOperator>(CI)) 3566 FMF = FPMO->getFastMathFlags(); 3567 3568 int ScalarEltCost = 3569 TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF); 3570 if (NeedToShuffleReuses) { 3571 ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost; 3572 } 3573 int ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 3574 3575 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 3576 int VecCallCost = std::min(VecCallCosts.first, VecCallCosts.second); 3577 3578 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 3579 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 3580 << " for " << *CI << "\n"); 3581 3582 return ReuseShuffleCost + VecCallCost - ScalarCallCost; 3583 } 3584 case Instruction::ShuffleVector: { 3585 assert(E->isAltShuffle() && 3586 ((Instruction::isBinaryOp(E->getOpcode()) && 3587 Instruction::isBinaryOp(E->getAltOpcode())) || 3588 (Instruction::isCast(E->getOpcode()) && 3589 Instruction::isCast(E->getAltOpcode()))) && 3590 "Invalid Shuffle Vector Operand"); 3591 int ScalarCost = 0; 3592 if (NeedToShuffleReuses) { 3593 for (unsigned Idx : E->ReuseShuffleIndices) { 3594 Instruction *I = cast<Instruction>(VL[Idx]); 3595 ReuseShuffleCost -= TTI->getInstructionCost( 3596 I, TargetTransformInfo::TCK_RecipThroughput); 3597 } 3598 for (Value *V : VL) { 3599 Instruction *I = cast<Instruction>(V); 3600 ReuseShuffleCost += TTI->getInstructionCost( 3601 I, TargetTransformInfo::TCK_RecipThroughput); 3602 } 3603 } 3604 for (Value *V : VL) { 3605 Instruction *I = cast<Instruction>(V); 3606 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 3607 ScalarCost += TTI->getInstructionCost( 3608 I, TargetTransformInfo::TCK_RecipThroughput); 3609 } 3610 // VecCost is equal to sum of the cost of creating 2 vectors 3611 // and the cost of creating shuffle. 3612 int VecCost = 0; 3613 if (Instruction::isBinaryOp(E->getOpcode())) { 3614 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy); 3615 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy); 3616 } else { 3617 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 3618 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 3619 VectorType *Src0Ty = VectorType::get(Src0SclTy, VL.size()); 3620 VectorType *Src1Ty = VectorType::get(Src1SclTy, VL.size()); 3621 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty); 3622 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty); 3623 } 3624 VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, 0); 3625 return ReuseShuffleCost + VecCost - ScalarCost; 3626 } 3627 default: 3628 llvm_unreachable("Unknown instruction"); 3629 } 3630 } 3631 3632 bool BoUpSLP::isFullyVectorizableTinyTree() const { 3633 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 3634 << VectorizableTree.size() << " is fully vectorizable .\n"); 3635 3636 // We only handle trees of heights 1 and 2. 3637 if (VectorizableTree.size() == 1 && 3638 VectorizableTree[0]->State == TreeEntry::Vectorize) 3639 return true; 3640 3641 if (VectorizableTree.size() != 2) 3642 return false; 3643 3644 // Handle splat and all-constants stores. 3645 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 3646 (allConstant(VectorizableTree[1]->Scalars) || 3647 isSplat(VectorizableTree[1]->Scalars))) 3648 return true; 3649 3650 // Gathering cost would be too much for tiny trees. 3651 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 3652 VectorizableTree[1]->State == TreeEntry::NeedToGather) 3653 return false; 3654 3655 return true; 3656 } 3657 3658 bool BoUpSLP::isLoadCombineReductionCandidate(unsigned RdxOpcode) const { 3659 if (RdxOpcode != Instruction::Or) 3660 return false; 3661 3662 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 3663 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 3664 3665 // Look past the reduction to find a source value. Arbitrarily follow the 3666 // path through operand 0 of any 'or'. Also, peek through optional 3667 // shift-left-by-constant. 3668 Value *ZextLoad = FirstReduced; 3669 while (match(ZextLoad, m_Or(m_Value(), m_Value())) || 3670 match(ZextLoad, m_Shl(m_Value(), m_Constant()))) 3671 ZextLoad = cast<BinaryOperator>(ZextLoad)->getOperand(0); 3672 3673 // Check if the input to the reduction is an extended load. 3674 Value *LoadPtr; 3675 if (!match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr))))) 3676 return false; 3677 3678 // Require that the total load bit width is a legal integer type. 3679 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 3680 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 3681 Type *SrcTy = LoadPtr->getType()->getPointerElementType(); 3682 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 3683 LLVMContext &Context = FirstReduced->getContext(); 3684 if (!TTI->isTypeLegal(IntegerType::get(Context, LoadBitWidth))) 3685 return false; 3686 3687 // Everything matched - assume that we can fold the whole sequence using 3688 // load combining. 3689 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for scalar reduction of " 3690 << *(cast<Instruction>(FirstReduced)) << "\n"); 3691 3692 return true; 3693 } 3694 3695 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const { 3696 // We can vectorize the tree if its size is greater than or equal to the 3697 // minimum size specified by the MinTreeSize command line option. 3698 if (VectorizableTree.size() >= MinTreeSize) 3699 return false; 3700 3701 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 3702 // can vectorize it if we can prove it fully vectorizable. 3703 if (isFullyVectorizableTinyTree()) 3704 return false; 3705 3706 assert(VectorizableTree.empty() 3707 ? ExternalUses.empty() 3708 : true && "We shouldn't have any external users"); 3709 3710 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 3711 // vectorizable. 3712 return true; 3713 } 3714 3715 int BoUpSLP::getSpillCost() const { 3716 // Walk from the bottom of the tree to the top, tracking which values are 3717 // live. When we see a call instruction that is not part of our tree, 3718 // query TTI to see if there is a cost to keeping values live over it 3719 // (for example, if spills and fills are required). 3720 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 3721 int Cost = 0; 3722 3723 SmallPtrSet<Instruction*, 4> LiveValues; 3724 Instruction *PrevInst = nullptr; 3725 3726 for (const auto &TEPtr : VectorizableTree) { 3727 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 3728 if (!Inst) 3729 continue; 3730 3731 if (!PrevInst) { 3732 PrevInst = Inst; 3733 continue; 3734 } 3735 3736 // Update LiveValues. 3737 LiveValues.erase(PrevInst); 3738 for (auto &J : PrevInst->operands()) { 3739 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 3740 LiveValues.insert(cast<Instruction>(&*J)); 3741 } 3742 3743 LLVM_DEBUG({ 3744 dbgs() << "SLP: #LV: " << LiveValues.size(); 3745 for (auto *X : LiveValues) 3746 dbgs() << " " << X->getName(); 3747 dbgs() << ", Looking at "; 3748 Inst->dump(); 3749 }); 3750 3751 // Now find the sequence of instructions between PrevInst and Inst. 3752 unsigned NumCalls = 0; 3753 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 3754 PrevInstIt = 3755 PrevInst->getIterator().getReverse(); 3756 while (InstIt != PrevInstIt) { 3757 if (PrevInstIt == PrevInst->getParent()->rend()) { 3758 PrevInstIt = Inst->getParent()->rbegin(); 3759 continue; 3760 } 3761 3762 // Debug information does not impact spill cost. 3763 if ((isa<CallInst>(&*PrevInstIt) && 3764 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 3765 &*PrevInstIt != PrevInst) 3766 NumCalls++; 3767 3768 ++PrevInstIt; 3769 } 3770 3771 if (NumCalls) { 3772 SmallVector<Type*, 4> V; 3773 for (auto *II : LiveValues) 3774 V.push_back(VectorType::get(II->getType(), BundleWidth)); 3775 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 3776 } 3777 3778 PrevInst = Inst; 3779 } 3780 3781 return Cost; 3782 } 3783 3784 int BoUpSLP::getTreeCost() { 3785 int Cost = 0; 3786 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 3787 << VectorizableTree.size() << ".\n"); 3788 3789 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 3790 3791 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 3792 TreeEntry &TE = *VectorizableTree[I].get(); 3793 3794 // We create duplicate tree entries for gather sequences that have multiple 3795 // uses. However, we should not compute the cost of duplicate sequences. 3796 // For example, if we have a build vector (i.e., insertelement sequence) 3797 // that is used by more than one vector instruction, we only need to 3798 // compute the cost of the insertelement instructions once. The redundant 3799 // instructions will be eliminated by CSE. 3800 // 3801 // We should consider not creating duplicate tree entries for gather 3802 // sequences, and instead add additional edges to the tree representing 3803 // their uses. Since such an approach results in fewer total entries, 3804 // existing heuristics based on tree size may yield different results. 3805 // 3806 if (TE.State == TreeEntry::NeedToGather && 3807 std::any_of(std::next(VectorizableTree.begin(), I + 1), 3808 VectorizableTree.end(), 3809 [TE](const std::unique_ptr<TreeEntry> &EntryPtr) { 3810 return EntryPtr->State == TreeEntry::NeedToGather && 3811 EntryPtr->isSame(TE.Scalars); 3812 })) 3813 continue; 3814 3815 int C = getEntryCost(&TE); 3816 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 3817 << " for bundle that starts with " << *TE.Scalars[0] 3818 << ".\n"); 3819 Cost += C; 3820 } 3821 3822 SmallPtrSet<Value *, 16> ExtractCostCalculated; 3823 int ExtractCost = 0; 3824 for (ExternalUser &EU : ExternalUses) { 3825 // We only add extract cost once for the same scalar. 3826 if (!ExtractCostCalculated.insert(EU.Scalar).second) 3827 continue; 3828 3829 // Uses by ephemeral values are free (because the ephemeral value will be 3830 // removed prior to code generation, and so the extraction will be 3831 // removed as well). 3832 if (EphValues.count(EU.User)) 3833 continue; 3834 3835 // If we plan to rewrite the tree in a smaller type, we will need to sign 3836 // extend the extracted value back to the original type. Here, we account 3837 // for the extract and the added cost of the sign extend if needed. 3838 auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth); 3839 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 3840 if (MinBWs.count(ScalarRoot)) { 3841 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 3842 auto Extend = 3843 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 3844 VecTy = VectorType::get(MinTy, BundleWidth); 3845 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 3846 VecTy, EU.Lane); 3847 } else { 3848 ExtractCost += 3849 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 3850 } 3851 } 3852 3853 int SpillCost = getSpillCost(); 3854 Cost += SpillCost + ExtractCost; 3855 3856 std::string Str; 3857 { 3858 raw_string_ostream OS(Str); 3859 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 3860 << "SLP: Extract Cost = " << ExtractCost << ".\n" 3861 << "SLP: Total Cost = " << Cost << ".\n"; 3862 } 3863 LLVM_DEBUG(dbgs() << Str); 3864 3865 if (ViewSLPTree) 3866 ViewGraph(this, "SLP" + F->getName(), false, Str); 3867 3868 return Cost; 3869 } 3870 3871 int BoUpSLP::getGatherCost(Type *Ty, 3872 const DenseSet<unsigned> &ShuffledIndices) const { 3873 int Cost = 0; 3874 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i) 3875 if (!ShuffledIndices.count(i)) 3876 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i); 3877 if (!ShuffledIndices.empty()) 3878 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 3879 return Cost; 3880 } 3881 3882 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 3883 // Find the type of the operands in VL. 3884 Type *ScalarTy = VL[0]->getType(); 3885 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 3886 ScalarTy = SI->getValueOperand()->getType(); 3887 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 3888 // Find the cost of inserting/extracting values from the vector. 3889 // Check if the same elements are inserted several times and count them as 3890 // shuffle candidates. 3891 DenseSet<unsigned> ShuffledElements; 3892 DenseSet<Value *> UniqueElements; 3893 // Iterate in reverse order to consider insert elements with the high cost. 3894 for (unsigned I = VL.size(); I > 0; --I) { 3895 unsigned Idx = I - 1; 3896 if (!UniqueElements.insert(VL[Idx]).second) 3897 ShuffledElements.insert(Idx); 3898 } 3899 return getGatherCost(VecTy, ShuffledElements); 3900 } 3901 3902 // Perform operand reordering on the instructions in VL and return the reordered 3903 // operands in Left and Right. 3904 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 3905 SmallVectorImpl<Value *> &Left, 3906 SmallVectorImpl<Value *> &Right, 3907 const DataLayout &DL, 3908 ScalarEvolution &SE, 3909 const BoUpSLP &R) { 3910 if (VL.empty()) 3911 return; 3912 VLOperands Ops(VL, DL, SE, R); 3913 // Reorder the operands in place. 3914 Ops.reorder(); 3915 Left = Ops.getVL(0); 3916 Right = Ops.getVL(1); 3917 } 3918 3919 void BoUpSLP::setInsertPointAfterBundle(TreeEntry *E) { 3920 // Get the basic block this bundle is in. All instructions in the bundle 3921 // should be in this block. 3922 auto *Front = E->getMainOp(); 3923 auto *BB = Front->getParent(); 3924 assert(llvm::all_of(make_range(E->Scalars.begin(), E->Scalars.end()), 3925 [=](Value *V) -> bool { 3926 auto *I = cast<Instruction>(V); 3927 return !E->isOpcodeOrAlt(I) || I->getParent() == BB; 3928 })); 3929 3930 // The last instruction in the bundle in program order. 3931 Instruction *LastInst = nullptr; 3932 3933 // Find the last instruction. The common case should be that BB has been 3934 // scheduled, and the last instruction is VL.back(). So we start with 3935 // VL.back() and iterate over schedule data until we reach the end of the 3936 // bundle. The end of the bundle is marked by null ScheduleData. 3937 if (BlocksSchedules.count(BB)) { 3938 auto *Bundle = 3939 BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back())); 3940 if (Bundle && Bundle->isPartOfBundle()) 3941 for (; Bundle; Bundle = Bundle->NextInBundle) 3942 if (Bundle->OpValue == Bundle->Inst) 3943 LastInst = Bundle->Inst; 3944 } 3945 3946 // LastInst can still be null at this point if there's either not an entry 3947 // for BB in BlocksSchedules or there's no ScheduleData available for 3948 // VL.back(). This can be the case if buildTree_rec aborts for various 3949 // reasons (e.g., the maximum recursion depth is reached, the maximum region 3950 // size is reached, etc.). ScheduleData is initialized in the scheduling 3951 // "dry-run". 3952 // 3953 // If this happens, we can still find the last instruction by brute force. We 3954 // iterate forwards from Front (inclusive) until we either see all 3955 // instructions in the bundle or reach the end of the block. If Front is the 3956 // last instruction in program order, LastInst will be set to Front, and we 3957 // will visit all the remaining instructions in the block. 3958 // 3959 // One of the reasons we exit early from buildTree_rec is to place an upper 3960 // bound on compile-time. Thus, taking an additional compile-time hit here is 3961 // not ideal. However, this should be exceedingly rare since it requires that 3962 // we both exit early from buildTree_rec and that the bundle be out-of-order 3963 // (causing us to iterate all the way to the end of the block). 3964 if (!LastInst) { 3965 SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end()); 3966 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) { 3967 if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I)) 3968 LastInst = &I; 3969 if (Bundle.empty()) 3970 break; 3971 } 3972 } 3973 assert(LastInst && "Failed to find last instruction in bundle"); 3974 3975 // Set the insertion point after the last instruction in the bundle. Set the 3976 // debug location to Front. 3977 Builder.SetInsertPoint(BB, ++LastInst->getIterator()); 3978 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 3979 } 3980 3981 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) { 3982 Value *Vec = UndefValue::get(Ty); 3983 // Generate the 'InsertElement' instruction. 3984 for (unsigned i = 0; i < Ty->getNumElements(); ++i) { 3985 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i)); 3986 if (auto *Insrt = dyn_cast<InsertElementInst>(Vec)) { 3987 GatherSeq.insert(Insrt); 3988 CSEBlocks.insert(Insrt->getParent()); 3989 3990 // Add to our 'need-to-extract' list. 3991 if (TreeEntry *E = getTreeEntry(VL[i])) { 3992 // Find which lane we need to extract. 3993 int FoundLane = -1; 3994 for (unsigned Lane = 0, LE = E->Scalars.size(); Lane != LE; ++Lane) { 3995 // Is this the lane of the scalar that we are looking for ? 3996 if (E->Scalars[Lane] == VL[i]) { 3997 FoundLane = Lane; 3998 break; 3999 } 4000 } 4001 assert(FoundLane >= 0 && "Could not find the correct lane"); 4002 if (!E->ReuseShuffleIndices.empty()) { 4003 FoundLane = 4004 std::distance(E->ReuseShuffleIndices.begin(), 4005 llvm::find(E->ReuseShuffleIndices, FoundLane)); 4006 } 4007 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane)); 4008 } 4009 } 4010 } 4011 4012 return Vec; 4013 } 4014 4015 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 4016 InstructionsState S = getSameOpcode(VL); 4017 if (S.getOpcode()) { 4018 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 4019 if (E->isSame(VL)) { 4020 Value *V = vectorizeTree(E); 4021 if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) { 4022 // We need to get the vectorized value but without shuffle. 4023 if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) { 4024 V = SV->getOperand(0); 4025 } else { 4026 // Reshuffle to get only unique values. 4027 SmallVector<unsigned, 4> UniqueIdxs; 4028 SmallSet<unsigned, 4> UsedIdxs; 4029 for(unsigned Idx : E->ReuseShuffleIndices) 4030 if (UsedIdxs.insert(Idx).second) 4031 UniqueIdxs.emplace_back(Idx); 4032 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()), 4033 UniqueIdxs); 4034 } 4035 } 4036 return V; 4037 } 4038 } 4039 } 4040 4041 Type *ScalarTy = S.OpValue->getType(); 4042 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 4043 ScalarTy = SI->getValueOperand()->getType(); 4044 4045 // Check that every instruction appears once in this bundle. 4046 SmallVector<unsigned, 4> ReuseShuffleIndicies; 4047 SmallVector<Value *, 4> UniqueValues; 4048 if (VL.size() > 2) { 4049 DenseMap<Value *, unsigned> UniquePositions; 4050 for (Value *V : VL) { 4051 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 4052 ReuseShuffleIndicies.emplace_back(Res.first->second); 4053 if (Res.second || isa<Constant>(V)) 4054 UniqueValues.emplace_back(V); 4055 } 4056 // Do not shuffle single element or if number of unique values is not power 4057 // of 2. 4058 if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 || 4059 !llvm::isPowerOf2_32(UniqueValues.size())) 4060 ReuseShuffleIndicies.clear(); 4061 else 4062 VL = UniqueValues; 4063 } 4064 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 4065 4066 Value *V = Gather(VL, VecTy); 4067 if (!ReuseShuffleIndicies.empty()) { 4068 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4069 ReuseShuffleIndicies, "shuffle"); 4070 if (auto *I = dyn_cast<Instruction>(V)) { 4071 GatherSeq.insert(I); 4072 CSEBlocks.insert(I->getParent()); 4073 } 4074 } 4075 return V; 4076 } 4077 4078 static void inversePermutation(ArrayRef<unsigned> Indices, 4079 SmallVectorImpl<unsigned> &Mask) { 4080 Mask.clear(); 4081 const unsigned E = Indices.size(); 4082 Mask.resize(E); 4083 for (unsigned I = 0; I < E; ++I) 4084 Mask[Indices[I]] = I; 4085 } 4086 4087 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 4088 IRBuilder<>::InsertPointGuard Guard(Builder); 4089 4090 if (E->VectorizedValue) { 4091 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 4092 return E->VectorizedValue; 4093 } 4094 4095 Instruction *VL0 = E->getMainOp(); 4096 Type *ScalarTy = VL0->getType(); 4097 if (StoreInst *SI = dyn_cast<StoreInst>(VL0)) 4098 ScalarTy = SI->getValueOperand()->getType(); 4099 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size()); 4100 4101 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 4102 4103 if (E->State == TreeEntry::NeedToGather) { 4104 setInsertPointAfterBundle(E); 4105 auto *V = Gather(E->Scalars, VecTy); 4106 if (NeedToShuffleReuses) { 4107 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4108 E->ReuseShuffleIndices, "shuffle"); 4109 if (auto *I = dyn_cast<Instruction>(V)) { 4110 GatherSeq.insert(I); 4111 CSEBlocks.insert(I->getParent()); 4112 } 4113 } 4114 E->VectorizedValue = V; 4115 return V; 4116 } 4117 4118 assert(E->State == TreeEntry::Vectorize && "Unhandled state"); 4119 unsigned ShuffleOrOp = 4120 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 4121 switch (ShuffleOrOp) { 4122 case Instruction::PHI: { 4123 auto *PH = cast<PHINode>(VL0); 4124 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 4125 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 4126 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 4127 Value *V = NewPhi; 4128 if (NeedToShuffleReuses) { 4129 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4130 E->ReuseShuffleIndices, "shuffle"); 4131 } 4132 E->VectorizedValue = V; 4133 4134 // PHINodes may have multiple entries from the same block. We want to 4135 // visit every block once. 4136 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 4137 4138 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 4139 ValueList Operands; 4140 BasicBlock *IBB = PH->getIncomingBlock(i); 4141 4142 if (!VisitedBBs.insert(IBB).second) { 4143 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 4144 continue; 4145 } 4146 4147 Builder.SetInsertPoint(IBB->getTerminator()); 4148 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 4149 Value *Vec = vectorizeTree(E->getOperand(i)); 4150 NewPhi->addIncoming(Vec, IBB); 4151 } 4152 4153 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 4154 "Invalid number of incoming values"); 4155 return V; 4156 } 4157 4158 case Instruction::ExtractElement: { 4159 Value *V = E->getSingleOperand(0); 4160 if (!E->ReorderIndices.empty()) { 4161 OrdersType Mask; 4162 inversePermutation(E->ReorderIndices, Mask); 4163 Builder.SetInsertPoint(VL0); 4164 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), Mask, 4165 "reorder_shuffle"); 4166 } 4167 if (NeedToShuffleReuses) { 4168 // TODO: Merge this shuffle with the ReorderShuffleMask. 4169 if (E->ReorderIndices.empty()) 4170 Builder.SetInsertPoint(VL0); 4171 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4172 E->ReuseShuffleIndices, "shuffle"); 4173 } 4174 E->VectorizedValue = V; 4175 return V; 4176 } 4177 case Instruction::ExtractValue: { 4178 LoadInst *LI = cast<LoadInst>(E->getSingleOperand(0)); 4179 Builder.SetInsertPoint(LI); 4180 PointerType *PtrTy = 4181 PointerType::get(VecTy, LI->getPointerAddressSpace()); 4182 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 4183 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 4184 Value *NewV = propagateMetadata(V, E->Scalars); 4185 if (!E->ReorderIndices.empty()) { 4186 OrdersType Mask; 4187 inversePermutation(E->ReorderIndices, Mask); 4188 NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), Mask, 4189 "reorder_shuffle"); 4190 } 4191 if (NeedToShuffleReuses) { 4192 // TODO: Merge this shuffle with the ReorderShuffleMask. 4193 NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), 4194 E->ReuseShuffleIndices, "shuffle"); 4195 } 4196 E->VectorizedValue = NewV; 4197 return NewV; 4198 } 4199 case Instruction::ZExt: 4200 case Instruction::SExt: 4201 case Instruction::FPToUI: 4202 case Instruction::FPToSI: 4203 case Instruction::FPExt: 4204 case Instruction::PtrToInt: 4205 case Instruction::IntToPtr: 4206 case Instruction::SIToFP: 4207 case Instruction::UIToFP: 4208 case Instruction::Trunc: 4209 case Instruction::FPTrunc: 4210 case Instruction::BitCast: { 4211 setInsertPointAfterBundle(E); 4212 4213 Value *InVec = vectorizeTree(E->getOperand(0)); 4214 4215 if (E->VectorizedValue) { 4216 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 4217 return E->VectorizedValue; 4218 } 4219 4220 auto *CI = cast<CastInst>(VL0); 4221 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 4222 if (NeedToShuffleReuses) { 4223 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4224 E->ReuseShuffleIndices, "shuffle"); 4225 } 4226 E->VectorizedValue = V; 4227 ++NumVectorInstructions; 4228 return V; 4229 } 4230 case Instruction::FCmp: 4231 case Instruction::ICmp: { 4232 setInsertPointAfterBundle(E); 4233 4234 Value *L = vectorizeTree(E->getOperand(0)); 4235 Value *R = vectorizeTree(E->getOperand(1)); 4236 4237 if (E->VectorizedValue) { 4238 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 4239 return E->VectorizedValue; 4240 } 4241 4242 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 4243 Value *V; 4244 if (E->getOpcode() == Instruction::FCmp) 4245 V = Builder.CreateFCmp(P0, L, R); 4246 else 4247 V = Builder.CreateICmp(P0, L, R); 4248 4249 propagateIRFlags(V, E->Scalars, VL0); 4250 if (NeedToShuffleReuses) { 4251 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4252 E->ReuseShuffleIndices, "shuffle"); 4253 } 4254 E->VectorizedValue = V; 4255 ++NumVectorInstructions; 4256 return V; 4257 } 4258 case Instruction::Select: { 4259 setInsertPointAfterBundle(E); 4260 4261 Value *Cond = vectorizeTree(E->getOperand(0)); 4262 Value *True = vectorizeTree(E->getOperand(1)); 4263 Value *False = vectorizeTree(E->getOperand(2)); 4264 4265 if (E->VectorizedValue) { 4266 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 4267 return E->VectorizedValue; 4268 } 4269 4270 Value *V = Builder.CreateSelect(Cond, True, False); 4271 if (NeedToShuffleReuses) { 4272 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4273 E->ReuseShuffleIndices, "shuffle"); 4274 } 4275 E->VectorizedValue = V; 4276 ++NumVectorInstructions; 4277 return V; 4278 } 4279 case Instruction::FNeg: { 4280 setInsertPointAfterBundle(E); 4281 4282 Value *Op = vectorizeTree(E->getOperand(0)); 4283 4284 if (E->VectorizedValue) { 4285 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 4286 return E->VectorizedValue; 4287 } 4288 4289 Value *V = Builder.CreateUnOp( 4290 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 4291 propagateIRFlags(V, E->Scalars, VL0); 4292 if (auto *I = dyn_cast<Instruction>(V)) 4293 V = propagateMetadata(I, E->Scalars); 4294 4295 if (NeedToShuffleReuses) { 4296 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4297 E->ReuseShuffleIndices, "shuffle"); 4298 } 4299 E->VectorizedValue = V; 4300 ++NumVectorInstructions; 4301 4302 return V; 4303 } 4304 case Instruction::Add: 4305 case Instruction::FAdd: 4306 case Instruction::Sub: 4307 case Instruction::FSub: 4308 case Instruction::Mul: 4309 case Instruction::FMul: 4310 case Instruction::UDiv: 4311 case Instruction::SDiv: 4312 case Instruction::FDiv: 4313 case Instruction::URem: 4314 case Instruction::SRem: 4315 case Instruction::FRem: 4316 case Instruction::Shl: 4317 case Instruction::LShr: 4318 case Instruction::AShr: 4319 case Instruction::And: 4320 case Instruction::Or: 4321 case Instruction::Xor: { 4322 setInsertPointAfterBundle(E); 4323 4324 Value *LHS = vectorizeTree(E->getOperand(0)); 4325 Value *RHS = vectorizeTree(E->getOperand(1)); 4326 4327 if (E->VectorizedValue) { 4328 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 4329 return E->VectorizedValue; 4330 } 4331 4332 Value *V = Builder.CreateBinOp( 4333 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 4334 RHS); 4335 propagateIRFlags(V, E->Scalars, VL0); 4336 if (auto *I = dyn_cast<Instruction>(V)) 4337 V = propagateMetadata(I, E->Scalars); 4338 4339 if (NeedToShuffleReuses) { 4340 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4341 E->ReuseShuffleIndices, "shuffle"); 4342 } 4343 E->VectorizedValue = V; 4344 ++NumVectorInstructions; 4345 4346 return V; 4347 } 4348 case Instruction::Load: { 4349 // Loads are inserted at the head of the tree because we don't want to 4350 // sink them all the way down past store instructions. 4351 bool IsReorder = E->updateStateIfReorder(); 4352 if (IsReorder) 4353 VL0 = E->getMainOp(); 4354 setInsertPointAfterBundle(E); 4355 4356 LoadInst *LI = cast<LoadInst>(VL0); 4357 Type *ScalarLoadTy = LI->getType(); 4358 unsigned AS = LI->getPointerAddressSpace(); 4359 4360 Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(), 4361 VecTy->getPointerTo(AS)); 4362 4363 // The pointer operand uses an in-tree scalar so we add the new BitCast to 4364 // ExternalUses list to make sure that an extract will be generated in the 4365 // future. 4366 Value *PO = LI->getPointerOperand(); 4367 if (getTreeEntry(PO)) 4368 ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0)); 4369 4370 MaybeAlign Alignment = MaybeAlign(LI->getAlignment()); 4371 LI = Builder.CreateLoad(VecTy, VecPtr); 4372 if (!Alignment) 4373 Alignment = MaybeAlign(DL->getABITypeAlignment(ScalarLoadTy)); 4374 LI->setAlignment(Alignment); 4375 Value *V = propagateMetadata(LI, E->Scalars); 4376 if (IsReorder) { 4377 OrdersType Mask; 4378 inversePermutation(E->ReorderIndices, Mask); 4379 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()), 4380 Mask, "reorder_shuffle"); 4381 } 4382 if (NeedToShuffleReuses) { 4383 // TODO: Merge this shuffle with the ReorderShuffleMask. 4384 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4385 E->ReuseShuffleIndices, "shuffle"); 4386 } 4387 E->VectorizedValue = V; 4388 ++NumVectorInstructions; 4389 return V; 4390 } 4391 case Instruction::Store: { 4392 bool IsReorder = !E->ReorderIndices.empty(); 4393 auto *SI = cast<StoreInst>( 4394 IsReorder ? E->Scalars[E->ReorderIndices.front()] : VL0); 4395 unsigned Alignment = SI->getAlignment(); 4396 unsigned AS = SI->getPointerAddressSpace(); 4397 4398 setInsertPointAfterBundle(E); 4399 4400 Value *VecValue = vectorizeTree(E->getOperand(0)); 4401 if (IsReorder) { 4402 OrdersType Mask; 4403 inversePermutation(E->ReorderIndices, Mask); 4404 VecValue = Builder.CreateShuffleVector( 4405 VecValue, UndefValue::get(VecValue->getType()), E->ReorderIndices, 4406 "reorder_shuffle"); 4407 } 4408 Value *ScalarPtr = SI->getPointerOperand(); 4409 Value *VecPtr = Builder.CreateBitCast( 4410 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 4411 StoreInst *ST = Builder.CreateStore(VecValue, VecPtr); 4412 4413 // The pointer operand uses an in-tree scalar, so add the new BitCast to 4414 // ExternalUses to make sure that an extract will be generated in the 4415 // future. 4416 if (getTreeEntry(ScalarPtr)) 4417 ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0)); 4418 4419 if (!Alignment) 4420 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType()); 4421 4422 ST->setAlignment(Align(Alignment)); 4423 Value *V = propagateMetadata(ST, E->Scalars); 4424 if (NeedToShuffleReuses) { 4425 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4426 E->ReuseShuffleIndices, "shuffle"); 4427 } 4428 E->VectorizedValue = V; 4429 ++NumVectorInstructions; 4430 return V; 4431 } 4432 case Instruction::GetElementPtr: { 4433 setInsertPointAfterBundle(E); 4434 4435 Value *Op0 = vectorizeTree(E->getOperand(0)); 4436 4437 std::vector<Value *> OpVecs; 4438 for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e; 4439 ++j) { 4440 ValueList &VL = E->getOperand(j); 4441 // Need to cast all elements to the same type before vectorization to 4442 // avoid crash. 4443 Type *VL0Ty = VL0->getOperand(j)->getType(); 4444 Type *Ty = llvm::all_of( 4445 VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); }) 4446 ? VL0Ty 4447 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 4448 ->getPointerOperandType() 4449 ->getScalarType()); 4450 for (Value *&V : VL) { 4451 auto *CI = cast<ConstantInt>(V); 4452 V = ConstantExpr::getIntegerCast(CI, Ty, 4453 CI->getValue().isSignBitSet()); 4454 } 4455 Value *OpVec = vectorizeTree(VL); 4456 OpVecs.push_back(OpVec); 4457 } 4458 4459 Value *V = Builder.CreateGEP( 4460 cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs); 4461 if (Instruction *I = dyn_cast<Instruction>(V)) 4462 V = propagateMetadata(I, E->Scalars); 4463 4464 if (NeedToShuffleReuses) { 4465 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4466 E->ReuseShuffleIndices, "shuffle"); 4467 } 4468 E->VectorizedValue = V; 4469 ++NumVectorInstructions; 4470 4471 return V; 4472 } 4473 case Instruction::Call: { 4474 CallInst *CI = cast<CallInst>(VL0); 4475 setInsertPointAfterBundle(E); 4476 4477 Intrinsic::ID IID = Intrinsic::not_intrinsic; 4478 if (Function *FI = CI->getCalledFunction()) 4479 IID = FI->getIntrinsicID(); 4480 4481 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4482 4483 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 4484 bool UseIntrinsic = VecCallCosts.first <= VecCallCosts.second; 4485 4486 Value *ScalarArg = nullptr; 4487 std::vector<Value *> OpVecs; 4488 for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) { 4489 ValueList OpVL; 4490 // Some intrinsics have scalar arguments. This argument should not be 4491 // vectorized. 4492 if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) { 4493 CallInst *CEI = cast<CallInst>(VL0); 4494 ScalarArg = CEI->getArgOperand(j); 4495 OpVecs.push_back(CEI->getArgOperand(j)); 4496 continue; 4497 } 4498 4499 Value *OpVec = vectorizeTree(E->getOperand(j)); 4500 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 4501 OpVecs.push_back(OpVec); 4502 } 4503 4504 Module *M = F->getParent(); 4505 Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) }; 4506 Function *CF = Intrinsic::getDeclaration(M, ID, Tys); 4507 4508 if (!UseIntrinsic) { 4509 VFShape Shape = VFShape::get( 4510 *CI, {static_cast<unsigned>(VecTy->getNumElements()), false}, 4511 false /*HasGlobalPred*/); 4512 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 4513 } 4514 4515 SmallVector<OperandBundleDef, 1> OpBundles; 4516 CI->getOperandBundlesAsDefs(OpBundles); 4517 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 4518 4519 // The scalar argument uses an in-tree scalar so we add the new vectorized 4520 // call to ExternalUses list to make sure that an extract will be 4521 // generated in the future. 4522 if (ScalarArg && getTreeEntry(ScalarArg)) 4523 ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0)); 4524 4525 propagateIRFlags(V, E->Scalars, VL0); 4526 if (NeedToShuffleReuses) { 4527 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4528 E->ReuseShuffleIndices, "shuffle"); 4529 } 4530 E->VectorizedValue = V; 4531 ++NumVectorInstructions; 4532 return V; 4533 } 4534 case Instruction::ShuffleVector: { 4535 assert(E->isAltShuffle() && 4536 ((Instruction::isBinaryOp(E->getOpcode()) && 4537 Instruction::isBinaryOp(E->getAltOpcode())) || 4538 (Instruction::isCast(E->getOpcode()) && 4539 Instruction::isCast(E->getAltOpcode()))) && 4540 "Invalid Shuffle Vector Operand"); 4541 4542 Value *LHS = nullptr, *RHS = nullptr; 4543 if (Instruction::isBinaryOp(E->getOpcode())) { 4544 setInsertPointAfterBundle(E); 4545 LHS = vectorizeTree(E->getOperand(0)); 4546 RHS = vectorizeTree(E->getOperand(1)); 4547 } else { 4548 setInsertPointAfterBundle(E); 4549 LHS = vectorizeTree(E->getOperand(0)); 4550 } 4551 4552 if (E->VectorizedValue) { 4553 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 4554 return E->VectorizedValue; 4555 } 4556 4557 Value *V0, *V1; 4558 if (Instruction::isBinaryOp(E->getOpcode())) { 4559 V0 = Builder.CreateBinOp( 4560 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 4561 V1 = Builder.CreateBinOp( 4562 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 4563 } else { 4564 V0 = Builder.CreateCast( 4565 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 4566 V1 = Builder.CreateCast( 4567 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 4568 } 4569 4570 // Create shuffle to take alternate operations from the vector. 4571 // Also, gather up main and alt scalar ops to propagate IR flags to 4572 // each vector operation. 4573 ValueList OpScalars, AltScalars; 4574 unsigned e = E->Scalars.size(); 4575 SmallVector<Constant *, 8> Mask(e); 4576 for (unsigned i = 0; i < e; ++i) { 4577 auto *OpInst = cast<Instruction>(E->Scalars[i]); 4578 assert(E->isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode"); 4579 if (OpInst->getOpcode() == E->getAltOpcode()) { 4580 Mask[i] = Builder.getInt32(e + i); 4581 AltScalars.push_back(E->Scalars[i]); 4582 } else { 4583 Mask[i] = Builder.getInt32(i); 4584 OpScalars.push_back(E->Scalars[i]); 4585 } 4586 } 4587 4588 Value *ShuffleMask = ConstantVector::get(Mask); 4589 propagateIRFlags(V0, OpScalars); 4590 propagateIRFlags(V1, AltScalars); 4591 4592 Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask); 4593 if (Instruction *I = dyn_cast<Instruction>(V)) 4594 V = propagateMetadata(I, E->Scalars); 4595 if (NeedToShuffleReuses) { 4596 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), 4597 E->ReuseShuffleIndices, "shuffle"); 4598 } 4599 E->VectorizedValue = V; 4600 ++NumVectorInstructions; 4601 4602 return V; 4603 } 4604 default: 4605 llvm_unreachable("unknown inst"); 4606 } 4607 return nullptr; 4608 } 4609 4610 Value *BoUpSLP::vectorizeTree() { 4611 ExtraValueToDebugLocsMap ExternallyUsedValues; 4612 return vectorizeTree(ExternallyUsedValues); 4613 } 4614 4615 Value * 4616 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 4617 // All blocks must be scheduled before any instructions are inserted. 4618 for (auto &BSIter : BlocksSchedules) { 4619 scheduleBlock(BSIter.second.get()); 4620 } 4621 4622 Builder.SetInsertPoint(&F->getEntryBlock().front()); 4623 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 4624 4625 // If the vectorized tree can be rewritten in a smaller type, we truncate the 4626 // vectorized root. InstCombine will then rewrite the entire expression. We 4627 // sign extend the extracted values below. 4628 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 4629 if (MinBWs.count(ScalarRoot)) { 4630 if (auto *I = dyn_cast<Instruction>(VectorRoot)) 4631 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 4632 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 4633 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 4634 auto *VecTy = VectorType::get(MinTy, BundleWidth); 4635 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 4636 VectorizableTree[0]->VectorizedValue = Trunc; 4637 } 4638 4639 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 4640 << " values .\n"); 4641 4642 // If necessary, sign-extend or zero-extend ScalarRoot to the larger type 4643 // specified by ScalarType. 4644 auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) { 4645 if (!MinBWs.count(ScalarRoot)) 4646 return Ex; 4647 if (MinBWs[ScalarRoot].second) 4648 return Builder.CreateSExt(Ex, ScalarType); 4649 return Builder.CreateZExt(Ex, ScalarType); 4650 }; 4651 4652 // Extract all of the elements with the external uses. 4653 for (const auto &ExternalUse : ExternalUses) { 4654 Value *Scalar = ExternalUse.Scalar; 4655 llvm::User *User = ExternalUse.User; 4656 4657 // Skip users that we already RAUW. This happens when one instruction 4658 // has multiple uses of the same value. 4659 if (User && !is_contained(Scalar->users(), User)) 4660 continue; 4661 TreeEntry *E = getTreeEntry(Scalar); 4662 assert(E && "Invalid scalar"); 4663 assert(E->State == TreeEntry::Vectorize && "Extracting from a gather list"); 4664 4665 Value *Vec = E->VectorizedValue; 4666 assert(Vec && "Can't find vectorizable value"); 4667 4668 Value *Lane = Builder.getInt32(ExternalUse.Lane); 4669 // If User == nullptr, the Scalar is used as extra arg. Generate 4670 // ExtractElement instruction and update the record for this scalar in 4671 // ExternallyUsedValues. 4672 if (!User) { 4673 assert(ExternallyUsedValues.count(Scalar) && 4674 "Scalar with nullptr as an external user must be registered in " 4675 "ExternallyUsedValues map"); 4676 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 4677 Builder.SetInsertPoint(VecI->getParent(), 4678 std::next(VecI->getIterator())); 4679 } else { 4680 Builder.SetInsertPoint(&F->getEntryBlock().front()); 4681 } 4682 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 4683 Ex = extend(ScalarRoot, Ex, Scalar->getType()); 4684 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 4685 auto &Locs = ExternallyUsedValues[Scalar]; 4686 ExternallyUsedValues.insert({Ex, Locs}); 4687 ExternallyUsedValues.erase(Scalar); 4688 // Required to update internally referenced instructions. 4689 Scalar->replaceAllUsesWith(Ex); 4690 continue; 4691 } 4692 4693 // Generate extracts for out-of-tree users. 4694 // Find the insertion point for the extractelement lane. 4695 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 4696 if (PHINode *PH = dyn_cast<PHINode>(User)) { 4697 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 4698 if (PH->getIncomingValue(i) == Scalar) { 4699 Instruction *IncomingTerminator = 4700 PH->getIncomingBlock(i)->getTerminator(); 4701 if (isa<CatchSwitchInst>(IncomingTerminator)) { 4702 Builder.SetInsertPoint(VecI->getParent(), 4703 std::next(VecI->getIterator())); 4704 } else { 4705 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 4706 } 4707 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 4708 Ex = extend(ScalarRoot, Ex, Scalar->getType()); 4709 CSEBlocks.insert(PH->getIncomingBlock(i)); 4710 PH->setOperand(i, Ex); 4711 } 4712 } 4713 } else { 4714 Builder.SetInsertPoint(cast<Instruction>(User)); 4715 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 4716 Ex = extend(ScalarRoot, Ex, Scalar->getType()); 4717 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 4718 User->replaceUsesOfWith(Scalar, Ex); 4719 } 4720 } else { 4721 Builder.SetInsertPoint(&F->getEntryBlock().front()); 4722 Value *Ex = Builder.CreateExtractElement(Vec, Lane); 4723 Ex = extend(ScalarRoot, Ex, Scalar->getType()); 4724 CSEBlocks.insert(&F->getEntryBlock()); 4725 User->replaceUsesOfWith(Scalar, Ex); 4726 } 4727 4728 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 4729 } 4730 4731 // For each vectorized value: 4732 for (auto &TEPtr : VectorizableTree) { 4733 TreeEntry *Entry = TEPtr.get(); 4734 4735 // No need to handle users of gathered values. 4736 if (Entry->State == TreeEntry::NeedToGather) 4737 continue; 4738 4739 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 4740 4741 // For each lane: 4742 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 4743 Value *Scalar = Entry->Scalars[Lane]; 4744 4745 #ifndef NDEBUG 4746 Type *Ty = Scalar->getType(); 4747 if (!Ty->isVoidTy()) { 4748 for (User *U : Scalar->users()) { 4749 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 4750 4751 // It is legal to delete users in the ignorelist. 4752 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) && 4753 "Deleting out-of-tree value"); 4754 } 4755 } 4756 #endif 4757 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 4758 eraseInstruction(cast<Instruction>(Scalar)); 4759 } 4760 } 4761 4762 Builder.ClearInsertionPoint(); 4763 4764 return VectorizableTree[0]->VectorizedValue; 4765 } 4766 4767 void BoUpSLP::optimizeGatherSequence() { 4768 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size() 4769 << " gather sequences instructions.\n"); 4770 // LICM InsertElementInst sequences. 4771 for (Instruction *I : GatherSeq) { 4772 if (isDeleted(I)) 4773 continue; 4774 4775 // Check if this block is inside a loop. 4776 Loop *L = LI->getLoopFor(I->getParent()); 4777 if (!L) 4778 continue; 4779 4780 // Check if it has a preheader. 4781 BasicBlock *PreHeader = L->getLoopPreheader(); 4782 if (!PreHeader) 4783 continue; 4784 4785 // If the vector or the element that we insert into it are 4786 // instructions that are defined in this basic block then we can't 4787 // hoist this instruction. 4788 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 4789 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 4790 if (Op0 && L->contains(Op0)) 4791 continue; 4792 if (Op1 && L->contains(Op1)) 4793 continue; 4794 4795 // We can hoist this instruction. Move it to the pre-header. 4796 I->moveBefore(PreHeader->getTerminator()); 4797 } 4798 4799 // Make a list of all reachable blocks in our CSE queue. 4800 SmallVector<const DomTreeNode *, 8> CSEWorkList; 4801 CSEWorkList.reserve(CSEBlocks.size()); 4802 for (BasicBlock *BB : CSEBlocks) 4803 if (DomTreeNode *N = DT->getNode(BB)) { 4804 assert(DT->isReachableFromEntry(N)); 4805 CSEWorkList.push_back(N); 4806 } 4807 4808 // Sort blocks by domination. This ensures we visit a block after all blocks 4809 // dominating it are visited. 4810 llvm::stable_sort(CSEWorkList, 4811 [this](const DomTreeNode *A, const DomTreeNode *B) { 4812 return DT->properlyDominates(A, B); 4813 }); 4814 4815 // Perform O(N^2) search over the gather sequences and merge identical 4816 // instructions. TODO: We can further optimize this scan if we split the 4817 // instructions into different buckets based on the insert lane. 4818 SmallVector<Instruction *, 16> Visited; 4819 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 4820 assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 4821 "Worklist not sorted properly!"); 4822 BasicBlock *BB = (*I)->getBlock(); 4823 // For all instructions in blocks containing gather sequences: 4824 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) { 4825 Instruction *In = &*it++; 4826 if (isDeleted(In)) 4827 continue; 4828 if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) 4829 continue; 4830 4831 // Check if we can replace this instruction with any of the 4832 // visited instructions. 4833 for (Instruction *v : Visited) { 4834 if (In->isIdenticalTo(v) && 4835 DT->dominates(v->getParent(), In->getParent())) { 4836 In->replaceAllUsesWith(v); 4837 eraseInstruction(In); 4838 In = nullptr; 4839 break; 4840 } 4841 } 4842 if (In) { 4843 assert(!is_contained(Visited, In)); 4844 Visited.push_back(In); 4845 } 4846 } 4847 } 4848 CSEBlocks.clear(); 4849 GatherSeq.clear(); 4850 } 4851 4852 // Groups the instructions to a bundle (which is then a single scheduling entity) 4853 // and schedules instructions until the bundle gets ready. 4854 Optional<BoUpSLP::ScheduleData *> 4855 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 4856 const InstructionsState &S) { 4857 if (isa<PHINode>(S.OpValue)) 4858 return nullptr; 4859 4860 // Initialize the instruction bundle. 4861 Instruction *OldScheduleEnd = ScheduleEnd; 4862 ScheduleData *PrevInBundle = nullptr; 4863 ScheduleData *Bundle = nullptr; 4864 bool ReSchedule = false; 4865 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 4866 4867 // Make sure that the scheduling region contains all 4868 // instructions of the bundle. 4869 for (Value *V : VL) { 4870 if (!extendSchedulingRegion(V, S)) 4871 return None; 4872 } 4873 4874 for (Value *V : VL) { 4875 ScheduleData *BundleMember = getScheduleData(V); 4876 assert(BundleMember && 4877 "no ScheduleData for bundle member (maybe not in same basic block)"); 4878 if (BundleMember->IsScheduled) { 4879 // A bundle member was scheduled as single instruction before and now 4880 // needs to be scheduled as part of the bundle. We just get rid of the 4881 // existing schedule. 4882 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 4883 << " was already scheduled\n"); 4884 ReSchedule = true; 4885 } 4886 assert(BundleMember->isSchedulingEntity() && 4887 "bundle member already part of other bundle"); 4888 if (PrevInBundle) { 4889 PrevInBundle->NextInBundle = BundleMember; 4890 } else { 4891 Bundle = BundleMember; 4892 } 4893 BundleMember->UnscheduledDepsInBundle = 0; 4894 Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps; 4895 4896 // Group the instructions to a bundle. 4897 BundleMember->FirstInBundle = Bundle; 4898 PrevInBundle = BundleMember; 4899 } 4900 if (ScheduleEnd != OldScheduleEnd) { 4901 // The scheduling region got new instructions at the lower end (or it is a 4902 // new region for the first bundle). This makes it necessary to 4903 // recalculate all dependencies. 4904 // It is seldom that this needs to be done a second time after adding the 4905 // initial bundle to the region. 4906 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 4907 doForAllOpcodes(I, [](ScheduleData *SD) { 4908 SD->clearDependencies(); 4909 }); 4910 } 4911 ReSchedule = true; 4912 } 4913 if (ReSchedule) { 4914 resetSchedule(); 4915 initialFillReadyList(ReadyInsts); 4916 } 4917 assert(Bundle && "Failed to find schedule bundle"); 4918 4919 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block " 4920 << BB->getName() << "\n"); 4921 4922 calculateDependencies(Bundle, true, SLP); 4923 4924 // Now try to schedule the new bundle. As soon as the bundle is "ready" it 4925 // means that there are no cyclic dependencies and we can schedule it. 4926 // Note that's important that we don't "schedule" the bundle yet (see 4927 // cancelScheduling). 4928 while (!Bundle->isReady() && !ReadyInsts.empty()) { 4929 4930 ScheduleData *pickedSD = ReadyInsts.back(); 4931 ReadyInsts.pop_back(); 4932 4933 if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) { 4934 schedule(pickedSD, ReadyInsts); 4935 } 4936 } 4937 if (!Bundle->isReady()) { 4938 cancelScheduling(VL, S.OpValue); 4939 return None; 4940 } 4941 return Bundle; 4942 } 4943 4944 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 4945 Value *OpValue) { 4946 if (isa<PHINode>(OpValue)) 4947 return; 4948 4949 ScheduleData *Bundle = getScheduleData(OpValue); 4950 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 4951 assert(!Bundle->IsScheduled && 4952 "Can't cancel bundle which is already scheduled"); 4953 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() && 4954 "tried to unbundle something which is not a bundle"); 4955 4956 // Un-bundle: make single instructions out of the bundle. 4957 ScheduleData *BundleMember = Bundle; 4958 while (BundleMember) { 4959 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 4960 BundleMember->FirstInBundle = BundleMember; 4961 ScheduleData *Next = BundleMember->NextInBundle; 4962 BundleMember->NextInBundle = nullptr; 4963 BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps; 4964 if (BundleMember->UnscheduledDepsInBundle == 0) { 4965 ReadyInsts.insert(BundleMember); 4966 } 4967 BundleMember = Next; 4968 } 4969 } 4970 4971 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 4972 // Allocate a new ScheduleData for the instruction. 4973 if (ChunkPos >= ChunkSize) { 4974 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 4975 ChunkPos = 0; 4976 } 4977 return &(ScheduleDataChunks.back()[ChunkPos++]); 4978 } 4979 4980 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 4981 const InstructionsState &S) { 4982 if (getScheduleData(V, isOneOf(S, V))) 4983 return true; 4984 Instruction *I = dyn_cast<Instruction>(V); 4985 assert(I && "bundle member must be an instruction"); 4986 assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled"); 4987 auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool { 4988 ScheduleData *ISD = getScheduleData(I); 4989 if (!ISD) 4990 return false; 4991 assert(isInSchedulingRegion(ISD) && 4992 "ScheduleData not in scheduling region"); 4993 ScheduleData *SD = allocateScheduleDataChunks(); 4994 SD->Inst = I; 4995 SD->init(SchedulingRegionID, S.OpValue); 4996 ExtraScheduleDataMap[I][S.OpValue] = SD; 4997 return true; 4998 }; 4999 if (CheckSheduleForI(I)) 5000 return true; 5001 if (!ScheduleStart) { 5002 // It's the first instruction in the new region. 5003 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 5004 ScheduleStart = I; 5005 ScheduleEnd = I->getNextNode(); 5006 if (isOneOf(S, I) != I) 5007 CheckSheduleForI(I); 5008 assert(ScheduleEnd && "tried to vectorize a terminator?"); 5009 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 5010 return true; 5011 } 5012 // Search up and down at the same time, because we don't know if the new 5013 // instruction is above or below the existing scheduling region. 5014 BasicBlock::reverse_iterator UpIter = 5015 ++ScheduleStart->getIterator().getReverse(); 5016 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 5017 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 5018 BasicBlock::iterator LowerEnd = BB->end(); 5019 while (true) { 5020 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 5021 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 5022 return false; 5023 } 5024 5025 if (UpIter != UpperEnd) { 5026 if (&*UpIter == I) { 5027 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 5028 ScheduleStart = I; 5029 if (isOneOf(S, I) != I) 5030 CheckSheduleForI(I); 5031 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 5032 << "\n"); 5033 return true; 5034 } 5035 ++UpIter; 5036 } 5037 if (DownIter != LowerEnd) { 5038 if (&*DownIter == I) { 5039 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 5040 nullptr); 5041 ScheduleEnd = I->getNextNode(); 5042 if (isOneOf(S, I) != I) 5043 CheckSheduleForI(I); 5044 assert(ScheduleEnd && "tried to vectorize a terminator?"); 5045 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I 5046 << "\n"); 5047 return true; 5048 } 5049 ++DownIter; 5050 } 5051 assert((UpIter != UpperEnd || DownIter != LowerEnd) && 5052 "instruction not found in block"); 5053 } 5054 return true; 5055 } 5056 5057 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 5058 Instruction *ToI, 5059 ScheduleData *PrevLoadStore, 5060 ScheduleData *NextLoadStore) { 5061 ScheduleData *CurrentLoadStore = PrevLoadStore; 5062 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 5063 ScheduleData *SD = ScheduleDataMap[I]; 5064 if (!SD) { 5065 SD = allocateScheduleDataChunks(); 5066 ScheduleDataMap[I] = SD; 5067 SD->Inst = I; 5068 } 5069 assert(!isInSchedulingRegion(SD) && 5070 "new ScheduleData already in scheduling region"); 5071 SD->init(SchedulingRegionID, I); 5072 5073 if (I->mayReadOrWriteMemory() && 5074 (!isa<IntrinsicInst>(I) || 5075 cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) { 5076 // Update the linked list of memory accessing instructions. 5077 if (CurrentLoadStore) { 5078 CurrentLoadStore->NextLoadStore = SD; 5079 } else { 5080 FirstLoadStoreInRegion = SD; 5081 } 5082 CurrentLoadStore = SD; 5083 } 5084 } 5085 if (NextLoadStore) { 5086 if (CurrentLoadStore) 5087 CurrentLoadStore->NextLoadStore = NextLoadStore; 5088 } else { 5089 LastLoadStoreInRegion = CurrentLoadStore; 5090 } 5091 } 5092 5093 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 5094 bool InsertInReadyList, 5095 BoUpSLP *SLP) { 5096 assert(SD->isSchedulingEntity()); 5097 5098 SmallVector<ScheduleData *, 10> WorkList; 5099 WorkList.push_back(SD); 5100 5101 while (!WorkList.empty()) { 5102 ScheduleData *SD = WorkList.back(); 5103 WorkList.pop_back(); 5104 5105 ScheduleData *BundleMember = SD; 5106 while (BundleMember) { 5107 assert(isInSchedulingRegion(BundleMember)); 5108 if (!BundleMember->hasValidDependencies()) { 5109 5110 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 5111 << "\n"); 5112 BundleMember->Dependencies = 0; 5113 BundleMember->resetUnscheduledDeps(); 5114 5115 // Handle def-use chain dependencies. 5116 if (BundleMember->OpValue != BundleMember->Inst) { 5117 ScheduleData *UseSD = getScheduleData(BundleMember->Inst); 5118 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 5119 BundleMember->Dependencies++; 5120 ScheduleData *DestBundle = UseSD->FirstInBundle; 5121 if (!DestBundle->IsScheduled) 5122 BundleMember->incrementUnscheduledDeps(1); 5123 if (!DestBundle->hasValidDependencies()) 5124 WorkList.push_back(DestBundle); 5125 } 5126 } else { 5127 for (User *U : BundleMember->Inst->users()) { 5128 if (isa<Instruction>(U)) { 5129 ScheduleData *UseSD = getScheduleData(U); 5130 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 5131 BundleMember->Dependencies++; 5132 ScheduleData *DestBundle = UseSD->FirstInBundle; 5133 if (!DestBundle->IsScheduled) 5134 BundleMember->incrementUnscheduledDeps(1); 5135 if (!DestBundle->hasValidDependencies()) 5136 WorkList.push_back(DestBundle); 5137 } 5138 } else { 5139 // I'm not sure if this can ever happen. But we need to be safe. 5140 // This lets the instruction/bundle never be scheduled and 5141 // eventually disable vectorization. 5142 BundleMember->Dependencies++; 5143 BundleMember->incrementUnscheduledDeps(1); 5144 } 5145 } 5146 } 5147 5148 // Handle the memory dependencies. 5149 ScheduleData *DepDest = BundleMember->NextLoadStore; 5150 if (DepDest) { 5151 Instruction *SrcInst = BundleMember->Inst; 5152 MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA); 5153 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 5154 unsigned numAliased = 0; 5155 unsigned DistToSrc = 1; 5156 5157 while (DepDest) { 5158 assert(isInSchedulingRegion(DepDest)); 5159 5160 // We have two limits to reduce the complexity: 5161 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 5162 // SLP->isAliased (which is the expensive part in this loop). 5163 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 5164 // the whole loop (even if the loop is fast, it's quadratic). 5165 // It's important for the loop break condition (see below) to 5166 // check this limit even between two read-only instructions. 5167 if (DistToSrc >= MaxMemDepDistance || 5168 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 5169 (numAliased >= AliasedCheckLimit || 5170 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 5171 5172 // We increment the counter only if the locations are aliased 5173 // (instead of counting all alias checks). This gives a better 5174 // balance between reduced runtime and accurate dependencies. 5175 numAliased++; 5176 5177 DepDest->MemoryDependencies.push_back(BundleMember); 5178 BundleMember->Dependencies++; 5179 ScheduleData *DestBundle = DepDest->FirstInBundle; 5180 if (!DestBundle->IsScheduled) { 5181 BundleMember->incrementUnscheduledDeps(1); 5182 } 5183 if (!DestBundle->hasValidDependencies()) { 5184 WorkList.push_back(DestBundle); 5185 } 5186 } 5187 DepDest = DepDest->NextLoadStore; 5188 5189 // Example, explaining the loop break condition: Let's assume our 5190 // starting instruction is i0 and MaxMemDepDistance = 3. 5191 // 5192 // +--------v--v--v 5193 // i0,i1,i2,i3,i4,i5,i6,i7,i8 5194 // +--------^--^--^ 5195 // 5196 // MaxMemDepDistance let us stop alias-checking at i3 and we add 5197 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 5198 // Previously we already added dependencies from i3 to i6,i7,i8 5199 // (because of MaxMemDepDistance). As we added a dependency from 5200 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 5201 // and we can abort this loop at i6. 5202 if (DistToSrc >= 2 * MaxMemDepDistance) 5203 break; 5204 DistToSrc++; 5205 } 5206 } 5207 } 5208 BundleMember = BundleMember->NextInBundle; 5209 } 5210 if (InsertInReadyList && SD->isReady()) { 5211 ReadyInsts.push_back(SD); 5212 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 5213 << "\n"); 5214 } 5215 } 5216 } 5217 5218 void BoUpSLP::BlockScheduling::resetSchedule() { 5219 assert(ScheduleStart && 5220 "tried to reset schedule on block which has not been scheduled"); 5221 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 5222 doForAllOpcodes(I, [&](ScheduleData *SD) { 5223 assert(isInSchedulingRegion(SD) && 5224 "ScheduleData not in scheduling region"); 5225 SD->IsScheduled = false; 5226 SD->resetUnscheduledDeps(); 5227 }); 5228 } 5229 ReadyInsts.clear(); 5230 } 5231 5232 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 5233 if (!BS->ScheduleStart) 5234 return; 5235 5236 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 5237 5238 BS->resetSchedule(); 5239 5240 // For the real scheduling we use a more sophisticated ready-list: it is 5241 // sorted by the original instruction location. This lets the final schedule 5242 // be as close as possible to the original instruction order. 5243 struct ScheduleDataCompare { 5244 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { 5245 return SD2->SchedulingPriority < SD1->SchedulingPriority; 5246 } 5247 }; 5248 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 5249 5250 // Ensure that all dependency data is updated and fill the ready-list with 5251 // initial instructions. 5252 int Idx = 0; 5253 int NumToSchedule = 0; 5254 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 5255 I = I->getNextNode()) { 5256 BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) { 5257 assert(SD->isPartOfBundle() == 5258 (getTreeEntry(SD->Inst) != nullptr) && 5259 "scheduler and vectorizer bundle mismatch"); 5260 SD->FirstInBundle->SchedulingPriority = Idx++; 5261 if (SD->isSchedulingEntity()) { 5262 BS->calculateDependencies(SD, false, this); 5263 NumToSchedule++; 5264 } 5265 }); 5266 } 5267 BS->initialFillReadyList(ReadyInsts); 5268 5269 Instruction *LastScheduledInst = BS->ScheduleEnd; 5270 5271 // Do the "real" scheduling. 5272 while (!ReadyInsts.empty()) { 5273 ScheduleData *picked = *ReadyInsts.begin(); 5274 ReadyInsts.erase(ReadyInsts.begin()); 5275 5276 // Move the scheduled instruction(s) to their dedicated places, if not 5277 // there yet. 5278 ScheduleData *BundleMember = picked; 5279 while (BundleMember) { 5280 Instruction *pickedInst = BundleMember->Inst; 5281 if (LastScheduledInst->getNextNode() != pickedInst) { 5282 BS->BB->getInstList().remove(pickedInst); 5283 BS->BB->getInstList().insert(LastScheduledInst->getIterator(), 5284 pickedInst); 5285 } 5286 LastScheduledInst = pickedInst; 5287 BundleMember = BundleMember->NextInBundle; 5288 } 5289 5290 BS->schedule(picked, ReadyInsts); 5291 NumToSchedule--; 5292 } 5293 assert(NumToSchedule == 0 && "could not schedule all instructions"); 5294 5295 // Avoid duplicate scheduling of the block. 5296 BS->ScheduleStart = nullptr; 5297 } 5298 5299 unsigned BoUpSLP::getVectorElementSize(Value *V) const { 5300 // If V is a store, just return the width of the stored value without 5301 // traversing the expression tree. This is the common case. 5302 if (auto *Store = dyn_cast<StoreInst>(V)) 5303 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 5304 5305 // If V is not a store, we can traverse the expression tree to find loads 5306 // that feed it. The type of the loaded value may indicate a more suitable 5307 // width than V's type. We want to base the vector element size on the width 5308 // of memory operations where possible. 5309 SmallVector<Instruction *, 16> Worklist; 5310 SmallPtrSet<Instruction *, 16> Visited; 5311 if (auto *I = dyn_cast<Instruction>(V)) 5312 Worklist.push_back(I); 5313 5314 // Traverse the expression tree in bottom-up order looking for loads. If we 5315 // encounter an instruction we don't yet handle, we give up. 5316 auto MaxWidth = 0u; 5317 auto FoundUnknownInst = false; 5318 while (!Worklist.empty() && !FoundUnknownInst) { 5319 auto *I = Worklist.pop_back_val(); 5320 Visited.insert(I); 5321 5322 // We should only be looking at scalar instructions here. If the current 5323 // instruction has a vector type, give up. 5324 auto *Ty = I->getType(); 5325 if (isa<VectorType>(Ty)) 5326 FoundUnknownInst = true; 5327 5328 // If the current instruction is a load, update MaxWidth to reflect the 5329 // width of the loaded value. 5330 else if (isa<LoadInst>(I)) 5331 MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty)); 5332 5333 // Otherwise, we need to visit the operands of the instruction. We only 5334 // handle the interesting cases from buildTree here. If an operand is an 5335 // instruction we haven't yet visited, we add it to the worklist. 5336 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 5337 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) { 5338 for (Use &U : I->operands()) 5339 if (auto *J = dyn_cast<Instruction>(U.get())) 5340 if (!Visited.count(J)) 5341 Worklist.push_back(J); 5342 } 5343 5344 // If we don't yet handle the instruction, give up. 5345 else 5346 FoundUnknownInst = true; 5347 } 5348 5349 // If we didn't encounter a memory access in the expression tree, or if we 5350 // gave up for some reason, just return the width of V. 5351 if (!MaxWidth || FoundUnknownInst) 5352 return DL->getTypeSizeInBits(V->getType()); 5353 5354 // Otherwise, return the maximum width we found. 5355 return MaxWidth; 5356 } 5357 5358 // Determine if a value V in a vectorizable expression Expr can be demoted to a 5359 // smaller type with a truncation. We collect the values that will be demoted 5360 // in ToDemote and additional roots that require investigating in Roots. 5361 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 5362 SmallVectorImpl<Value *> &ToDemote, 5363 SmallVectorImpl<Value *> &Roots) { 5364 // We can always demote constants. 5365 if (isa<Constant>(V)) { 5366 ToDemote.push_back(V); 5367 return true; 5368 } 5369 5370 // If the value is not an instruction in the expression with only one use, it 5371 // cannot be demoted. 5372 auto *I = dyn_cast<Instruction>(V); 5373 if (!I || !I->hasOneUse() || !Expr.count(I)) 5374 return false; 5375 5376 switch (I->getOpcode()) { 5377 5378 // We can always demote truncations and extensions. Since truncations can 5379 // seed additional demotion, we save the truncated value. 5380 case Instruction::Trunc: 5381 Roots.push_back(I->getOperand(0)); 5382 break; 5383 case Instruction::ZExt: 5384 case Instruction::SExt: 5385 break; 5386 5387 // We can demote certain binary operations if we can demote both of their 5388 // operands. 5389 case Instruction::Add: 5390 case Instruction::Sub: 5391 case Instruction::Mul: 5392 case Instruction::And: 5393 case Instruction::Or: 5394 case Instruction::Xor: 5395 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 5396 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 5397 return false; 5398 break; 5399 5400 // We can demote selects if we can demote their true and false values. 5401 case Instruction::Select: { 5402 SelectInst *SI = cast<SelectInst>(I); 5403 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 5404 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 5405 return false; 5406 break; 5407 } 5408 5409 // We can demote phis if we can demote all their incoming operands. Note that 5410 // we don't need to worry about cycles since we ensure single use above. 5411 case Instruction::PHI: { 5412 PHINode *PN = cast<PHINode>(I); 5413 for (Value *IncValue : PN->incoming_values()) 5414 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 5415 return false; 5416 break; 5417 } 5418 5419 // Otherwise, conservatively give up. 5420 default: 5421 return false; 5422 } 5423 5424 // Record the value that we can demote. 5425 ToDemote.push_back(V); 5426 return true; 5427 } 5428 5429 void BoUpSLP::computeMinimumValueSizes() { 5430 // If there are no external uses, the expression tree must be rooted by a 5431 // store. We can't demote in-memory values, so there is nothing to do here. 5432 if (ExternalUses.empty()) 5433 return; 5434 5435 // We only attempt to truncate integer expressions. 5436 auto &TreeRoot = VectorizableTree[0]->Scalars; 5437 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 5438 if (!TreeRootIT) 5439 return; 5440 5441 // If the expression is not rooted by a store, these roots should have 5442 // external uses. We will rely on InstCombine to rewrite the expression in 5443 // the narrower type. However, InstCombine only rewrites single-use values. 5444 // This means that if a tree entry other than a root is used externally, it 5445 // must have multiple uses and InstCombine will not rewrite it. The code 5446 // below ensures that only the roots are used externally. 5447 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 5448 for (auto &EU : ExternalUses) 5449 if (!Expr.erase(EU.Scalar)) 5450 return; 5451 if (!Expr.empty()) 5452 return; 5453 5454 // Collect the scalar values of the vectorizable expression. We will use this 5455 // context to determine which values can be demoted. If we see a truncation, 5456 // we mark it as seeding another demotion. 5457 for (auto &EntryPtr : VectorizableTree) 5458 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 5459 5460 // Ensure the roots of the vectorizable tree don't form a cycle. They must 5461 // have a single external user that is not in the vectorizable tree. 5462 for (auto *Root : TreeRoot) 5463 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 5464 return; 5465 5466 // Conservatively determine if we can actually truncate the roots of the 5467 // expression. Collect the values that can be demoted in ToDemote and 5468 // additional roots that require investigating in Roots. 5469 SmallVector<Value *, 32> ToDemote; 5470 SmallVector<Value *, 4> Roots; 5471 for (auto *Root : TreeRoot) 5472 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 5473 return; 5474 5475 // The maximum bit width required to represent all the values that can be 5476 // demoted without loss of precision. It would be safe to truncate the roots 5477 // of the expression to this width. 5478 auto MaxBitWidth = 8u; 5479 5480 // We first check if all the bits of the roots are demanded. If they're not, 5481 // we can truncate the roots to this narrower type. 5482 for (auto *Root : TreeRoot) { 5483 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 5484 MaxBitWidth = std::max<unsigned>( 5485 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 5486 } 5487 5488 // True if the roots can be zero-extended back to their original type, rather 5489 // than sign-extended. We know that if the leading bits are not demanded, we 5490 // can safely zero-extend. So we initialize IsKnownPositive to True. 5491 bool IsKnownPositive = true; 5492 5493 // If all the bits of the roots are demanded, we can try a little harder to 5494 // compute a narrower type. This can happen, for example, if the roots are 5495 // getelementptr indices. InstCombine promotes these indices to the pointer 5496 // width. Thus, all their bits are technically demanded even though the 5497 // address computation might be vectorized in a smaller type. 5498 // 5499 // We start by looking at each entry that can be demoted. We compute the 5500 // maximum bit width required to store the scalar by using ValueTracking to 5501 // compute the number of high-order bits we can truncate. 5502 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 5503 llvm::all_of(TreeRoot, [](Value *R) { 5504 assert(R->hasOneUse() && "Root should have only one use!"); 5505 return isa<GetElementPtrInst>(R->user_back()); 5506 })) { 5507 MaxBitWidth = 8u; 5508 5509 // Determine if the sign bit of all the roots is known to be zero. If not, 5510 // IsKnownPositive is set to False. 5511 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 5512 KnownBits Known = computeKnownBits(R, *DL); 5513 return Known.isNonNegative(); 5514 }); 5515 5516 // Determine the maximum number of bits required to store the scalar 5517 // values. 5518 for (auto *Scalar : ToDemote) { 5519 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 5520 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 5521 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 5522 } 5523 5524 // If we can't prove that the sign bit is zero, we must add one to the 5525 // maximum bit width to account for the unknown sign bit. This preserves 5526 // the existing sign bit so we can safely sign-extend the root back to the 5527 // original type. Otherwise, if we know the sign bit is zero, we will 5528 // zero-extend the root instead. 5529 // 5530 // FIXME: This is somewhat suboptimal, as there will be cases where adding 5531 // one to the maximum bit width will yield a larger-than-necessary 5532 // type. In general, we need to add an extra bit only if we can't 5533 // prove that the upper bit of the original type is equal to the 5534 // upper bit of the proposed smaller type. If these two bits are the 5535 // same (either zero or one) we know that sign-extending from the 5536 // smaller type will result in the same value. Here, since we can't 5537 // yet prove this, we are just making the proposed smaller type 5538 // larger to ensure correctness. 5539 if (!IsKnownPositive) 5540 ++MaxBitWidth; 5541 } 5542 5543 // Round MaxBitWidth up to the next power-of-two. 5544 if (!isPowerOf2_64(MaxBitWidth)) 5545 MaxBitWidth = NextPowerOf2(MaxBitWidth); 5546 5547 // If the maximum bit width we compute is less than the with of the roots' 5548 // type, we can proceed with the narrowing. Otherwise, do nothing. 5549 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 5550 return; 5551 5552 // If we can truncate the root, we must collect additional values that might 5553 // be demoted as a result. That is, those seeded by truncations we will 5554 // modify. 5555 while (!Roots.empty()) 5556 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 5557 5558 // Finally, map the values we can demote to the maximum bit with we computed. 5559 for (auto *Scalar : ToDemote) 5560 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 5561 } 5562 5563 namespace { 5564 5565 /// The SLPVectorizer Pass. 5566 struct SLPVectorizer : public FunctionPass { 5567 SLPVectorizerPass Impl; 5568 5569 /// Pass identification, replacement for typeid 5570 static char ID; 5571 5572 explicit SLPVectorizer() : FunctionPass(ID) { 5573 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 5574 } 5575 5576 bool doInitialization(Module &M) override { 5577 return false; 5578 } 5579 5580 bool runOnFunction(Function &F) override { 5581 if (skipFunction(F)) 5582 return false; 5583 5584 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 5585 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 5586 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 5587 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 5588 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 5589 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 5590 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 5591 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 5592 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 5593 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 5594 5595 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 5596 } 5597 5598 void getAnalysisUsage(AnalysisUsage &AU) const override { 5599 FunctionPass::getAnalysisUsage(AU); 5600 AU.addRequired<AssumptionCacheTracker>(); 5601 AU.addRequired<ScalarEvolutionWrapperPass>(); 5602 AU.addRequired<AAResultsWrapperPass>(); 5603 AU.addRequired<TargetTransformInfoWrapperPass>(); 5604 AU.addRequired<LoopInfoWrapperPass>(); 5605 AU.addRequired<DominatorTreeWrapperPass>(); 5606 AU.addRequired<DemandedBitsWrapperPass>(); 5607 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 5608 AU.addRequired<InjectTLIMappingsLegacy>(); 5609 AU.addPreserved<LoopInfoWrapperPass>(); 5610 AU.addPreserved<DominatorTreeWrapperPass>(); 5611 AU.addPreserved<AAResultsWrapperPass>(); 5612 AU.addPreserved<GlobalsAAWrapperPass>(); 5613 AU.setPreservesCFG(); 5614 } 5615 }; 5616 5617 } // end anonymous namespace 5618 5619 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 5620 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 5621 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 5622 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 5623 auto *AA = &AM.getResult<AAManager>(F); 5624 auto *LI = &AM.getResult<LoopAnalysis>(F); 5625 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 5626 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 5627 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 5628 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 5629 5630 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 5631 if (!Changed) 5632 return PreservedAnalyses::all(); 5633 5634 PreservedAnalyses PA; 5635 PA.preserveSet<CFGAnalyses>(); 5636 PA.preserve<AAManager>(); 5637 PA.preserve<GlobalsAA>(); 5638 return PA; 5639 } 5640 5641 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 5642 TargetTransformInfo *TTI_, 5643 TargetLibraryInfo *TLI_, AliasAnalysis *AA_, 5644 LoopInfo *LI_, DominatorTree *DT_, 5645 AssumptionCache *AC_, DemandedBits *DB_, 5646 OptimizationRemarkEmitter *ORE_) { 5647 SE = SE_; 5648 TTI = TTI_; 5649 TLI = TLI_; 5650 AA = AA_; 5651 LI = LI_; 5652 DT = DT_; 5653 AC = AC_; 5654 DB = DB_; 5655 DL = &F.getParent()->getDataLayout(); 5656 5657 Stores.clear(); 5658 GEPs.clear(); 5659 bool Changed = false; 5660 5661 // If the target claims to have no vector registers don't attempt 5662 // vectorization. 5663 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) 5664 return false; 5665 5666 // Don't vectorize when the attribute NoImplicitFloat is used. 5667 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 5668 return false; 5669 5670 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 5671 5672 // Use the bottom up slp vectorizer to construct chains that start with 5673 // store instructions. 5674 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 5675 5676 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 5677 // delete instructions. 5678 5679 // Scan the blocks in the function in post order. 5680 for (auto BB : post_order(&F.getEntryBlock())) { 5681 collectSeedInstructions(BB); 5682 5683 // Vectorize trees that end at stores. 5684 if (!Stores.empty()) { 5685 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 5686 << " underlying objects.\n"); 5687 Changed |= vectorizeStoreChains(R); 5688 } 5689 5690 // Vectorize trees that end at reductions. 5691 Changed |= vectorizeChainsInBlock(BB, R); 5692 5693 // Vectorize the index computations of getelementptr instructions. This 5694 // is primarily intended to catch gather-like idioms ending at 5695 // non-consecutive loads. 5696 if (!GEPs.empty()) { 5697 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 5698 << " underlying objects.\n"); 5699 Changed |= vectorizeGEPIndices(BB, R); 5700 } 5701 } 5702 5703 if (Changed) { 5704 R.optimizeGatherSequence(); 5705 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 5706 LLVM_DEBUG(verifyFunction(F)); 5707 } 5708 return Changed; 5709 } 5710 5711 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 5712 unsigned Idx) { 5713 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 5714 << "\n"); 5715 const unsigned Sz = R.getVectorElementSize(Chain[0]); 5716 const unsigned MinVF = R.getMinVecRegSize() / Sz; 5717 unsigned VF = Chain.size(); 5718 5719 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 5720 return false; 5721 5722 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 5723 << "\n"); 5724 5725 R.buildTree(Chain); 5726 Optional<ArrayRef<unsigned>> Order = R.bestOrder(); 5727 // TODO: Handle orders of size less than number of elements in the vector. 5728 if (Order && Order->size() == Chain.size()) { 5729 // TODO: reorder tree nodes without tree rebuilding. 5730 SmallVector<Value *, 4> ReorderedOps(Chain.rbegin(), Chain.rend()); 5731 llvm::transform(*Order, ReorderedOps.begin(), 5732 [Chain](const unsigned Idx) { return Chain[Idx]; }); 5733 R.buildTree(ReorderedOps); 5734 } 5735 if (R.isTreeTinyAndNotFullyVectorizable()) 5736 return false; 5737 5738 R.computeMinimumValueSizes(); 5739 5740 int Cost = R.getTreeCost(); 5741 5742 LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n"); 5743 if (Cost < -SLPCostThreshold) { 5744 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n"); 5745 5746 using namespace ore; 5747 5748 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 5749 cast<StoreInst>(Chain[0])) 5750 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 5751 << " and with tree size " 5752 << NV("TreeSize", R.getTreeSize())); 5753 5754 R.vectorizeTree(); 5755 return true; 5756 } 5757 5758 return false; 5759 } 5760 5761 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 5762 BoUpSLP &R) { 5763 // We may run into multiple chains that merge into a single chain. We mark the 5764 // stores that we vectorized so that we don't visit the same store twice. 5765 BoUpSLP::ValueSet VectorizedStores; 5766 bool Changed = false; 5767 5768 int E = Stores.size(); 5769 SmallBitVector Tails(E, false); 5770 SmallVector<int, 16> ConsecutiveChain(E, E + 1); 5771 int MaxIter = MaxStoreLookup.getValue(); 5772 int IterCnt; 5773 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 5774 &ConsecutiveChain](int K, int Idx) { 5775 if (IterCnt >= MaxIter) 5776 return true; 5777 ++IterCnt; 5778 if (!isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE)) 5779 return false; 5780 5781 Tails.set(Idx); 5782 ConsecutiveChain[K] = Idx; 5783 return true; 5784 }; 5785 // Do a quadratic search on all of the given stores in reverse order and find 5786 // all of the pairs of stores that follow each other. 5787 for (int Idx = E - 1; Idx >= 0; --Idx) { 5788 // If a store has multiple consecutive store candidates, search according 5789 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 5790 // This is because usually pairing with immediate succeeding or preceding 5791 // candidate create the best chance to find slp vectorization opportunity. 5792 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 5793 IterCnt = 0; 5794 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 5795 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 5796 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 5797 break; 5798 } 5799 5800 // For stores that start but don't end a link in the chain: 5801 for (int Cnt = E; Cnt > 0; --Cnt) { 5802 int I = Cnt - 1; 5803 if (ConsecutiveChain[I] == E + 1 || Tails.test(I)) 5804 continue; 5805 // We found a store instr that starts a chain. Now follow the chain and try 5806 // to vectorize it. 5807 BoUpSLP::ValueList Operands; 5808 // Collect the chain into a list. 5809 while (I != E + 1 && !VectorizedStores.count(Stores[I])) { 5810 Operands.push_back(Stores[I]); 5811 // Move to the next value in the chain. 5812 I = ConsecutiveChain[I]; 5813 } 5814 5815 // If a vector register can't hold 1 element, we are done. 5816 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 5817 unsigned EltSize = R.getVectorElementSize(Stores[0]); 5818 if (MaxVecRegSize % EltSize != 0) 5819 continue; 5820 5821 unsigned MaxElts = MaxVecRegSize / EltSize; 5822 // FIXME: Is division-by-2 the correct step? Should we assert that the 5823 // register size is a power-of-2? 5824 unsigned StartIdx = 0; 5825 for (unsigned Size = llvm::PowerOf2Ceil(MaxElts); Size >= 2; Size /= 2) { 5826 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 5827 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 5828 if (!VectorizedStores.count(Slice.front()) && 5829 !VectorizedStores.count(Slice.back()) && 5830 vectorizeStoreChain(Slice, R, Cnt)) { 5831 // Mark the vectorized stores so that we don't vectorize them again. 5832 VectorizedStores.insert(Slice.begin(), Slice.end()); 5833 Changed = true; 5834 // If we vectorized initial block, no need to try to vectorize it 5835 // again. 5836 if (Cnt == StartIdx) 5837 StartIdx += Size; 5838 Cnt += Size; 5839 continue; 5840 } 5841 ++Cnt; 5842 } 5843 // Check if the whole array was vectorized already - exit. 5844 if (StartIdx >= Operands.size()) 5845 break; 5846 } 5847 } 5848 5849 return Changed; 5850 } 5851 5852 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 5853 // Initialize the collections. We will make a single pass over the block. 5854 Stores.clear(); 5855 GEPs.clear(); 5856 5857 // Visit the store and getelementptr instructions in BB and organize them in 5858 // Stores and GEPs according to the underlying objects of their pointer 5859 // operands. 5860 for (Instruction &I : *BB) { 5861 // Ignore store instructions that are volatile or have a pointer operand 5862 // that doesn't point to a scalar type. 5863 if (auto *SI = dyn_cast<StoreInst>(&I)) { 5864 if (!SI->isSimple()) 5865 continue; 5866 if (!isValidElementType(SI->getValueOperand()->getType())) 5867 continue; 5868 Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI); 5869 } 5870 5871 // Ignore getelementptr instructions that have more than one index, a 5872 // constant index, or a pointer operand that doesn't point to a scalar 5873 // type. 5874 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 5875 auto Idx = GEP->idx_begin()->get(); 5876 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 5877 continue; 5878 if (!isValidElementType(Idx->getType())) 5879 continue; 5880 if (GEP->getType()->isVectorTy()) 5881 continue; 5882 GEPs[GEP->getPointerOperand()].push_back(GEP); 5883 } 5884 } 5885 } 5886 5887 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 5888 if (!A || !B) 5889 return false; 5890 Value *VL[] = { A, B }; 5891 return tryToVectorizeList(VL, R, /*UserCost=*/0, true); 5892 } 5893 5894 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 5895 int UserCost, bool AllowReorder) { 5896 if (VL.size() < 2) 5897 return false; 5898 5899 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 5900 << VL.size() << ".\n"); 5901 5902 // Check that all of the parts are instructions of the same type, 5903 // we permit an alternate opcode via InstructionsState. 5904 InstructionsState S = getSameOpcode(VL); 5905 if (!S.getOpcode()) 5906 return false; 5907 5908 Instruction *I0 = cast<Instruction>(S.OpValue); 5909 // Make sure invalid types (including vector type) are rejected before 5910 // determining vectorization factor for scalar instructions. 5911 for (Value *V : VL) { 5912 Type *Ty = V->getType(); 5913 if (!isValidElementType(Ty)) { 5914 // NOTE: the following will give user internal llvm type name, which may 5915 // not be useful. 5916 R.getORE()->emit([&]() { 5917 std::string type_str; 5918 llvm::raw_string_ostream rso(type_str); 5919 Ty->print(rso); 5920 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 5921 << "Cannot SLP vectorize list: type " 5922 << rso.str() + " is unsupported by vectorizer"; 5923 }); 5924 return false; 5925 } 5926 } 5927 5928 unsigned Sz = R.getVectorElementSize(I0); 5929 unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz); 5930 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 5931 if (MaxVF < 2) { 5932 R.getORE()->emit([&]() { 5933 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 5934 << "Cannot SLP vectorize list: vectorization factor " 5935 << "less than 2 is not supported"; 5936 }); 5937 return false; 5938 } 5939 5940 bool Changed = false; 5941 bool CandidateFound = false; 5942 int MinCost = SLPCostThreshold; 5943 5944 unsigned NextInst = 0, MaxInst = VL.size(); 5945 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 5946 // No actual vectorization should happen, if number of parts is the same as 5947 // provided vectorization factor (i.e. the scalar type is used for vector 5948 // code during codegen). 5949 auto *VecTy = VectorType::get(VL[0]->getType(), VF); 5950 if (TTI->getNumberOfParts(VecTy) == VF) 5951 continue; 5952 for (unsigned I = NextInst; I < MaxInst; ++I) { 5953 unsigned OpsWidth = 0; 5954 5955 if (I + VF > MaxInst) 5956 OpsWidth = MaxInst - I; 5957 else 5958 OpsWidth = VF; 5959 5960 if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2) 5961 break; 5962 5963 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 5964 // Check that a previous iteration of this loop did not delete the Value. 5965 if (llvm::any_of(Ops, [&R](Value *V) { 5966 auto *I = dyn_cast<Instruction>(V); 5967 return I && R.isDeleted(I); 5968 })) 5969 continue; 5970 5971 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 5972 << "\n"); 5973 5974 R.buildTree(Ops); 5975 Optional<ArrayRef<unsigned>> Order = R.bestOrder(); 5976 // TODO: check if we can allow reordering for more cases. 5977 if (AllowReorder && Order) { 5978 // TODO: reorder tree nodes without tree rebuilding. 5979 // Conceptually, there is nothing actually preventing us from trying to 5980 // reorder a larger list. In fact, we do exactly this when vectorizing 5981 // reductions. However, at this point, we only expect to get here when 5982 // there are exactly two operations. 5983 assert(Ops.size() == 2); 5984 Value *ReorderedOps[] = {Ops[1], Ops[0]}; 5985 R.buildTree(ReorderedOps, None); 5986 } 5987 if (R.isTreeTinyAndNotFullyVectorizable()) 5988 continue; 5989 5990 R.computeMinimumValueSizes(); 5991 int Cost = R.getTreeCost() - UserCost; 5992 CandidateFound = true; 5993 MinCost = std::min(MinCost, Cost); 5994 5995 if (Cost < -SLPCostThreshold) { 5996 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 5997 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 5998 cast<Instruction>(Ops[0])) 5999 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 6000 << " and with tree size " 6001 << ore::NV("TreeSize", R.getTreeSize())); 6002 6003 R.vectorizeTree(); 6004 // Move to the next bundle. 6005 I += VF - 1; 6006 NextInst = I + 1; 6007 Changed = true; 6008 } 6009 } 6010 } 6011 6012 if (!Changed && CandidateFound) { 6013 R.getORE()->emit([&]() { 6014 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 6015 << "List vectorization was possible but not beneficial with cost " 6016 << ore::NV("Cost", MinCost) << " >= " 6017 << ore::NV("Treshold", -SLPCostThreshold); 6018 }); 6019 } else if (!Changed) { 6020 R.getORE()->emit([&]() { 6021 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 6022 << "Cannot SLP vectorize list: vectorization was impossible" 6023 << " with available vectorization factors"; 6024 }); 6025 } 6026 return Changed; 6027 } 6028 6029 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 6030 if (!I) 6031 return false; 6032 6033 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) 6034 return false; 6035 6036 Value *P = I->getParent(); 6037 6038 // Vectorize in current basic block only. 6039 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 6040 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 6041 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 6042 return false; 6043 6044 // Try to vectorize V. 6045 if (tryToVectorizePair(Op0, Op1, R)) 6046 return true; 6047 6048 auto *A = dyn_cast<BinaryOperator>(Op0); 6049 auto *B = dyn_cast<BinaryOperator>(Op1); 6050 // Try to skip B. 6051 if (B && B->hasOneUse()) { 6052 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 6053 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 6054 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R)) 6055 return true; 6056 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R)) 6057 return true; 6058 } 6059 6060 // Try to skip A. 6061 if (A && A->hasOneUse()) { 6062 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 6063 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 6064 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R)) 6065 return true; 6066 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R)) 6067 return true; 6068 } 6069 return false; 6070 } 6071 6072 /// Generate a shuffle mask to be used in a reduction tree. 6073 /// 6074 /// \param VecLen The length of the vector to be reduced. 6075 /// \param NumEltsToRdx The number of elements that should be reduced in the 6076 /// vector. 6077 /// \param IsPairwise Whether the reduction is a pairwise or splitting 6078 /// reduction. A pairwise reduction will generate a mask of 6079 /// <0,2,...> or <1,3,..> while a splitting reduction will generate 6080 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2. 6081 /// \param IsLeft True will generate a mask of even elements, odd otherwise. 6082 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx, 6083 bool IsPairwise, bool IsLeft, 6084 IRBuilder<> &Builder) { 6085 assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask"); 6086 6087 SmallVector<Constant *, 32> ShuffleMask( 6088 VecLen, UndefValue::get(Builder.getInt32Ty())); 6089 6090 if (IsPairwise) 6091 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right). 6092 for (unsigned i = 0; i != NumEltsToRdx; ++i) 6093 ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft); 6094 else 6095 // Move the upper half of the vector to the lower half. 6096 for (unsigned i = 0; i != NumEltsToRdx; ++i) 6097 ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i); 6098 6099 return ConstantVector::get(ShuffleMask); 6100 } 6101 6102 namespace { 6103 6104 /// Model horizontal reductions. 6105 /// 6106 /// A horizontal reduction is a tree of reduction operations (currently add and 6107 /// fadd) that has operations that can be put into a vector as its leaf. 6108 /// For example, this tree: 6109 /// 6110 /// mul mul mul mul 6111 /// \ / \ / 6112 /// + + 6113 /// \ / 6114 /// + 6115 /// This tree has "mul" as its reduced values and "+" as its reduction 6116 /// operations. A reduction might be feeding into a store or a binary operation 6117 /// feeding a phi. 6118 /// ... 6119 /// \ / 6120 /// + 6121 /// | 6122 /// phi += 6123 /// 6124 /// Or: 6125 /// ... 6126 /// \ / 6127 /// + 6128 /// | 6129 /// *p = 6130 /// 6131 class HorizontalReduction { 6132 using ReductionOpsType = SmallVector<Value *, 16>; 6133 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 6134 ReductionOpsListType ReductionOps; 6135 SmallVector<Value *, 32> ReducedVals; 6136 // Use map vector to make stable output. 6137 MapVector<Instruction *, Value *> ExtraArgs; 6138 6139 /// Kind of the reduction data. 6140 enum ReductionKind { 6141 RK_None, /// Not a reduction. 6142 RK_Arithmetic, /// Binary reduction data. 6143 RK_Min, /// Minimum reduction data. 6144 RK_UMin, /// Unsigned minimum reduction data. 6145 RK_Max, /// Maximum reduction data. 6146 RK_UMax, /// Unsigned maximum reduction data. 6147 }; 6148 6149 /// Contains info about operation, like its opcode, left and right operands. 6150 class OperationData { 6151 /// Opcode of the instruction. 6152 unsigned Opcode = 0; 6153 6154 /// Left operand of the reduction operation. 6155 Value *LHS = nullptr; 6156 6157 /// Right operand of the reduction operation. 6158 Value *RHS = nullptr; 6159 6160 /// Kind of the reduction operation. 6161 ReductionKind Kind = RK_None; 6162 6163 /// True if float point min/max reduction has no NaNs. 6164 bool NoNaN = false; 6165 6166 /// Checks if the reduction operation can be vectorized. 6167 bool isVectorizable() const { 6168 return LHS && RHS && 6169 // We currently only support add/mul/logical && min/max reductions. 6170 ((Kind == RK_Arithmetic && 6171 (Opcode == Instruction::Add || Opcode == Instruction::FAdd || 6172 Opcode == Instruction::Mul || Opcode == Instruction::FMul || 6173 Opcode == Instruction::And || Opcode == Instruction::Or || 6174 Opcode == Instruction::Xor)) || 6175 ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && 6176 (Kind == RK_Min || Kind == RK_Max)) || 6177 (Opcode == Instruction::ICmp && 6178 (Kind == RK_UMin || Kind == RK_UMax))); 6179 } 6180 6181 /// Creates reduction operation with the current opcode. 6182 Value *createOp(IRBuilder<> &Builder, const Twine &Name) const { 6183 assert(isVectorizable() && 6184 "Expected add|fadd or min/max reduction operation."); 6185 Value *Cmp = nullptr; 6186 switch (Kind) { 6187 case RK_Arithmetic: 6188 return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS, 6189 Name); 6190 case RK_Min: 6191 Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS) 6192 : Builder.CreateFCmpOLT(LHS, RHS); 6193 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 6194 case RK_Max: 6195 Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS) 6196 : Builder.CreateFCmpOGT(LHS, RHS); 6197 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 6198 case RK_UMin: 6199 assert(Opcode == Instruction::ICmp && "Expected integer types."); 6200 Cmp = Builder.CreateICmpULT(LHS, RHS); 6201 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 6202 case RK_UMax: 6203 assert(Opcode == Instruction::ICmp && "Expected integer types."); 6204 Cmp = Builder.CreateICmpUGT(LHS, RHS); 6205 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 6206 case RK_None: 6207 break; 6208 } 6209 llvm_unreachable("Unknown reduction operation."); 6210 } 6211 6212 public: 6213 explicit OperationData() = default; 6214 6215 /// Construction for reduced values. They are identified by opcode only and 6216 /// don't have associated LHS/RHS values. 6217 explicit OperationData(Value *V) { 6218 if (auto *I = dyn_cast<Instruction>(V)) 6219 Opcode = I->getOpcode(); 6220 } 6221 6222 /// Constructor for reduction operations with opcode and its left and 6223 /// right operands. 6224 OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind, 6225 bool NoNaN = false) 6226 : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) { 6227 assert(Kind != RK_None && "One of the reduction operations is expected."); 6228 } 6229 6230 explicit operator bool() const { return Opcode; } 6231 6232 /// Return true if this operation is any kind of minimum or maximum. 6233 bool isMinMax() const { 6234 switch (Kind) { 6235 case RK_Arithmetic: 6236 return false; 6237 case RK_Min: 6238 case RK_Max: 6239 case RK_UMin: 6240 case RK_UMax: 6241 return true; 6242 case RK_None: 6243 break; 6244 } 6245 llvm_unreachable("Reduction kind is not set"); 6246 } 6247 6248 /// Get the index of the first operand. 6249 unsigned getFirstOperandIndex() const { 6250 assert(!!*this && "The opcode is not set."); 6251 // We allow calling this before 'Kind' is set, so handle that specially. 6252 if (Kind == RK_None) 6253 return 0; 6254 return isMinMax() ? 1 : 0; 6255 } 6256 6257 /// Total number of operands in the reduction operation. 6258 unsigned getNumberOfOperands() const { 6259 assert(Kind != RK_None && !!*this && LHS && RHS && 6260 "Expected reduction operation."); 6261 return isMinMax() ? 3 : 2; 6262 } 6263 6264 /// Checks if the operation has the same parent as \p P. 6265 bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const { 6266 assert(Kind != RK_None && !!*this && LHS && RHS && 6267 "Expected reduction operation."); 6268 if (!IsRedOp) 6269 return I->getParent() == P; 6270 if (isMinMax()) { 6271 // SelectInst must be used twice while the condition op must have single 6272 // use only. 6273 auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition()); 6274 return I->getParent() == P && Cmp && Cmp->getParent() == P; 6275 } 6276 // Arithmetic reduction operation must be used once only. 6277 return I->getParent() == P; 6278 } 6279 6280 /// Expected number of uses for reduction operations/reduced values. 6281 bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const { 6282 assert(Kind != RK_None && !!*this && LHS && RHS && 6283 "Expected reduction operation."); 6284 if (isMinMax()) 6285 return I->hasNUses(2) && 6286 (!IsReductionOp || 6287 cast<SelectInst>(I)->getCondition()->hasOneUse()); 6288 return I->hasOneUse(); 6289 } 6290 6291 /// Initializes the list of reduction operations. 6292 void initReductionOps(ReductionOpsListType &ReductionOps) { 6293 assert(Kind != RK_None && !!*this && LHS && RHS && 6294 "Expected reduction operation."); 6295 if (isMinMax()) 6296 ReductionOps.assign(2, ReductionOpsType()); 6297 else 6298 ReductionOps.assign(1, ReductionOpsType()); 6299 } 6300 6301 /// Add all reduction operations for the reduction instruction \p I. 6302 void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) { 6303 assert(Kind != RK_None && !!*this && LHS && RHS && 6304 "Expected reduction operation."); 6305 if (isMinMax()) { 6306 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 6307 ReductionOps[1].emplace_back(I); 6308 } else { 6309 ReductionOps[0].emplace_back(I); 6310 } 6311 } 6312 6313 /// Checks if instruction is associative and can be vectorized. 6314 bool isAssociative(Instruction *I) const { 6315 assert(Kind != RK_None && *this && LHS && RHS && 6316 "Expected reduction operation."); 6317 switch (Kind) { 6318 case RK_Arithmetic: 6319 return I->isAssociative(); 6320 case RK_Min: 6321 case RK_Max: 6322 return Opcode == Instruction::ICmp || 6323 cast<Instruction>(I->getOperand(0))->isFast(); 6324 case RK_UMin: 6325 case RK_UMax: 6326 assert(Opcode == Instruction::ICmp && 6327 "Only integer compare operation is expected."); 6328 return true; 6329 case RK_None: 6330 break; 6331 } 6332 llvm_unreachable("Reduction kind is not set"); 6333 } 6334 6335 /// Checks if the reduction operation can be vectorized. 6336 bool isVectorizable(Instruction *I) const { 6337 return isVectorizable() && isAssociative(I); 6338 } 6339 6340 /// Checks if two operation data are both a reduction op or both a reduced 6341 /// value. 6342 bool operator==(const OperationData &OD) const { 6343 assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) && 6344 "One of the comparing operations is incorrect."); 6345 return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode); 6346 } 6347 bool operator!=(const OperationData &OD) const { return !(*this == OD); } 6348 void clear() { 6349 Opcode = 0; 6350 LHS = nullptr; 6351 RHS = nullptr; 6352 Kind = RK_None; 6353 NoNaN = false; 6354 } 6355 6356 /// Get the opcode of the reduction operation. 6357 unsigned getOpcode() const { 6358 assert(isVectorizable() && "Expected vectorizable operation."); 6359 return Opcode; 6360 } 6361 6362 /// Get kind of reduction data. 6363 ReductionKind getKind() const { return Kind; } 6364 Value *getLHS() const { return LHS; } 6365 Value *getRHS() const { return RHS; } 6366 Type *getConditionType() const { 6367 return isMinMax() ? CmpInst::makeCmpResultType(LHS->getType()) : nullptr; 6368 } 6369 6370 /// Creates reduction operation with the current opcode with the IR flags 6371 /// from \p ReductionOps. 6372 Value *createOp(IRBuilder<> &Builder, const Twine &Name, 6373 const ReductionOpsListType &ReductionOps) const { 6374 assert(isVectorizable() && 6375 "Expected add|fadd or min/max reduction operation."); 6376 auto *Op = createOp(Builder, Name); 6377 switch (Kind) { 6378 case RK_Arithmetic: 6379 propagateIRFlags(Op, ReductionOps[0]); 6380 return Op; 6381 case RK_Min: 6382 case RK_Max: 6383 case RK_UMin: 6384 case RK_UMax: 6385 if (auto *SI = dyn_cast<SelectInst>(Op)) 6386 propagateIRFlags(SI->getCondition(), ReductionOps[0]); 6387 propagateIRFlags(Op, ReductionOps[1]); 6388 return Op; 6389 case RK_None: 6390 break; 6391 } 6392 llvm_unreachable("Unknown reduction operation."); 6393 } 6394 /// Creates reduction operation with the current opcode with the IR flags 6395 /// from \p I. 6396 Value *createOp(IRBuilder<> &Builder, const Twine &Name, 6397 Instruction *I) const { 6398 assert(isVectorizable() && 6399 "Expected add|fadd or min/max reduction operation."); 6400 auto *Op = createOp(Builder, Name); 6401 switch (Kind) { 6402 case RK_Arithmetic: 6403 propagateIRFlags(Op, I); 6404 return Op; 6405 case RK_Min: 6406 case RK_Max: 6407 case RK_UMin: 6408 case RK_UMax: 6409 if (auto *SI = dyn_cast<SelectInst>(Op)) { 6410 propagateIRFlags(SI->getCondition(), 6411 cast<SelectInst>(I)->getCondition()); 6412 } 6413 propagateIRFlags(Op, I); 6414 return Op; 6415 case RK_None: 6416 break; 6417 } 6418 llvm_unreachable("Unknown reduction operation."); 6419 } 6420 6421 TargetTransformInfo::ReductionFlags getFlags() const { 6422 TargetTransformInfo::ReductionFlags Flags; 6423 Flags.NoNaN = NoNaN; 6424 switch (Kind) { 6425 case RK_Arithmetic: 6426 break; 6427 case RK_Min: 6428 Flags.IsSigned = Opcode == Instruction::ICmp; 6429 Flags.IsMaxOp = false; 6430 break; 6431 case RK_Max: 6432 Flags.IsSigned = Opcode == Instruction::ICmp; 6433 Flags.IsMaxOp = true; 6434 break; 6435 case RK_UMin: 6436 Flags.IsSigned = false; 6437 Flags.IsMaxOp = false; 6438 break; 6439 case RK_UMax: 6440 Flags.IsSigned = false; 6441 Flags.IsMaxOp = true; 6442 break; 6443 case RK_None: 6444 llvm_unreachable("Reduction kind is not set"); 6445 } 6446 return Flags; 6447 } 6448 }; 6449 6450 WeakTrackingVH ReductionRoot; 6451 6452 /// The operation data of the reduction operation. 6453 OperationData ReductionData; 6454 6455 /// The operation data of the values we perform a reduction on. 6456 OperationData ReducedValueData; 6457 6458 /// Should we model this reduction as a pairwise reduction tree or a tree that 6459 /// splits the vector in halves and adds those halves. 6460 bool IsPairwiseReduction = false; 6461 6462 /// Checks if the ParentStackElem.first should be marked as a reduction 6463 /// operation with an extra argument or as extra argument itself. 6464 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem, 6465 Value *ExtraArg) { 6466 if (ExtraArgs.count(ParentStackElem.first)) { 6467 ExtraArgs[ParentStackElem.first] = nullptr; 6468 // We ran into something like: 6469 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg. 6470 // The whole ParentStackElem.first should be considered as an extra value 6471 // in this case. 6472 // Do not perform analysis of remaining operands of ParentStackElem.first 6473 // instruction, this whole instruction is an extra argument. 6474 ParentStackElem.second = ParentStackElem.first->getNumOperands(); 6475 } else { 6476 // We ran into something like: 6477 // ParentStackElem.first += ... + ExtraArg + ... 6478 ExtraArgs[ParentStackElem.first] = ExtraArg; 6479 } 6480 } 6481 6482 static OperationData getOperationData(Value *V) { 6483 if (!V) 6484 return OperationData(); 6485 6486 Value *LHS; 6487 Value *RHS; 6488 if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) { 6489 return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS, 6490 RK_Arithmetic); 6491 } 6492 if (auto *Select = dyn_cast<SelectInst>(V)) { 6493 // Look for a min/max pattern. 6494 if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) { 6495 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin); 6496 } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) { 6497 return OperationData(Instruction::ICmp, LHS, RHS, RK_Min); 6498 } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) || 6499 m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) { 6500 return OperationData( 6501 Instruction::FCmp, LHS, RHS, RK_Min, 6502 cast<Instruction>(Select->getCondition())->hasNoNaNs()); 6503 } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) { 6504 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax); 6505 } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) { 6506 return OperationData(Instruction::ICmp, LHS, RHS, RK_Max); 6507 } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) || 6508 m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) { 6509 return OperationData( 6510 Instruction::FCmp, LHS, RHS, RK_Max, 6511 cast<Instruction>(Select->getCondition())->hasNoNaNs()); 6512 } else { 6513 // Try harder: look for min/max pattern based on instructions producing 6514 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 6515 // During the intermediate stages of SLP, it's very common to have 6516 // pattern like this (since optimizeGatherSequence is run only once 6517 // at the end): 6518 // %1 = extractelement <2 x i32> %a, i32 0 6519 // %2 = extractelement <2 x i32> %a, i32 1 6520 // %cond = icmp sgt i32 %1, %2 6521 // %3 = extractelement <2 x i32> %a, i32 0 6522 // %4 = extractelement <2 x i32> %a, i32 1 6523 // %select = select i1 %cond, i32 %3, i32 %4 6524 CmpInst::Predicate Pred; 6525 Instruction *L1; 6526 Instruction *L2; 6527 6528 LHS = Select->getTrueValue(); 6529 RHS = Select->getFalseValue(); 6530 Value *Cond = Select->getCondition(); 6531 6532 // TODO: Support inverse predicates. 6533 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 6534 if (!isa<ExtractElementInst>(RHS) || 6535 !L2->isIdenticalTo(cast<Instruction>(RHS))) 6536 return OperationData(V); 6537 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 6538 if (!isa<ExtractElementInst>(LHS) || 6539 !L1->isIdenticalTo(cast<Instruction>(LHS))) 6540 return OperationData(V); 6541 } else { 6542 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 6543 return OperationData(V); 6544 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 6545 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 6546 !L2->isIdenticalTo(cast<Instruction>(RHS))) 6547 return OperationData(V); 6548 } 6549 switch (Pred) { 6550 default: 6551 return OperationData(V); 6552 6553 case CmpInst::ICMP_ULT: 6554 case CmpInst::ICMP_ULE: 6555 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin); 6556 6557 case CmpInst::ICMP_SLT: 6558 case CmpInst::ICMP_SLE: 6559 return OperationData(Instruction::ICmp, LHS, RHS, RK_Min); 6560 6561 case CmpInst::FCMP_OLT: 6562 case CmpInst::FCMP_OLE: 6563 case CmpInst::FCMP_ULT: 6564 case CmpInst::FCMP_ULE: 6565 return OperationData(Instruction::FCmp, LHS, RHS, RK_Min, 6566 cast<Instruction>(Cond)->hasNoNaNs()); 6567 6568 case CmpInst::ICMP_UGT: 6569 case CmpInst::ICMP_UGE: 6570 return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax); 6571 6572 case CmpInst::ICMP_SGT: 6573 case CmpInst::ICMP_SGE: 6574 return OperationData(Instruction::ICmp, LHS, RHS, RK_Max); 6575 6576 case CmpInst::FCMP_OGT: 6577 case CmpInst::FCMP_OGE: 6578 case CmpInst::FCMP_UGT: 6579 case CmpInst::FCMP_UGE: 6580 return OperationData(Instruction::FCmp, LHS, RHS, RK_Max, 6581 cast<Instruction>(Cond)->hasNoNaNs()); 6582 } 6583 } 6584 } 6585 return OperationData(V); 6586 } 6587 6588 public: 6589 HorizontalReduction() = default; 6590 6591 /// Try to find a reduction tree. 6592 bool matchAssociativeReduction(PHINode *Phi, Instruction *B) { 6593 assert((!Phi || is_contained(Phi->operands(), B)) && 6594 "Thi phi needs to use the binary operator"); 6595 6596 ReductionData = getOperationData(B); 6597 6598 // We could have a initial reductions that is not an add. 6599 // r *= v1 + v2 + v3 + v4 6600 // In such a case start looking for a tree rooted in the first '+'. 6601 if (Phi) { 6602 if (ReductionData.getLHS() == Phi) { 6603 Phi = nullptr; 6604 B = dyn_cast<Instruction>(ReductionData.getRHS()); 6605 ReductionData = getOperationData(B); 6606 } else if (ReductionData.getRHS() == Phi) { 6607 Phi = nullptr; 6608 B = dyn_cast<Instruction>(ReductionData.getLHS()); 6609 ReductionData = getOperationData(B); 6610 } 6611 } 6612 6613 if (!ReductionData.isVectorizable(B)) 6614 return false; 6615 6616 Type *Ty = B->getType(); 6617 if (!isValidElementType(Ty)) 6618 return false; 6619 if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy()) 6620 return false; 6621 6622 ReducedValueData.clear(); 6623 ReductionRoot = B; 6624 6625 // Post order traverse the reduction tree starting at B. We only handle true 6626 // trees containing only binary operators. 6627 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack; 6628 Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex())); 6629 ReductionData.initReductionOps(ReductionOps); 6630 while (!Stack.empty()) { 6631 Instruction *TreeN = Stack.back().first; 6632 unsigned EdgeToVist = Stack.back().second++; 6633 OperationData OpData = getOperationData(TreeN); 6634 bool IsReducedValue = OpData != ReductionData; 6635 6636 // Postorder vist. 6637 if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) { 6638 if (IsReducedValue) 6639 ReducedVals.push_back(TreeN); 6640 else { 6641 auto I = ExtraArgs.find(TreeN); 6642 if (I != ExtraArgs.end() && !I->second) { 6643 // Check if TreeN is an extra argument of its parent operation. 6644 if (Stack.size() <= 1) { 6645 // TreeN can't be an extra argument as it is a root reduction 6646 // operation. 6647 return false; 6648 } 6649 // Yes, TreeN is an extra argument, do not add it to a list of 6650 // reduction operations. 6651 // Stack[Stack.size() - 2] always points to the parent operation. 6652 markExtraArg(Stack[Stack.size() - 2], TreeN); 6653 ExtraArgs.erase(TreeN); 6654 } else 6655 ReductionData.addReductionOps(TreeN, ReductionOps); 6656 } 6657 // Retract. 6658 Stack.pop_back(); 6659 continue; 6660 } 6661 6662 // Visit left or right. 6663 Value *NextV = TreeN->getOperand(EdgeToVist); 6664 if (NextV != Phi) { 6665 auto *I = dyn_cast<Instruction>(NextV); 6666 OpData = getOperationData(I); 6667 // Continue analysis if the next operand is a reduction operation or 6668 // (possibly) a reduced value. If the reduced value opcode is not set, 6669 // the first met operation != reduction operation is considered as the 6670 // reduced value class. 6671 if (I && (!ReducedValueData || OpData == ReducedValueData || 6672 OpData == ReductionData)) { 6673 const bool IsReductionOperation = OpData == ReductionData; 6674 // Only handle trees in the current basic block. 6675 if (!ReductionData.hasSameParent(I, B->getParent(), 6676 IsReductionOperation)) { 6677 // I is an extra argument for TreeN (its parent operation). 6678 markExtraArg(Stack.back(), I); 6679 continue; 6680 } 6681 6682 // Each tree node needs to have minimal number of users except for the 6683 // ultimate reduction. 6684 if (!ReductionData.hasRequiredNumberOfUses(I, 6685 OpData == ReductionData) && 6686 I != B) { 6687 // I is an extra argument for TreeN (its parent operation). 6688 markExtraArg(Stack.back(), I); 6689 continue; 6690 } 6691 6692 if (IsReductionOperation) { 6693 // We need to be able to reassociate the reduction operations. 6694 if (!OpData.isAssociative(I)) { 6695 // I is an extra argument for TreeN (its parent operation). 6696 markExtraArg(Stack.back(), I); 6697 continue; 6698 } 6699 } else if (ReducedValueData && 6700 ReducedValueData != OpData) { 6701 // Make sure that the opcodes of the operations that we are going to 6702 // reduce match. 6703 // I is an extra argument for TreeN (its parent operation). 6704 markExtraArg(Stack.back(), I); 6705 continue; 6706 } else if (!ReducedValueData) 6707 ReducedValueData = OpData; 6708 6709 Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex())); 6710 continue; 6711 } 6712 } 6713 // NextV is an extra argument for TreeN (its parent operation). 6714 markExtraArg(Stack.back(), NextV); 6715 } 6716 return true; 6717 } 6718 6719 /// Attempt to vectorize the tree found by 6720 /// matchAssociativeReduction. 6721 bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 6722 if (ReducedVals.empty()) 6723 return false; 6724 6725 // If there is a sufficient number of reduction values, reduce 6726 // to a nearby power-of-2. Can safely generate oversized 6727 // vectors and rely on the backend to split them to legal sizes. 6728 unsigned NumReducedVals = ReducedVals.size(); 6729 if (NumReducedVals < 4) 6730 return false; 6731 6732 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals); 6733 6734 Value *VectorizedTree = nullptr; 6735 6736 // FIXME: Fast-math-flags should be set based on the instructions in the 6737 // reduction (not all of 'fast' are required). 6738 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 6739 FastMathFlags Unsafe; 6740 Unsafe.setFast(); 6741 Builder.setFastMathFlags(Unsafe); 6742 unsigned i = 0; 6743 6744 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 6745 // The same extra argument may be used several time, so log each attempt 6746 // to use it. 6747 for (auto &Pair : ExtraArgs) { 6748 assert(Pair.first && "DebugLoc must be set."); 6749 ExternallyUsedValues[Pair.second].push_back(Pair.first); 6750 } 6751 6752 // The compare instruction of a min/max is the insertion point for new 6753 // instructions and may be replaced with a new compare instruction. 6754 auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 6755 assert(isa<SelectInst>(RdxRootInst) && 6756 "Expected min/max reduction to have select root instruction"); 6757 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 6758 assert(isa<Instruction>(ScalarCond) && 6759 "Expected min/max reduction to have compare condition"); 6760 return cast<Instruction>(ScalarCond); 6761 }; 6762 6763 // The reduction root is used as the insertion point for new instructions, 6764 // so set it as externally used to prevent it from being deleted. 6765 ExternallyUsedValues[ReductionRoot]; 6766 SmallVector<Value *, 16> IgnoreList; 6767 for (auto &V : ReductionOps) 6768 IgnoreList.append(V.begin(), V.end()); 6769 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) { 6770 auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth); 6771 V.buildTree(VL, ExternallyUsedValues, IgnoreList); 6772 Optional<ArrayRef<unsigned>> Order = V.bestOrder(); 6773 // TODO: Handle orders of size less than number of elements in the vector. 6774 if (Order && Order->size() == VL.size()) { 6775 // TODO: reorder tree nodes without tree rebuilding. 6776 SmallVector<Value *, 4> ReorderedOps(VL.size()); 6777 llvm::transform(*Order, ReorderedOps.begin(), 6778 [VL](const unsigned Idx) { return VL[Idx]; }); 6779 V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList); 6780 } 6781 if (V.isTreeTinyAndNotFullyVectorizable()) 6782 break; 6783 if (V.isLoadCombineReductionCandidate(ReductionData.getOpcode())) 6784 break; 6785 6786 V.computeMinimumValueSizes(); 6787 6788 // Estimate cost. 6789 int TreeCost = V.getTreeCost(); 6790 int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth); 6791 int Cost = TreeCost + ReductionCost; 6792 if (Cost >= -SLPCostThreshold) { 6793 V.getORE()->emit([&]() { 6794 return OptimizationRemarkMissed( 6795 SV_NAME, "HorSLPNotBeneficial", cast<Instruction>(VL[0])) 6796 << "Vectorizing horizontal reduction is possible" 6797 << "but not beneficial with cost " 6798 << ore::NV("Cost", Cost) << " and threshold " 6799 << ore::NV("Threshold", -SLPCostThreshold); 6800 }); 6801 break; 6802 } 6803 6804 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 6805 << Cost << ". (HorRdx)\n"); 6806 V.getORE()->emit([&]() { 6807 return OptimizationRemark( 6808 SV_NAME, "VectorizedHorizontalReduction", cast<Instruction>(VL[0])) 6809 << "Vectorized horizontal reduction with cost " 6810 << ore::NV("Cost", Cost) << " and with tree size " 6811 << ore::NV("TreeSize", V.getTreeSize()); 6812 }); 6813 6814 // Vectorize a tree. 6815 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); 6816 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues); 6817 6818 // Emit a reduction. For min/max, the root is a select, but the insertion 6819 // point is the compare condition of that select. 6820 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 6821 if (ReductionData.isMinMax()) 6822 Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst)); 6823 else 6824 Builder.SetInsertPoint(RdxRootInst); 6825 6826 Value *ReducedSubTree = 6827 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 6828 if (VectorizedTree) { 6829 Builder.SetCurrentDebugLocation(Loc); 6830 OperationData VectReductionData(ReductionData.getOpcode(), 6831 VectorizedTree, ReducedSubTree, 6832 ReductionData.getKind()); 6833 VectorizedTree = 6834 VectReductionData.createOp(Builder, "op.rdx", ReductionOps); 6835 } else 6836 VectorizedTree = ReducedSubTree; 6837 i += ReduxWidth; 6838 ReduxWidth = PowerOf2Floor(NumReducedVals - i); 6839 } 6840 6841 if (VectorizedTree) { 6842 // Finish the reduction. 6843 for (; i < NumReducedVals; ++i) { 6844 auto *I = cast<Instruction>(ReducedVals[i]); 6845 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 6846 OperationData VectReductionData(ReductionData.getOpcode(), 6847 VectorizedTree, I, 6848 ReductionData.getKind()); 6849 VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps); 6850 } 6851 for (auto &Pair : ExternallyUsedValues) { 6852 // Add each externally used value to the final reduction. 6853 for (auto *I : Pair.second) { 6854 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 6855 OperationData VectReductionData(ReductionData.getOpcode(), 6856 VectorizedTree, Pair.first, 6857 ReductionData.getKind()); 6858 VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I); 6859 } 6860 } 6861 6862 // Update users. For a min/max reduction that ends with a compare and 6863 // select, we also have to RAUW for the compare instruction feeding the 6864 // reduction root. That's because the original compare may have extra uses 6865 // besides the final select of the reduction. 6866 if (ReductionData.isMinMax()) { 6867 if (auto *VecSelect = dyn_cast<SelectInst>(VectorizedTree)) { 6868 Instruction *ScalarCmp = 6869 getCmpForMinMaxReduction(cast<Instruction>(ReductionRoot)); 6870 ScalarCmp->replaceAllUsesWith(VecSelect->getCondition()); 6871 } 6872 } 6873 ReductionRoot->replaceAllUsesWith(VectorizedTree); 6874 6875 // Mark all scalar reduction ops for deletion, they are replaced by the 6876 // vector reductions. 6877 V.eraseInstructions(IgnoreList); 6878 } 6879 return VectorizedTree != nullptr; 6880 } 6881 6882 unsigned numReductionValues() const { 6883 return ReducedVals.size(); 6884 } 6885 6886 private: 6887 /// Calculate the cost of a reduction. 6888 int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal, 6889 unsigned ReduxWidth) { 6890 Type *ScalarTy = FirstReducedVal->getType(); 6891 Type *VecTy = VectorType::get(ScalarTy, ReduxWidth); 6892 6893 int PairwiseRdxCost; 6894 int SplittingRdxCost; 6895 switch (ReductionData.getKind()) { 6896 case RK_Arithmetic: 6897 PairwiseRdxCost = 6898 TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy, 6899 /*IsPairwiseForm=*/true); 6900 SplittingRdxCost = 6901 TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy, 6902 /*IsPairwiseForm=*/false); 6903 break; 6904 case RK_Min: 6905 case RK_Max: 6906 case RK_UMin: 6907 case RK_UMax: { 6908 Type *VecCondTy = CmpInst::makeCmpResultType(VecTy); 6909 bool IsUnsigned = ReductionData.getKind() == RK_UMin || 6910 ReductionData.getKind() == RK_UMax; 6911 PairwiseRdxCost = 6912 TTI->getMinMaxReductionCost(VecTy, VecCondTy, 6913 /*IsPairwiseForm=*/true, IsUnsigned); 6914 SplittingRdxCost = 6915 TTI->getMinMaxReductionCost(VecTy, VecCondTy, 6916 /*IsPairwiseForm=*/false, IsUnsigned); 6917 break; 6918 } 6919 case RK_None: 6920 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 6921 } 6922 6923 IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost; 6924 int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost; 6925 6926 int ScalarReduxCost = 0; 6927 switch (ReductionData.getKind()) { 6928 case RK_Arithmetic: 6929 ScalarReduxCost = 6930 TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy); 6931 break; 6932 case RK_Min: 6933 case RK_Max: 6934 case RK_UMin: 6935 case RK_UMax: 6936 ScalarReduxCost = 6937 TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) + 6938 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 6939 CmpInst::makeCmpResultType(ScalarTy)); 6940 break; 6941 case RK_None: 6942 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 6943 } 6944 ScalarReduxCost *= (ReduxWidth - 1); 6945 6946 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost 6947 << " for reduction that starts with " << *FirstReducedVal 6948 << " (It is a " 6949 << (IsPairwiseReduction ? "pairwise" : "splitting") 6950 << " reduction)\n"); 6951 6952 return VecReduxCost - ScalarReduxCost; 6953 } 6954 6955 /// Emit a horizontal reduction of the vectorized value. 6956 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 6957 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 6958 assert(VectorizedValue && "Need to have a vectorized tree node"); 6959 assert(isPowerOf2_32(ReduxWidth) && 6960 "We only handle power-of-two reductions for now"); 6961 6962 if (!IsPairwiseReduction) { 6963 // FIXME: The builder should use an FMF guard. It should not be hard-coded 6964 // to 'fast'. 6965 assert(Builder.getFastMathFlags().isFast() && "Expected 'fast' FMF"); 6966 return createSimpleTargetReduction( 6967 Builder, TTI, ReductionData.getOpcode(), VectorizedValue, 6968 ReductionData.getFlags(), ReductionOps.back()); 6969 } 6970 6971 Value *TmpVec = VectorizedValue; 6972 for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) { 6973 Value *LeftMask = 6974 createRdxShuffleMask(ReduxWidth, i, true, true, Builder); 6975 Value *RightMask = 6976 createRdxShuffleMask(ReduxWidth, i, true, false, Builder); 6977 6978 Value *LeftShuf = Builder.CreateShuffleVector( 6979 TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l"); 6980 Value *RightShuf = Builder.CreateShuffleVector( 6981 TmpVec, UndefValue::get(TmpVec->getType()), (RightMask), 6982 "rdx.shuf.r"); 6983 OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf, 6984 RightShuf, ReductionData.getKind()); 6985 TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps); 6986 } 6987 6988 // The result is in the first element of the vector. 6989 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 6990 } 6991 }; 6992 6993 } // end anonymous namespace 6994 6995 /// Recognize construction of vectors like 6996 /// %ra = insertelement <4 x float> undef, float %s0, i32 0 6997 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 6998 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 6999 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 7000 /// starting from the last insertelement or insertvalue instruction. 7001 /// 7002 /// Also recognize aggregates like {<2 x float>, <2 x float>}, 7003 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 7004 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 7005 /// 7006 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 7007 /// 7008 /// \return true if it matches. 7009 static bool findBuildAggregate(Value *LastInsertInst, TargetTransformInfo *TTI, 7010 SmallVectorImpl<Value *> &BuildVectorOpds, 7011 int &UserCost) { 7012 assert((isa<InsertElementInst>(LastInsertInst) || 7013 isa<InsertValueInst>(LastInsertInst)) && 7014 "Expected insertelement or insertvalue instruction!"); 7015 UserCost = 0; 7016 do { 7017 Value *InsertedOperand; 7018 if (auto *IE = dyn_cast<InsertElementInst>(LastInsertInst)) { 7019 InsertedOperand = IE->getOperand(1); 7020 LastInsertInst = IE->getOperand(0); 7021 if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) { 7022 UserCost += TTI->getVectorInstrCost(Instruction::InsertElement, 7023 IE->getType(), CI->getZExtValue()); 7024 } 7025 } else { 7026 auto *IV = cast<InsertValueInst>(LastInsertInst); 7027 InsertedOperand = IV->getInsertedValueOperand(); 7028 LastInsertInst = IV->getAggregateOperand(); 7029 } 7030 if (isa<InsertElementInst>(InsertedOperand) || 7031 isa<InsertValueInst>(InsertedOperand)) { 7032 int TmpUserCost; 7033 SmallVector<Value *, 8> TmpBuildVectorOpds; 7034 if (!findBuildAggregate(InsertedOperand, TTI, TmpBuildVectorOpds, 7035 TmpUserCost)) 7036 return false; 7037 BuildVectorOpds.append(TmpBuildVectorOpds.rbegin(), 7038 TmpBuildVectorOpds.rend()); 7039 UserCost += TmpUserCost; 7040 } else { 7041 BuildVectorOpds.push_back(InsertedOperand); 7042 } 7043 if (isa<UndefValue>(LastInsertInst)) 7044 break; 7045 if ((!isa<InsertValueInst>(LastInsertInst) && 7046 !isa<InsertElementInst>(LastInsertInst)) || 7047 !LastInsertInst->hasOneUse()) 7048 return false; 7049 } while (true); 7050 std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end()); 7051 return true; 7052 } 7053 7054 static bool PhiTypeSorterFunc(Value *V, Value *V2) { 7055 return V->getType() < V2->getType(); 7056 } 7057 7058 /// Try and get a reduction value from a phi node. 7059 /// 7060 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 7061 /// if they come from either \p ParentBB or a containing loop latch. 7062 /// 7063 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 7064 /// if not possible. 7065 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 7066 BasicBlock *ParentBB, LoopInfo *LI) { 7067 // There are situations where the reduction value is not dominated by the 7068 // reduction phi. Vectorizing such cases has been reported to cause 7069 // miscompiles. See PR25787. 7070 auto DominatedReduxValue = [&](Value *R) { 7071 return isa<Instruction>(R) && 7072 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 7073 }; 7074 7075 Value *Rdx = nullptr; 7076 7077 // Return the incoming value if it comes from the same BB as the phi node. 7078 if (P->getIncomingBlock(0) == ParentBB) { 7079 Rdx = P->getIncomingValue(0); 7080 } else if (P->getIncomingBlock(1) == ParentBB) { 7081 Rdx = P->getIncomingValue(1); 7082 } 7083 7084 if (Rdx && DominatedReduxValue(Rdx)) 7085 return Rdx; 7086 7087 // Otherwise, check whether we have a loop latch to look at. 7088 Loop *BBL = LI->getLoopFor(ParentBB); 7089 if (!BBL) 7090 return nullptr; 7091 BasicBlock *BBLatch = BBL->getLoopLatch(); 7092 if (!BBLatch) 7093 return nullptr; 7094 7095 // There is a loop latch, return the incoming value if it comes from 7096 // that. This reduction pattern occasionally turns up. 7097 if (P->getIncomingBlock(0) == BBLatch) { 7098 Rdx = P->getIncomingValue(0); 7099 } else if (P->getIncomingBlock(1) == BBLatch) { 7100 Rdx = P->getIncomingValue(1); 7101 } 7102 7103 if (Rdx && DominatedReduxValue(Rdx)) 7104 return Rdx; 7105 7106 return nullptr; 7107 } 7108 7109 /// Attempt to reduce a horizontal reduction. 7110 /// If it is legal to match a horizontal reduction feeding the phi node \a P 7111 /// with reduction operators \a Root (or one of its operands) in a basic block 7112 /// \a BB, then check if it can be done. If horizontal reduction is not found 7113 /// and root instruction is a binary operation, vectorization of the operands is 7114 /// attempted. 7115 /// \returns true if a horizontal reduction was matched and reduced or operands 7116 /// of one of the binary instruction were vectorized. 7117 /// \returns false if a horizontal reduction was not matched (or not possible) 7118 /// or no vectorization of any binary operation feeding \a Root instruction was 7119 /// performed. 7120 static bool tryToVectorizeHorReductionOrInstOperands( 7121 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 7122 TargetTransformInfo *TTI, 7123 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 7124 if (!ShouldVectorizeHor) 7125 return false; 7126 7127 if (!Root) 7128 return false; 7129 7130 if (Root->getParent() != BB || isa<PHINode>(Root)) 7131 return false; 7132 // Start analysis starting from Root instruction. If horizontal reduction is 7133 // found, try to vectorize it. If it is not a horizontal reduction or 7134 // vectorization is not possible or not effective, and currently analyzed 7135 // instruction is a binary operation, try to vectorize the operands, using 7136 // pre-order DFS traversal order. If the operands were not vectorized, repeat 7137 // the same procedure considering each operand as a possible root of the 7138 // horizontal reduction. 7139 // Interrupt the process if the Root instruction itself was vectorized or all 7140 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 7141 SmallVector<std::pair<Instruction *, unsigned>, 8> Stack(1, {Root, 0}); 7142 SmallPtrSet<Value *, 8> VisitedInstrs; 7143 bool Res = false; 7144 while (!Stack.empty()) { 7145 Instruction *Inst; 7146 unsigned Level; 7147 std::tie(Inst, Level) = Stack.pop_back_val(); 7148 auto *BI = dyn_cast<BinaryOperator>(Inst); 7149 auto *SI = dyn_cast<SelectInst>(Inst); 7150 if (BI || SI) { 7151 HorizontalReduction HorRdx; 7152 if (HorRdx.matchAssociativeReduction(P, Inst)) { 7153 if (HorRdx.tryToReduce(R, TTI)) { 7154 Res = true; 7155 // Set P to nullptr to avoid re-analysis of phi node in 7156 // matchAssociativeReduction function unless this is the root node. 7157 P = nullptr; 7158 continue; 7159 } 7160 } 7161 if (P && BI) { 7162 Inst = dyn_cast<Instruction>(BI->getOperand(0)); 7163 if (Inst == P) 7164 Inst = dyn_cast<Instruction>(BI->getOperand(1)); 7165 if (!Inst) { 7166 // Set P to nullptr to avoid re-analysis of phi node in 7167 // matchAssociativeReduction function unless this is the root node. 7168 P = nullptr; 7169 continue; 7170 } 7171 } 7172 } 7173 // Set P to nullptr to avoid re-analysis of phi node in 7174 // matchAssociativeReduction function unless this is the root node. 7175 P = nullptr; 7176 if (Vectorize(Inst, R)) { 7177 Res = true; 7178 continue; 7179 } 7180 7181 // Try to vectorize operands. 7182 // Continue analysis for the instruction from the same basic block only to 7183 // save compile time. 7184 if (++Level < RecursionMaxDepth) 7185 for (auto *Op : Inst->operand_values()) 7186 if (VisitedInstrs.insert(Op).second) 7187 if (auto *I = dyn_cast<Instruction>(Op)) 7188 if (!isa<PHINode>(I) && !R.isDeleted(I) && I->getParent() == BB) 7189 Stack.emplace_back(I, Level); 7190 } 7191 return Res; 7192 } 7193 7194 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 7195 BasicBlock *BB, BoUpSLP &R, 7196 TargetTransformInfo *TTI) { 7197 if (!V) 7198 return false; 7199 auto *I = dyn_cast<Instruction>(V); 7200 if (!I) 7201 return false; 7202 7203 if (!isa<BinaryOperator>(I)) 7204 P = nullptr; 7205 // Try to match and vectorize a horizontal reduction. 7206 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 7207 return tryToVectorize(I, R); 7208 }; 7209 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, 7210 ExtraVectorization); 7211 } 7212 7213 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 7214 BasicBlock *BB, BoUpSLP &R) { 7215 int UserCost = 0; 7216 const DataLayout &DL = BB->getModule()->getDataLayout(); 7217 if (!R.canMapToVector(IVI->getType(), DL)) 7218 return false; 7219 7220 SmallVector<Value *, 16> BuildVectorOpds; 7221 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, UserCost)) 7222 return false; 7223 7224 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 7225 // Aggregate value is unlikely to be processed in vector register, we need to 7226 // extract scalars into scalar registers, so NeedExtraction is set true. 7227 return tryToVectorizeList(BuildVectorOpds, R, UserCost); 7228 } 7229 7230 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 7231 BasicBlock *BB, BoUpSLP &R) { 7232 int UserCost; 7233 SmallVector<Value *, 16> BuildVectorOpds; 7234 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, UserCost) || 7235 (llvm::all_of(BuildVectorOpds, 7236 [](Value *V) { return isa<ExtractElementInst>(V); }) && 7237 isShuffle(BuildVectorOpds))) 7238 return false; 7239 7240 // Vectorize starting with the build vector operands ignoring the BuildVector 7241 // instructions for the purpose of scheduling and user extraction. 7242 return tryToVectorizeList(BuildVectorOpds, R, UserCost); 7243 } 7244 7245 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB, 7246 BoUpSLP &R) { 7247 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) 7248 return true; 7249 7250 bool OpsChanged = false; 7251 for (int Idx = 0; Idx < 2; ++Idx) { 7252 OpsChanged |= 7253 vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI); 7254 } 7255 return OpsChanged; 7256 } 7257 7258 bool SLPVectorizerPass::vectorizeSimpleInstructions( 7259 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R) { 7260 bool OpsChanged = false; 7261 for (auto *I : reverse(Instructions)) { 7262 if (R.isDeleted(I)) 7263 continue; 7264 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) 7265 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 7266 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) 7267 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 7268 else if (auto *CI = dyn_cast<CmpInst>(I)) 7269 OpsChanged |= vectorizeCmpInst(CI, BB, R); 7270 } 7271 Instructions.clear(); 7272 return OpsChanged; 7273 } 7274 7275 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 7276 bool Changed = false; 7277 SmallVector<Value *, 4> Incoming; 7278 SmallPtrSet<Value *, 16> VisitedInstrs; 7279 7280 bool HaveVectorizedPhiNodes = true; 7281 while (HaveVectorizedPhiNodes) { 7282 HaveVectorizedPhiNodes = false; 7283 7284 // Collect the incoming values from the PHIs. 7285 Incoming.clear(); 7286 for (Instruction &I : *BB) { 7287 PHINode *P = dyn_cast<PHINode>(&I); 7288 if (!P) 7289 break; 7290 7291 if (!VisitedInstrs.count(P) && !R.isDeleted(P)) 7292 Incoming.push_back(P); 7293 } 7294 7295 // Sort by type. 7296 llvm::stable_sort(Incoming, PhiTypeSorterFunc); 7297 7298 // Try to vectorize elements base on their type. 7299 for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(), 7300 E = Incoming.end(); 7301 IncIt != E;) { 7302 7303 // Look for the next elements with the same type. 7304 SmallVector<Value *, 4>::iterator SameTypeIt = IncIt; 7305 while (SameTypeIt != E && 7306 (*SameTypeIt)->getType() == (*IncIt)->getType()) { 7307 VisitedInstrs.insert(*SameTypeIt); 7308 ++SameTypeIt; 7309 } 7310 7311 // Try to vectorize them. 7312 unsigned NumElts = (SameTypeIt - IncIt); 7313 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs (" 7314 << NumElts << ")\n"); 7315 // The order in which the phi nodes appear in the program does not matter. 7316 // So allow tryToVectorizeList to reorder them if it is beneficial. This 7317 // is done when there are exactly two elements since tryToVectorizeList 7318 // asserts that there are only two values when AllowReorder is true. 7319 bool AllowReorder = NumElts == 2; 7320 if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R, 7321 /*UserCost=*/0, AllowReorder)) { 7322 // Success start over because instructions might have been changed. 7323 HaveVectorizedPhiNodes = true; 7324 Changed = true; 7325 break; 7326 } 7327 7328 // Start over at the next instruction of a different type (or the end). 7329 IncIt = SameTypeIt; 7330 } 7331 } 7332 7333 VisitedInstrs.clear(); 7334 7335 SmallVector<Instruction *, 8> PostProcessInstructions; 7336 SmallDenseSet<Instruction *, 4> KeyNodes; 7337 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 7338 // Skip instructions marked for the deletion. 7339 if (R.isDeleted(&*it)) 7340 continue; 7341 // We may go through BB multiple times so skip the one we have checked. 7342 if (!VisitedInstrs.insert(&*it).second) { 7343 if (it->use_empty() && KeyNodes.count(&*it) > 0 && 7344 vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) { 7345 // We would like to start over since some instructions are deleted 7346 // and the iterator may become invalid value. 7347 Changed = true; 7348 it = BB->begin(); 7349 e = BB->end(); 7350 } 7351 continue; 7352 } 7353 7354 if (isa<DbgInfoIntrinsic>(it)) 7355 continue; 7356 7357 // Try to vectorize reductions that use PHINodes. 7358 if (PHINode *P = dyn_cast<PHINode>(it)) { 7359 // Check that the PHI is a reduction PHI. 7360 if (P->getNumIncomingValues() != 2) 7361 return Changed; 7362 7363 // Try to match and vectorize a horizontal reduction. 7364 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 7365 TTI)) { 7366 Changed = true; 7367 it = BB->begin(); 7368 e = BB->end(); 7369 continue; 7370 } 7371 continue; 7372 } 7373 7374 // Ran into an instruction without users, like terminator, or function call 7375 // with ignored return value, store. Ignore unused instructions (basing on 7376 // instruction type, except for CallInst and InvokeInst). 7377 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 7378 isa<InvokeInst>(it))) { 7379 KeyNodes.insert(&*it); 7380 bool OpsChanged = false; 7381 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 7382 for (auto *V : it->operand_values()) { 7383 // Try to match and vectorize a horizontal reduction. 7384 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 7385 } 7386 } 7387 // Start vectorization of post-process list of instructions from the 7388 // top-tree instructions to try to vectorize as many instructions as 7389 // possible. 7390 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R); 7391 if (OpsChanged) { 7392 // We would like to start over since some instructions are deleted 7393 // and the iterator may become invalid value. 7394 Changed = true; 7395 it = BB->begin(); 7396 e = BB->end(); 7397 continue; 7398 } 7399 } 7400 7401 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 7402 isa<InsertValueInst>(it)) 7403 PostProcessInstructions.push_back(&*it); 7404 } 7405 7406 return Changed; 7407 } 7408 7409 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 7410 auto Changed = false; 7411 for (auto &Entry : GEPs) { 7412 // If the getelementptr list has fewer than two elements, there's nothing 7413 // to do. 7414 if (Entry.second.size() < 2) 7415 continue; 7416 7417 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 7418 << Entry.second.size() << ".\n"); 7419 7420 // Process the GEP list in chunks suitable for the target's supported 7421 // vector size. If a vector register can't hold 1 element, we are done. 7422 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 7423 unsigned EltSize = R.getVectorElementSize(Entry.second[0]); 7424 if (MaxVecRegSize < EltSize) 7425 continue; 7426 7427 unsigned MaxElts = MaxVecRegSize / EltSize; 7428 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 7429 auto Len = std::min<unsigned>(BE - BI, MaxElts); 7430 auto GEPList = makeArrayRef(&Entry.second[BI], Len); 7431 7432 // Initialize a set a candidate getelementptrs. Note that we use a 7433 // SetVector here to preserve program order. If the index computations 7434 // are vectorizable and begin with loads, we want to minimize the chance 7435 // of having to reorder them later. 7436 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 7437 7438 // Some of the candidates may have already been vectorized after we 7439 // initially collected them. If so, they are marked as deleted, so remove 7440 // them from the set of candidates. 7441 Candidates.remove_if( 7442 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 7443 7444 // Remove from the set of candidates all pairs of getelementptrs with 7445 // constant differences. Such getelementptrs are likely not good 7446 // candidates for vectorization in a bottom-up phase since one can be 7447 // computed from the other. We also ensure all candidate getelementptr 7448 // indices are unique. 7449 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 7450 auto *GEPI = GEPList[I]; 7451 if (!Candidates.count(GEPI)) 7452 continue; 7453 auto *SCEVI = SE->getSCEV(GEPList[I]); 7454 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 7455 auto *GEPJ = GEPList[J]; 7456 auto *SCEVJ = SE->getSCEV(GEPList[J]); 7457 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 7458 Candidates.remove(GEPI); 7459 Candidates.remove(GEPJ); 7460 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 7461 Candidates.remove(GEPJ); 7462 } 7463 } 7464 } 7465 7466 // We break out of the above computation as soon as we know there are 7467 // fewer than two candidates remaining. 7468 if (Candidates.size() < 2) 7469 continue; 7470 7471 // Add the single, non-constant index of each candidate to the bundle. We 7472 // ensured the indices met these constraints when we originally collected 7473 // the getelementptrs. 7474 SmallVector<Value *, 16> Bundle(Candidates.size()); 7475 auto BundleIndex = 0u; 7476 for (auto *V : Candidates) { 7477 auto *GEP = cast<GetElementPtrInst>(V); 7478 auto *GEPIdx = GEP->idx_begin()->get(); 7479 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 7480 Bundle[BundleIndex++] = GEPIdx; 7481 } 7482 7483 // Try and vectorize the indices. We are currently only interested in 7484 // gather-like cases of the form: 7485 // 7486 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 7487 // 7488 // where the loads of "a", the loads of "b", and the subtractions can be 7489 // performed in parallel. It's likely that detecting this pattern in a 7490 // bottom-up phase will be simpler and less costly than building a 7491 // full-blown top-down phase beginning at the consecutive loads. 7492 Changed |= tryToVectorizeList(Bundle, R); 7493 } 7494 } 7495 return Changed; 7496 } 7497 7498 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 7499 bool Changed = false; 7500 // Attempt to sort and vectorize each of the store-groups. 7501 for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e; 7502 ++it) { 7503 if (it->second.size() < 2) 7504 continue; 7505 7506 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 7507 << it->second.size() << ".\n"); 7508 7509 Changed |= vectorizeStores(it->second, R); 7510 } 7511 return Changed; 7512 } 7513 7514 char SLPVectorizer::ID = 0; 7515 7516 static const char lv_name[] = "SLP Vectorizer"; 7517 7518 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 7519 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 7520 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 7521 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 7522 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 7523 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 7524 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 7525 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 7526 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 7527 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 7528 7529 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 7530