1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 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 #define SV_NAME "slp-vectorizer" 19 #define DEBUG_TYPE "SLP" 20 21 #include "llvm/Transforms/Vectorize.h" 22 #include "llvm/ADT/MapVector.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/SetVector.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/Analysis/ScalarEvolution.h" 27 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 28 #include "llvm/Analysis/AliasAnalysis.h" 29 #include "llvm/Analysis/TargetTransformInfo.h" 30 #include "llvm/Analysis/Verifier.h" 31 #include "llvm/Analysis/LoopInfo.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/IRBuilder.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/Type.h" 38 #include "llvm/IR/Value.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <algorithm> 44 #include <map> 45 46 using namespace llvm; 47 48 static cl::opt<int> 49 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, 50 cl::desc("Only vectorize if you gain more than this " 51 "number ")); 52 namespace { 53 54 static const unsigned MinVecRegSize = 128; 55 56 static const unsigned RecursionMaxDepth = 12; 57 58 /// RAII pattern to save the insertion point of the IR builder. 59 class BuilderLocGuard { 60 public: 61 BuilderLocGuard(IRBuilder<> &B) : Builder(B), Loc(B.GetInsertPoint()) {} 62 ~BuilderLocGuard() { if (Loc) Builder.SetInsertPoint(Loc); } 63 64 private: 65 // Prevent copying. 66 BuilderLocGuard(const BuilderLocGuard &); 67 BuilderLocGuard &operator=(const BuilderLocGuard &); 68 IRBuilder<> &Builder; 69 AssertingVH<Instruction> Loc; 70 }; 71 72 /// A helper class for numbering instructions in multible blocks. 73 /// Numbers starts at zero for each basic block. 74 struct BlockNumbering { 75 76 BlockNumbering(BasicBlock *Bb) : BB(Bb), Valid(false) {} 77 78 BlockNumbering() : BB(0), Valid(false) {} 79 80 void numberInstructions() { 81 unsigned Loc = 0; 82 InstrIdx.clear(); 83 InstrVec.clear(); 84 // Number the instructions in the block. 85 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 86 InstrIdx[it] = Loc++; 87 InstrVec.push_back(it); 88 assert(InstrVec[InstrIdx[it]] == it && "Invalid allocation"); 89 } 90 Valid = true; 91 } 92 93 int getIndex(Instruction *I) { 94 assert(I->getParent() == BB && "Invalid instruction"); 95 if (!Valid) 96 numberInstructions(); 97 assert(InstrIdx.count(I) && "Unknown instruction"); 98 return InstrIdx[I]; 99 } 100 101 Instruction *getInstruction(unsigned loc) { 102 if (!Valid) 103 numberInstructions(); 104 assert(InstrVec.size() > loc && "Invalid Index"); 105 return InstrVec[loc]; 106 } 107 108 void forget() { Valid = false; } 109 110 private: 111 /// The block we are numbering. 112 BasicBlock *BB; 113 /// Is the block numbered. 114 bool Valid; 115 /// Maps instructions to numbers and back. 116 SmallDenseMap<Instruction *, int> InstrIdx; 117 /// Maps integers to Instructions. 118 std::vector<Instruction *> InstrVec; 119 }; 120 121 /// \returns the parent basic block if all of the instructions in \p VL 122 /// are in the same block or null otherwise. 123 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) { 124 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 125 if (!I0) 126 return 0; 127 BasicBlock *BB = I0->getParent(); 128 for (int i = 1, e = VL.size(); i < e; i++) { 129 Instruction *I = dyn_cast<Instruction>(VL[i]); 130 if (!I) 131 return 0; 132 133 if (BB != I->getParent()) 134 return 0; 135 } 136 return BB; 137 } 138 139 /// \returns True if all of the values in \p VL are constants. 140 static bool allConstant(ArrayRef<Value *> VL) { 141 for (unsigned i = 0, e = VL.size(); i < e; ++i) 142 if (!isa<Constant>(VL[i])) 143 return false; 144 return true; 145 } 146 147 /// \returns True if all of the values in \p VL are identical. 148 static bool isSplat(ArrayRef<Value *> VL) { 149 for (unsigned i = 1, e = VL.size(); i < e; ++i) 150 if (VL[i] != VL[0]) 151 return false; 152 return true; 153 } 154 155 /// \returns The opcode if all of the Instructions in \p VL have the same 156 /// opcode, or zero. 157 static unsigned getSameOpcode(ArrayRef<Value *> VL) { 158 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 159 if (!I0) 160 return 0; 161 unsigned Opcode = I0->getOpcode(); 162 for (int i = 1, e = VL.size(); i < e; i++) { 163 Instruction *I = dyn_cast<Instruction>(VL[i]); 164 if (!I || Opcode != I->getOpcode()) 165 return 0; 166 } 167 return Opcode; 168 } 169 170 /// \returns The type that all of the values in \p VL have or null if there 171 /// are different types. 172 static Type* getSameType(ArrayRef<Value *> VL) { 173 Type *Ty = VL[0]->getType(); 174 for (int i = 1, e = VL.size(); i < e; i++) 175 if (VL[i]->getType() != Ty) 176 return 0; 177 178 return Ty; 179 } 180 181 /// \returns True if the ExtractElement instructions in VL can be vectorized 182 /// to use the original vector. 183 static bool CanReuseExtract(ArrayRef<Value *> VL) { 184 assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode"); 185 // Check if all of the extracts come from the same vector and from the 186 // correct offset. 187 Value *VL0 = VL[0]; 188 ExtractElementInst *E0 = cast<ExtractElementInst>(VL0); 189 Value *Vec = E0->getOperand(0); 190 191 // We have to extract from the same vector type. 192 unsigned NElts = Vec->getType()->getVectorNumElements(); 193 194 if (NElts != VL.size()) 195 return false; 196 197 // Check that all of the indices extract from the correct offset. 198 ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1)); 199 if (!CI || CI->getZExtValue()) 200 return false; 201 202 for (unsigned i = 1, e = VL.size(); i < e; ++i) { 203 ExtractElementInst *E = cast<ExtractElementInst>(VL[i]); 204 ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 205 206 if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec) 207 return false; 208 } 209 210 return true; 211 } 212 213 /// Bottom Up SLP Vectorizer. 214 class BoUpSLP { 215 public: 216 typedef SmallVector<Value *, 8> ValueList; 217 typedef SmallVector<Instruction *, 16> InstrList; 218 typedef SmallPtrSet<Value *, 16> ValueSet; 219 typedef SmallVector<StoreInst *, 8> StoreList; 220 221 BoUpSLP(Function *Func, ScalarEvolution *Se, DataLayout *Dl, 222 TargetTransformInfo *Tti, AliasAnalysis *Aa, LoopInfo *Li, 223 DominatorTree *Dt) : 224 F(Func), SE(Se), DL(Dl), TTI(Tti), AA(Aa), LI(Li), DT(Dt), 225 Builder(Se->getContext()) { 226 // Setup the block numbering utility for all of the blocks in the 227 // function. 228 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) { 229 BasicBlock *BB = it; 230 BlocksNumbers[BB] = BlockNumbering(BB); 231 } 232 } 233 234 /// \brief Vectorize the tree that starts with the elements in \p VL. 235 void vectorizeTree(); 236 237 /// \returns the vectorization cost of the subtree that starts at \p VL. 238 /// A negative number means that this is profitable. 239 int getTreeCost(); 240 241 /// Construct a vectorizable tree that starts at \p Roots. 242 void buildTree(ArrayRef<Value *> Roots); 243 244 /// Clear the internal data structures that are created by 'buildTree'. 245 void deleteTree() { 246 VectorizableTree.clear(); 247 ScalarToTreeEntry.clear(); 248 MustGather.clear(); 249 ExternalUses.clear(); 250 MemBarrierIgnoreList.clear(); 251 } 252 253 /// \returns true if the memory operations A and B are consecutive. 254 bool isConsecutiveAccess(Value *A, Value *B); 255 256 /// \brief Perform LICM and CSE on the newly generated gather sequences. 257 void optimizeGatherSequence(); 258 private: 259 struct TreeEntry; 260 261 /// \returns the cost of the vectorizable entry. 262 int getEntryCost(TreeEntry *E); 263 264 /// This is the recursive part of buildTree. 265 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth); 266 267 /// Vectorizer a single entry in the tree. 268 Value *vectorizeTree(TreeEntry *E); 269 270 /// Vectorizer a single entry in the tree, starting in \p VL. 271 Value *vectorizeTree(ArrayRef<Value *> VL); 272 273 /// \brief Take the pointer operand from the Load/Store instruction. 274 /// \returns NULL if this is not a valid Load/Store instruction. 275 static Value *getPointerOperand(Value *I); 276 277 /// \brief Take the address space operand from the Load/Store instruction. 278 /// \returns -1 if this is not a valid Load/Store instruction. 279 static unsigned getAddressSpaceOperand(Value *I); 280 281 /// \returns the scalarization cost for this type. Scalarization in this 282 /// context means the creation of vectors from a group of scalars. 283 int getGatherCost(Type *Ty); 284 285 /// \returns the scalarization cost for this list of values. Assuming that 286 /// this subtree gets vectorized, we may need to extract the values from the 287 /// roots. This method calculates the cost of extracting the values. 288 int getGatherCost(ArrayRef<Value *> VL); 289 290 /// \returns the AA location that is being access by the instruction. 291 AliasAnalysis::Location getLocation(Instruction *I); 292 293 /// \brief Checks if it is possible to sink an instruction from 294 /// \p Src to \p Dst. 295 /// \returns the pointer to the barrier instruction if we can't sink. 296 Value *getSinkBarrier(Instruction *Src, Instruction *Dst); 297 298 /// \returns the index of the last instrucion in the BB from \p VL. 299 int getLastIndex(ArrayRef<Value *> VL); 300 301 /// \returns the Instrucion in the bundle \p VL. 302 Instruction *getLastInstruction(ArrayRef<Value *> VL); 303 304 /// \returns the Instruction at index \p Index which is in Block \p BB. 305 Instruction *getInstructionForIndex(unsigned Index, BasicBlock *BB); 306 307 /// \returns the index of the first User of \p VL. 308 int getFirstUserIndex(ArrayRef<Value *> VL); 309 310 /// \returns a vector from a collection of scalars in \p VL. 311 Value *Gather(ArrayRef<Value *> VL, VectorType *Ty); 312 313 struct TreeEntry { 314 TreeEntry() : Scalars(), VectorizedValue(0), LastScalarIndex(0), 315 NeedToGather(0) {} 316 317 /// \returns true if the scalars in VL are equal to this entry. 318 bool isSame(ArrayRef<Value *> VL) { 319 assert(VL.size() == Scalars.size() && "Invalid size"); 320 for (int i = 0, e = VL.size(); i != e; ++i) 321 if (VL[i] != Scalars[i]) 322 return false; 323 return true; 324 } 325 326 /// A vector of scalars. 327 ValueList Scalars; 328 329 /// The Scalars are vectorized into this value. It is initialized to Null. 330 Value *VectorizedValue; 331 332 /// The index in the basic block of the last scalar. 333 int LastScalarIndex; 334 335 /// Do we need to gather this sequence ? 336 bool NeedToGather; 337 }; 338 339 /// Create a new VectorizableTree entry. 340 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) { 341 VectorizableTree.push_back(TreeEntry()); 342 int idx = VectorizableTree.size() - 1; 343 TreeEntry *Last = &VectorizableTree[idx]; 344 Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end()); 345 Last->NeedToGather = !Vectorized; 346 if (Vectorized) { 347 Last->LastScalarIndex = getLastIndex(VL); 348 for (int i = 0, e = VL.size(); i != e; ++i) { 349 assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!"); 350 ScalarToTreeEntry[VL[i]] = idx; 351 } 352 } else { 353 Last->LastScalarIndex = 0; 354 MustGather.insert(VL.begin(), VL.end()); 355 } 356 return Last; 357 } 358 359 /// -- Vectorization State -- 360 /// Holds all of the tree entries. 361 std::vector<TreeEntry> VectorizableTree; 362 363 /// Maps a specific scalar to its tree entry. 364 SmallDenseMap<Value*, int> ScalarToTreeEntry; 365 366 /// A list of scalars that we found that we need to keep as scalars. 367 ValueSet MustGather; 368 369 /// This POD struct describes one external user in the vectorized tree. 370 struct ExternalUser { 371 ExternalUser (Value *S, llvm::User *U, int L) : 372 Scalar(S), User(U), Lane(L){}; 373 // Which scalar in our function. 374 Value *Scalar; 375 // Which user that uses the scalar. 376 llvm::User *User; 377 // Which lane does the scalar belong to. 378 int Lane; 379 }; 380 typedef SmallVector<ExternalUser, 16> UserList; 381 382 /// A list of values that need to extracted out of the tree. 383 /// This list holds pairs of (Internal Scalar : External User). 384 UserList ExternalUses; 385 386 /// A list of instructions to ignore while sinking 387 /// memory instructions. This map must be reset between runs of getCost. 388 ValueSet MemBarrierIgnoreList; 389 390 /// Holds all of the instructions that we gathered. 391 SetVector<Instruction *> GatherSeq; 392 393 /// Numbers instructions in different blocks. 394 std::map<BasicBlock *, BlockNumbering> BlocksNumbers; 395 396 // Analysis and block reference. 397 Function *F; 398 ScalarEvolution *SE; 399 DataLayout *DL; 400 TargetTransformInfo *TTI; 401 AliasAnalysis *AA; 402 LoopInfo *LI; 403 DominatorTree *DT; 404 /// Instruction builder to construct the vectorized tree. 405 IRBuilder<> Builder; 406 }; 407 408 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) { 409 deleteTree(); 410 if (!getSameType(Roots)) 411 return; 412 buildTree_rec(Roots, 0); 413 414 // Collect the values that we need to extract from the tree. 415 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) { 416 TreeEntry *Entry = &VectorizableTree[EIdx]; 417 418 // For each lane: 419 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 420 Value *Scalar = Entry->Scalars[Lane]; 421 422 // No need to handle users of gathered values. 423 if (Entry->NeedToGather) 424 continue; 425 426 for (Value::use_iterator User = Scalar->use_begin(), 427 UE = Scalar->use_end(); User != UE; ++User) { 428 DEBUG(dbgs() << "SLP: Checking user:" << **User << ".\n"); 429 430 bool Gathered = MustGather.count(*User); 431 432 // Skip in-tree scalars that become vectors. 433 if (ScalarToTreeEntry.count(*User) && !Gathered) { 434 DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << 435 **User << ".\n"); 436 int Idx = ScalarToTreeEntry[*User]; (void) Idx; 437 assert(!VectorizableTree[Idx].NeedToGather && "Bad state"); 438 continue; 439 } 440 441 if (!isa<Instruction>(*User)) 442 continue; 443 444 DEBUG(dbgs() << "SLP: Need to extract:" << **User << " from lane " << 445 Lane << " from " << *Scalar << ".\n"); 446 ExternalUses.push_back(ExternalUser(Scalar, *User, Lane)); 447 } 448 } 449 } 450 } 451 452 453 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) { 454 bool SameTy = getSameType(VL); (void)SameTy; 455 assert(SameTy && "Invalid types!"); 456 457 if (Depth == RecursionMaxDepth) { 458 DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 459 newTreeEntry(VL, false); 460 return; 461 } 462 463 // Don't handle vectors. 464 if (VL[0]->getType()->isVectorTy()) { 465 DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 466 newTreeEntry(VL, false); 467 return; 468 } 469 470 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 471 if (SI->getValueOperand()->getType()->isVectorTy()) { 472 DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 473 newTreeEntry(VL, false); 474 return; 475 } 476 477 // If all of the operands are identical or constant we have a simple solution. 478 if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || 479 !getSameOpcode(VL)) { 480 DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 481 newTreeEntry(VL, false); 482 return; 483 } 484 485 // We now know that this is a vector of instructions of the same type from 486 // the same block. 487 488 // Check if this is a duplicate of another entry. 489 if (ScalarToTreeEntry.count(VL[0])) { 490 int Idx = ScalarToTreeEntry[VL[0]]; 491 TreeEntry *E = &VectorizableTree[Idx]; 492 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 493 DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n"); 494 if (E->Scalars[i] != VL[i]) { 495 DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 496 newTreeEntry(VL, false); 497 return; 498 } 499 } 500 DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n"); 501 return; 502 } 503 504 // Check that none of the instructions in the bundle are already in the tree. 505 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 506 if (ScalarToTreeEntry.count(VL[i])) { 507 DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] << 508 ") is already in tree.\n"); 509 newTreeEntry(VL, false); 510 return; 511 } 512 } 513 514 // If any of the scalars appears in the table OR it is marked as a value that 515 // needs to stat scalar then we need to gather the scalars. 516 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 517 if (ScalarToTreeEntry.count(VL[i]) || MustGather.count(VL[i])) { 518 DEBUG(dbgs() << "SLP: Gathering due to gathered scalar. \n"); 519 newTreeEntry(VL, false); 520 return; 521 } 522 } 523 524 // Check that all of the users of the scalars that we want to vectorize are 525 // schedulable. 526 Instruction *VL0 = cast<Instruction>(VL[0]); 527 int MyLastIndex = getLastIndex(VL); 528 BasicBlock *BB = cast<Instruction>(VL0)->getParent(); 529 530 for (unsigned i = 0, e = VL.size(); i != e; ++i) { 531 Instruction *Scalar = cast<Instruction>(VL[i]); 532 DEBUG(dbgs() << "SLP: Checking users of " << *Scalar << ". \n"); 533 for (Value::use_iterator U = Scalar->use_begin(), UE = Scalar->use_end(); 534 U != UE; ++U) { 535 DEBUG(dbgs() << "SLP: \tUser " << **U << ". \n"); 536 Instruction *User = dyn_cast<Instruction>(*U); 537 if (!User) { 538 DEBUG(dbgs() << "SLP: Gathering due unknown user. \n"); 539 newTreeEntry(VL, false); 540 return; 541 } 542 543 // We don't care if the user is in a different basic block. 544 BasicBlock *UserBlock = User->getParent(); 545 if (UserBlock != BB) { 546 DEBUG(dbgs() << "SLP: User from a different basic block " 547 << *User << ". \n"); 548 continue; 549 } 550 551 // If this is a PHINode within this basic block then we can place the 552 // extract wherever we want. 553 if (isa<PHINode>(*User)) { 554 DEBUG(dbgs() << "SLP: \tWe can schedule PHIs:" << *User << ". \n"); 555 continue; 556 } 557 558 // Check if this is a safe in-tree user. 559 if (ScalarToTreeEntry.count(User)) { 560 int Idx = ScalarToTreeEntry[User]; 561 int VecLocation = VectorizableTree[Idx].LastScalarIndex; 562 if (VecLocation <= MyLastIndex) { 563 DEBUG(dbgs() << "SLP: Gathering due to unschedulable vector. \n"); 564 newTreeEntry(VL, false); 565 return; 566 } 567 DEBUG(dbgs() << "SLP: In-tree user (" << *User << ") at #" << 568 VecLocation << " vector value (" << *Scalar << ") at #" 569 << MyLastIndex << ".\n"); 570 continue; 571 } 572 573 // Make sure that we can schedule this unknown user. 574 BlockNumbering &BN = BlocksNumbers[BB]; 575 int UserIndex = BN.getIndex(User); 576 if (UserIndex < MyLastIndex) { 577 578 DEBUG(dbgs() << "SLP: Can't schedule extractelement for " 579 << *User << ". \n"); 580 newTreeEntry(VL, false); 581 return; 582 } 583 } 584 } 585 586 // Check that every instructions appears once in this bundle. 587 for (unsigned i = 0, e = VL.size(); i < e; ++i) 588 for (unsigned j = i+1; j < e; ++j) 589 if (VL[i] == VL[j]) { 590 DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 591 newTreeEntry(VL, false); 592 return; 593 } 594 595 // Check that instructions in this bundle don't reference other instructions. 596 // The runtime of this check is O(N * N-1 * uses(N)) and a typical N is 4. 597 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 598 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end(); 599 U != UE; ++U) { 600 for (unsigned j = 0; j < e; ++j) { 601 if (i != j && *U == VL[j]) { 602 DEBUG(dbgs() << "SLP: Intra-bundle dependencies!" << **U << ". \n"); 603 newTreeEntry(VL, false); 604 return; 605 } 606 } 607 } 608 } 609 610 DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 611 612 unsigned Opcode = getSameOpcode(VL); 613 614 // Check if it is safe to sink the loads or the stores. 615 if (Opcode == Instruction::Load || Opcode == Instruction::Store) { 616 Instruction *Last = getLastInstruction(VL); 617 618 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 619 if (VL[i] == Last) 620 continue; 621 Value *Barrier = getSinkBarrier(cast<Instruction>(VL[i]), Last); 622 if (Barrier) { 623 DEBUG(dbgs() << "SLP: Can't sink " << *VL[i] << "\n down to " << *Last 624 << "\n because of " << *Barrier << ". Gathering.\n"); 625 newTreeEntry(VL, false); 626 return; 627 } 628 } 629 } 630 631 switch (Opcode) { 632 case Instruction::PHI: { 633 PHINode *PH = dyn_cast<PHINode>(VL0); 634 newTreeEntry(VL, true); 635 DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 636 637 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 638 ValueList Operands; 639 // Prepare the operand vector. 640 for (unsigned j = 0; j < VL.size(); ++j) 641 Operands.push_back(cast<PHINode>(VL[j])->getIncomingValue(i)); 642 643 buildTree_rec(Operands, Depth + 1); 644 } 645 return; 646 } 647 case Instruction::ExtractElement: { 648 bool Reuse = CanReuseExtract(VL); 649 if (Reuse) { 650 DEBUG(dbgs() << "SLP: Reusing extract sequence.\n"); 651 } 652 newTreeEntry(VL, Reuse); 653 return; 654 } 655 case Instruction::Load: { 656 // Check if the loads are consecutive or of we need to swizzle them. 657 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) 658 if (!isConsecutiveAccess(VL[i], VL[i + 1])) { 659 newTreeEntry(VL, false); 660 DEBUG(dbgs() << "SLP: Need to swizzle loads.\n"); 661 return; 662 } 663 664 newTreeEntry(VL, true); 665 DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 666 return; 667 } 668 case Instruction::ZExt: 669 case Instruction::SExt: 670 case Instruction::FPToUI: 671 case Instruction::FPToSI: 672 case Instruction::FPExt: 673 case Instruction::PtrToInt: 674 case Instruction::IntToPtr: 675 case Instruction::SIToFP: 676 case Instruction::UIToFP: 677 case Instruction::Trunc: 678 case Instruction::FPTrunc: 679 case Instruction::BitCast: { 680 Type *SrcTy = VL0->getOperand(0)->getType(); 681 for (unsigned i = 0; i < VL.size(); ++i) { 682 Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType(); 683 if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) { 684 newTreeEntry(VL, false); 685 DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n"); 686 return; 687 } 688 } 689 newTreeEntry(VL, true); 690 DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 691 692 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 693 ValueList Operands; 694 // Prepare the operand vector. 695 for (unsigned j = 0; j < VL.size(); ++j) 696 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 697 698 buildTree_rec(Operands, Depth+1); 699 } 700 return; 701 } 702 case Instruction::ICmp: 703 case Instruction::FCmp: { 704 // Check that all of the compares have the same predicate. 705 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate(); 706 Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType(); 707 for (unsigned i = 1, e = VL.size(); i < e; ++i) { 708 CmpInst *Cmp = cast<CmpInst>(VL[i]); 709 if (Cmp->getPredicate() != P0 || 710 Cmp->getOperand(0)->getType() != ComparedTy) { 711 newTreeEntry(VL, false); 712 DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n"); 713 return; 714 } 715 } 716 717 newTreeEntry(VL, true); 718 DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 719 720 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 721 ValueList Operands; 722 // Prepare the operand vector. 723 for (unsigned j = 0; j < VL.size(); ++j) 724 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 725 726 buildTree_rec(Operands, Depth+1); 727 } 728 return; 729 } 730 case Instruction::Select: 731 case Instruction::Add: 732 case Instruction::FAdd: 733 case Instruction::Sub: 734 case Instruction::FSub: 735 case Instruction::Mul: 736 case Instruction::FMul: 737 case Instruction::UDiv: 738 case Instruction::SDiv: 739 case Instruction::FDiv: 740 case Instruction::URem: 741 case Instruction::SRem: 742 case Instruction::FRem: 743 case Instruction::Shl: 744 case Instruction::LShr: 745 case Instruction::AShr: 746 case Instruction::And: 747 case Instruction::Or: 748 case Instruction::Xor: { 749 newTreeEntry(VL, true); 750 DEBUG(dbgs() << "SLP: added a vector of bin op.\n"); 751 752 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 753 ValueList Operands; 754 // Prepare the operand vector. 755 for (unsigned j = 0; j < VL.size(); ++j) 756 Operands.push_back(cast<Instruction>(VL[j])->getOperand(i)); 757 758 buildTree_rec(Operands, Depth+1); 759 } 760 return; 761 } 762 case Instruction::Store: { 763 // Check if the stores are consecutive or of we need to swizzle them. 764 for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) 765 if (!isConsecutiveAccess(VL[i], VL[i + 1])) { 766 newTreeEntry(VL, false); 767 DEBUG(dbgs() << "SLP: Non consecutive store.\n"); 768 return; 769 } 770 771 newTreeEntry(VL, true); 772 DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 773 774 ValueList Operands; 775 for (unsigned j = 0; j < VL.size(); ++j) 776 Operands.push_back(cast<Instruction>(VL[j])->getOperand(0)); 777 778 // We can ignore these values because we are sinking them down. 779 MemBarrierIgnoreList.insert(VL.begin(), VL.end()); 780 buildTree_rec(Operands, Depth + 1); 781 return; 782 } 783 default: 784 newTreeEntry(VL, false); 785 DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 786 return; 787 } 788 } 789 790 int BoUpSLP::getEntryCost(TreeEntry *E) { 791 ArrayRef<Value*> VL = E->Scalars; 792 793 Type *ScalarTy = VL[0]->getType(); 794 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 795 ScalarTy = SI->getValueOperand()->getType(); 796 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 797 798 if (E->NeedToGather) { 799 if (allConstant(VL)) 800 return 0; 801 if (isSplat(VL)) { 802 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0); 803 } 804 return getGatherCost(E->Scalars); 805 } 806 807 assert(getSameOpcode(VL) && getSameType(VL) && getSameBlock(VL) && 808 "Invalid VL"); 809 Instruction *VL0 = cast<Instruction>(VL[0]); 810 unsigned Opcode = VL0->getOpcode(); 811 switch (Opcode) { 812 case Instruction::PHI: { 813 return 0; 814 } 815 case Instruction::ExtractElement: { 816 if (CanReuseExtract(VL)) 817 return 0; 818 return getGatherCost(VecTy); 819 } 820 case Instruction::ZExt: 821 case Instruction::SExt: 822 case Instruction::FPToUI: 823 case Instruction::FPToSI: 824 case Instruction::FPExt: 825 case Instruction::PtrToInt: 826 case Instruction::IntToPtr: 827 case Instruction::SIToFP: 828 case Instruction::UIToFP: 829 case Instruction::Trunc: 830 case Instruction::FPTrunc: 831 case Instruction::BitCast: { 832 Type *SrcTy = VL0->getOperand(0)->getType(); 833 834 // Calculate the cost of this instruction. 835 int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(), 836 VL0->getType(), SrcTy); 837 838 VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size()); 839 int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy); 840 return VecCost - ScalarCost; 841 } 842 case Instruction::FCmp: 843 case Instruction::ICmp: 844 case Instruction::Select: 845 case Instruction::Add: 846 case Instruction::FAdd: 847 case Instruction::Sub: 848 case Instruction::FSub: 849 case Instruction::Mul: 850 case Instruction::FMul: 851 case Instruction::UDiv: 852 case Instruction::SDiv: 853 case Instruction::FDiv: 854 case Instruction::URem: 855 case Instruction::SRem: 856 case Instruction::FRem: 857 case Instruction::Shl: 858 case Instruction::LShr: 859 case Instruction::AShr: 860 case Instruction::And: 861 case Instruction::Or: 862 case Instruction::Xor: { 863 // Calculate the cost of this instruction. 864 int ScalarCost = 0; 865 int VecCost = 0; 866 if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp || 867 Opcode == Instruction::Select) { 868 VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size()); 869 ScalarCost = VecTy->getNumElements() * 870 TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty()); 871 VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy); 872 } else { 873 ScalarCost = VecTy->getNumElements() * 874 TTI->getArithmeticInstrCost(Opcode, ScalarTy); 875 VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy); 876 } 877 return VecCost - ScalarCost; 878 } 879 case Instruction::Load: { 880 // Cost of wide load - cost of scalar loads. 881 int ScalarLdCost = VecTy->getNumElements() * 882 TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0); 883 int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0); 884 return VecLdCost - ScalarLdCost; 885 } 886 case Instruction::Store: { 887 // We know that we can merge the stores. Calculate the cost. 888 int ScalarStCost = VecTy->getNumElements() * 889 TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0); 890 int VecStCost = TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0); 891 return VecStCost - ScalarStCost; 892 } 893 default: 894 llvm_unreachable("Unknown instruction"); 895 } 896 } 897 898 int BoUpSLP::getTreeCost() { 899 int Cost = 0; 900 DEBUG(dbgs() << "SLP: Calculating cost for tree of size " << 901 VectorizableTree.size() << ".\n"); 902 903 if (!VectorizableTree.size()) { 904 assert(!ExternalUses.size() && "We should not have any external users"); 905 return 0; 906 } 907 908 unsigned BundleWidth = VectorizableTree[0].Scalars.size(); 909 910 for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) { 911 int C = getEntryCost(&VectorizableTree[i]); 912 DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with " 913 << *VectorizableTree[i].Scalars[0] << " .\n"); 914 Cost += C; 915 } 916 917 int ExtractCost = 0; 918 for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end(); 919 I != E; ++I) { 920 921 VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth); 922 ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, 923 I->Lane); 924 } 925 926 927 DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n"); 928 return Cost + ExtractCost; 929 } 930 931 int BoUpSLP::getGatherCost(Type *Ty) { 932 int Cost = 0; 933 for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i) 934 Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i); 935 return Cost; 936 } 937 938 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) { 939 // Find the type of the operands in VL. 940 Type *ScalarTy = VL[0]->getType(); 941 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 942 ScalarTy = SI->getValueOperand()->getType(); 943 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 944 // Find the cost of inserting/extracting values from the vector. 945 return getGatherCost(VecTy); 946 } 947 948 AliasAnalysis::Location BoUpSLP::getLocation(Instruction *I) { 949 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 950 return AA->getLocation(SI); 951 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 952 return AA->getLocation(LI); 953 return AliasAnalysis::Location(); 954 } 955 956 Value *BoUpSLP::getPointerOperand(Value *I) { 957 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 958 return LI->getPointerOperand(); 959 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 960 return SI->getPointerOperand(); 961 return 0; 962 } 963 964 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) { 965 if (LoadInst *L = dyn_cast<LoadInst>(I)) 966 return L->getPointerAddressSpace(); 967 if (StoreInst *S = dyn_cast<StoreInst>(I)) 968 return S->getPointerAddressSpace(); 969 return -1; 970 } 971 972 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) { 973 Value *PtrA = getPointerOperand(A); 974 Value *PtrB = getPointerOperand(B); 975 unsigned ASA = getAddressSpaceOperand(A); 976 unsigned ASB = getAddressSpaceOperand(B); 977 978 // Check that the address spaces match and that the pointers are valid. 979 if (!PtrA || !PtrB || (ASA != ASB)) 980 return false; 981 982 // Make sure that A and B are different pointers of the same type. 983 if (PtrA == PtrB || PtrA->getType() != PtrB->getType()) 984 return false; 985 986 // Calculate a constant offset from the base pointer without using SCEV 987 // in the supported cases. 988 // TODO: Add support for the case where one of the pointers is a GEP that 989 // uses the other pointer. 990 GetElementPtrInst *GepA = dyn_cast<GetElementPtrInst>(PtrA); 991 GetElementPtrInst *GepB = dyn_cast<GetElementPtrInst>(PtrB); 992 993 unsigned BW = DL->getPointerSizeInBits(ASA); 994 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType(); 995 int64_t Sz = DL->getTypeStoreSize(Ty); 996 997 // If both pointers are GEPs: 998 if (GepA && GepB) { 999 // Check that they have the same base pointer. 1000 if (GepA->getPointerOperand() != GepB->getPointerOperand()) 1001 return false; 1002 1003 // Check if the geps use a constant offset. 1004 APInt OffsetA(BW, 0) ,OffsetB(BW, 0); 1005 if (GepA->accumulateConstantOffset(*DL, OffsetA) && 1006 GepB->accumulateConstantOffset(*DL, OffsetB)) 1007 return ((OffsetB.getSExtValue() - OffsetA.getSExtValue()) == Sz); 1008 1009 if (GepA->getNumIndices() != GepB->getNumIndices()) 1010 return false; 1011 1012 // Try to strip the geps. This makes SCEV faster. 1013 // Make sure that all of the indices except for the last are identical. 1014 int LastIdx = GepA->getNumIndices(); 1015 for (int i = 0; i < LastIdx - 1; i++) { 1016 if (GepA->getOperand(i+1) != GepB->getOperand(i+1)) 1017 return false; 1018 } 1019 1020 PtrA = GepA->getOperand(LastIdx); 1021 PtrB = GepB->getOperand(LastIdx); 1022 Sz = 1; 1023 } 1024 1025 // Check if PtrA is the base and PtrB is a constant offset. 1026 if (GepB && GepB->getPointerOperand() == PtrA) { 1027 APInt Offset(BW, 0); 1028 if (GepB->accumulateConstantOffset(*DL, Offset)) 1029 return Offset.getZExtValue() == DL->getTypeStoreSize(Ty); 1030 } 1031 1032 // GepA can't use PtrB as a base pointer. 1033 if (GepA && GepA->getPointerOperand() == PtrB) 1034 return false; 1035 1036 ConstantInt *CA = dyn_cast<ConstantInt>(PtrA); 1037 ConstantInt *CB = dyn_cast<ConstantInt>(PtrB); 1038 if (CA && CB) { 1039 return (CA->getSExtValue() + Sz == CB->getSExtValue()); 1040 } 1041 1042 // Calculate the distance. 1043 const SCEV *PtrSCEVA = SE->getSCEV(PtrA); 1044 const SCEV *PtrSCEVB = SE->getSCEV(PtrB); 1045 const SCEV *C = SE->getConstant(PtrSCEVA->getType(), Sz); 1046 const SCEV *X = SE->getAddExpr(PtrSCEVA, C); 1047 return X == PtrSCEVB; 1048 } 1049 1050 Value *BoUpSLP::getSinkBarrier(Instruction *Src, Instruction *Dst) { 1051 assert(Src->getParent() == Dst->getParent() && "Not the same BB"); 1052 BasicBlock::iterator I = Src, E = Dst; 1053 /// Scan all of the instruction from SRC to DST and check if 1054 /// the source may alias. 1055 for (++I; I != E; ++I) { 1056 // Ignore store instructions that are marked as 'ignore'. 1057 if (MemBarrierIgnoreList.count(I)) 1058 continue; 1059 if (Src->mayWriteToMemory()) /* Write */ { 1060 if (!I->mayReadOrWriteMemory()) 1061 continue; 1062 } else /* Read */ { 1063 if (!I->mayWriteToMemory()) 1064 continue; 1065 } 1066 AliasAnalysis::Location A = getLocation(&*I); 1067 AliasAnalysis::Location B = getLocation(Src); 1068 1069 if (!A.Ptr || !B.Ptr || AA->alias(A, B)) 1070 return I; 1071 } 1072 return 0; 1073 } 1074 1075 int BoUpSLP::getLastIndex(ArrayRef<Value *> VL) { 1076 BasicBlock *BB = cast<Instruction>(VL[0])->getParent(); 1077 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block"); 1078 BlockNumbering &BN = BlocksNumbers[BB]; 1079 1080 int MaxIdx = BN.getIndex(BB->getFirstNonPHI()); 1081 for (unsigned i = 0, e = VL.size(); i < e; ++i) 1082 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i]))); 1083 return MaxIdx; 1084 } 1085 1086 Instruction *BoUpSLP::getLastInstruction(ArrayRef<Value *> VL) { 1087 BasicBlock *BB = cast<Instruction>(VL[0])->getParent(); 1088 assert(BB == getSameBlock(VL) && BlocksNumbers.count(BB) && "Invalid block"); 1089 BlockNumbering &BN = BlocksNumbers[BB]; 1090 1091 int MaxIdx = BN.getIndex(cast<Instruction>(VL[0])); 1092 for (unsigned i = 1, e = VL.size(); i < e; ++i) 1093 MaxIdx = std::max(MaxIdx, BN.getIndex(cast<Instruction>(VL[i]))); 1094 Instruction *I = BN.getInstruction(MaxIdx); 1095 assert(I && "bad location"); 1096 return I; 1097 } 1098 1099 Instruction *BoUpSLP::getInstructionForIndex(unsigned Index, BasicBlock *BB) { 1100 BlockNumbering &BN = BlocksNumbers[BB]; 1101 return BN.getInstruction(Index); 1102 } 1103 1104 int BoUpSLP::getFirstUserIndex(ArrayRef<Value *> VL) { 1105 BasicBlock *BB = getSameBlock(VL); 1106 assert(BB && "All instructions must come from the same block"); 1107 BlockNumbering &BN = BlocksNumbers[BB]; 1108 1109 // Find the first user of the values. 1110 int FirstUser = BN.getIndex(BB->getTerminator()); 1111 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 1112 for (Value::use_iterator U = VL[i]->use_begin(), UE = VL[i]->use_end(); 1113 U != UE; ++U) { 1114 Instruction *Instr = dyn_cast<Instruction>(*U); 1115 1116 if (!Instr || Instr->getParent() != BB) 1117 continue; 1118 1119 FirstUser = std::min(FirstUser, BN.getIndex(Instr)); 1120 } 1121 } 1122 return FirstUser; 1123 } 1124 1125 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) { 1126 Value *Vec = UndefValue::get(Ty); 1127 // Generate the 'InsertElement' instruction. 1128 for (unsigned i = 0; i < Ty->getNumElements(); ++i) { 1129 Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i)); 1130 if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) { 1131 GatherSeq.insert(Insrt); 1132 1133 // Add to our 'need-to-extract' list. 1134 if (ScalarToTreeEntry.count(VL[i])) { 1135 int Idx = ScalarToTreeEntry[VL[i]]; 1136 TreeEntry *E = &VectorizableTree[Idx]; 1137 // Find which lane we need to extract. 1138 int FoundLane = -1; 1139 for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) { 1140 // Is this the lane of the scalar that we are looking for ? 1141 if (E->Scalars[Lane] == VL[i]) { 1142 FoundLane = Lane; 1143 break; 1144 } 1145 } 1146 assert(FoundLane >= 0 && "Could not find the correct lane"); 1147 ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane)); 1148 } 1149 } 1150 } 1151 1152 return Vec; 1153 } 1154 1155 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 1156 if (ScalarToTreeEntry.count(VL[0])) { 1157 int Idx = ScalarToTreeEntry[VL[0]]; 1158 TreeEntry *E = &VectorizableTree[Idx]; 1159 if (E->isSame(VL)) 1160 return vectorizeTree(E); 1161 } 1162 1163 Type *ScalarTy = VL[0]->getType(); 1164 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 1165 ScalarTy = SI->getValueOperand()->getType(); 1166 VectorType *VecTy = VectorType::get(ScalarTy, VL.size()); 1167 1168 return Gather(VL, VecTy); 1169 } 1170 1171 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 1172 BuilderLocGuard Guard(Builder); 1173 1174 if (E->VectorizedValue) { 1175 DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 1176 return E->VectorizedValue; 1177 } 1178 1179 Type *ScalarTy = E->Scalars[0]->getType(); 1180 if (StoreInst *SI = dyn_cast<StoreInst>(E->Scalars[0])) 1181 ScalarTy = SI->getValueOperand()->getType(); 1182 VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size()); 1183 1184 if (E->NeedToGather) { 1185 return Gather(E->Scalars, VecTy); 1186 } 1187 1188 Instruction *VL0 = cast<Instruction>(E->Scalars[0]); 1189 unsigned Opcode = VL0->getOpcode(); 1190 assert(Opcode == getSameOpcode(E->Scalars) && "Invalid opcode"); 1191 1192 switch (Opcode) { 1193 case Instruction::PHI: { 1194 PHINode *PH = dyn_cast<PHINode>(VL0); 1195 Builder.SetInsertPoint(PH->getParent()->getFirstInsertionPt()); 1196 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 1197 E->VectorizedValue = NewPhi; 1198 1199 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 1200 ValueList Operands; 1201 BasicBlock *IBB = PH->getIncomingBlock(i); 1202 1203 // Prepare the operand vector. 1204 for (unsigned j = 0; j < E->Scalars.size(); ++j) 1205 Operands.push_back(cast<PHINode>(E->Scalars[j])-> 1206 getIncomingValueForBlock(IBB)); 1207 1208 Builder.SetInsertPoint(IBB->getTerminator()); 1209 Value *Vec = vectorizeTree(Operands); 1210 NewPhi->addIncoming(Vec, IBB); 1211 } 1212 1213 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 1214 "Invalid number of incoming values"); 1215 return NewPhi; 1216 } 1217 1218 case Instruction::ExtractElement: { 1219 if (CanReuseExtract(E->Scalars)) { 1220 Value *V = VL0->getOperand(0); 1221 E->VectorizedValue = V; 1222 return V; 1223 } 1224 return Gather(E->Scalars, VecTy); 1225 } 1226 case Instruction::ZExt: 1227 case Instruction::SExt: 1228 case Instruction::FPToUI: 1229 case Instruction::FPToSI: 1230 case Instruction::FPExt: 1231 case Instruction::PtrToInt: 1232 case Instruction::IntToPtr: 1233 case Instruction::SIToFP: 1234 case Instruction::UIToFP: 1235 case Instruction::Trunc: 1236 case Instruction::FPTrunc: 1237 case Instruction::BitCast: { 1238 ValueList INVL; 1239 for (int i = 0, e = E->Scalars.size(); i < e; ++i) 1240 INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0)); 1241 1242 Builder.SetInsertPoint(getLastInstruction(E->Scalars)); 1243 Value *InVec = vectorizeTree(INVL); 1244 CastInst *CI = dyn_cast<CastInst>(VL0); 1245 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 1246 E->VectorizedValue = V; 1247 return V; 1248 } 1249 case Instruction::FCmp: 1250 case Instruction::ICmp: { 1251 ValueList LHSV, RHSV; 1252 for (int i = 0, e = E->Scalars.size(); i < e; ++i) { 1253 LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0)); 1254 RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1)); 1255 } 1256 1257 Builder.SetInsertPoint(getLastInstruction(E->Scalars)); 1258 Value *L = vectorizeTree(LHSV); 1259 Value *R = vectorizeTree(RHSV); 1260 Value *V; 1261 1262 CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate(); 1263 if (Opcode == Instruction::FCmp) 1264 V = Builder.CreateFCmp(P0, L, R); 1265 else 1266 V = Builder.CreateICmp(P0, L, R); 1267 1268 E->VectorizedValue = V; 1269 return V; 1270 } 1271 case Instruction::Select: { 1272 ValueList TrueVec, FalseVec, CondVec; 1273 for (int i = 0, e = E->Scalars.size(); i < e; ++i) { 1274 CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0)); 1275 TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1)); 1276 FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2)); 1277 } 1278 1279 Builder.SetInsertPoint(getLastInstruction(E->Scalars)); 1280 Value *Cond = vectorizeTree(CondVec); 1281 Value *True = vectorizeTree(TrueVec); 1282 Value *False = vectorizeTree(FalseVec); 1283 Value *V = Builder.CreateSelect(Cond, True, False); 1284 E->VectorizedValue = V; 1285 return V; 1286 } 1287 case Instruction::Add: 1288 case Instruction::FAdd: 1289 case Instruction::Sub: 1290 case Instruction::FSub: 1291 case Instruction::Mul: 1292 case Instruction::FMul: 1293 case Instruction::UDiv: 1294 case Instruction::SDiv: 1295 case Instruction::FDiv: 1296 case Instruction::URem: 1297 case Instruction::SRem: 1298 case Instruction::FRem: 1299 case Instruction::Shl: 1300 case Instruction::LShr: 1301 case Instruction::AShr: 1302 case Instruction::And: 1303 case Instruction::Or: 1304 case Instruction::Xor: { 1305 ValueList LHSVL, RHSVL; 1306 for (int i = 0, e = E->Scalars.size(); i < e; ++i) { 1307 LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0)); 1308 RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1)); 1309 } 1310 1311 Builder.SetInsertPoint(getLastInstruction(E->Scalars)); 1312 Value *LHS = vectorizeTree(LHSVL); 1313 Value *RHS = vectorizeTree(RHSVL); 1314 1315 if (LHS == RHS && isa<Instruction>(LHS)) { 1316 assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order"); 1317 } 1318 1319 BinaryOperator *BinOp = cast<BinaryOperator>(VL0); 1320 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS); 1321 E->VectorizedValue = V; 1322 return V; 1323 } 1324 case Instruction::Load: { 1325 // Loads are inserted at the head of the tree because we don't want to 1326 // sink them all the way down past store instructions. 1327 Builder.SetInsertPoint(getLastInstruction(E->Scalars)); 1328 LoadInst *LI = cast<LoadInst>(VL0); 1329 Value *VecPtr = 1330 Builder.CreateBitCast(LI->getPointerOperand(), VecTy->getPointerTo()); 1331 unsigned Alignment = LI->getAlignment(); 1332 LI = Builder.CreateLoad(VecPtr); 1333 LI->setAlignment(Alignment); 1334 E->VectorizedValue = LI; 1335 return LI; 1336 } 1337 case Instruction::Store: { 1338 StoreInst *SI = cast<StoreInst>(VL0); 1339 unsigned Alignment = SI->getAlignment(); 1340 1341 ValueList ValueOp; 1342 for (int i = 0, e = E->Scalars.size(); i < e; ++i) 1343 ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand()); 1344 1345 Builder.SetInsertPoint(getLastInstruction(E->Scalars)); 1346 Value *VecValue = vectorizeTree(ValueOp); 1347 Value *VecPtr = 1348 Builder.CreateBitCast(SI->getPointerOperand(), VecTy->getPointerTo()); 1349 StoreInst *S = Builder.CreateStore(VecValue, VecPtr); 1350 S->setAlignment(Alignment); 1351 E->VectorizedValue = S; 1352 return S; 1353 } 1354 default: 1355 llvm_unreachable("unknown inst"); 1356 } 1357 return 0; 1358 } 1359 1360 void BoUpSLP::vectorizeTree() { 1361 Builder.SetInsertPoint(F->getEntryBlock().begin()); 1362 vectorizeTree(&VectorizableTree[0]); 1363 1364 DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n"); 1365 1366 // Extract all of the elements with the external uses. 1367 for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end(); 1368 it != e; ++it) { 1369 Value *Scalar = it->Scalar; 1370 llvm::User *User = it->User; 1371 1372 // Skip users that we already RAUW. This happens when one instruction 1373 // has multiple uses of the same value. 1374 if (std::find(Scalar->use_begin(), Scalar->use_end(), User) == 1375 Scalar->use_end()) 1376 continue; 1377 assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar"); 1378 1379 int Idx = ScalarToTreeEntry[Scalar]; 1380 TreeEntry *E = &VectorizableTree[Idx]; 1381 assert(!E->NeedToGather && "Extracting from a gather list"); 1382 1383 Value *Vec = E->VectorizedValue; 1384 assert(Vec && "Can't find vectorizable value"); 1385 1386 // Generate extracts for out-of-tree users. 1387 // Find the insertion point for the extractelement lane. 1388 Instruction *Loc = 0; 1389 if (PHINode *PN = dyn_cast<PHINode>(Vec)) { 1390 Loc = PN->getParent()->getFirstInsertionPt(); 1391 } else if (isa<Instruction>(Vec)){ 1392 if (PHINode *PH = dyn_cast<PHINode>(User)) { 1393 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 1394 if (PH->getIncomingValue(i) == Scalar) { 1395 Loc = PH->getIncomingBlock(i)->getTerminator(); 1396 break; 1397 } 1398 } 1399 assert(Loc && "Unable to find incoming value for the PHI"); 1400 } else { 1401 Loc = cast<Instruction>(User); 1402 } 1403 } else { 1404 Loc = F->getEntryBlock().begin(); 1405 } 1406 1407 Builder.SetInsertPoint(Loc); 1408 Value *Ex = Builder.CreateExtractElement(Vec, Builder.getInt32(it->Lane)); 1409 User->replaceUsesOfWith(Scalar, Ex); 1410 DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 1411 } 1412 1413 // For each vectorized value: 1414 for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) { 1415 TreeEntry *Entry = &VectorizableTree[EIdx]; 1416 1417 // For each lane: 1418 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 1419 Value *Scalar = Entry->Scalars[Lane]; 1420 1421 // No need to handle users of gathered values. 1422 if (Entry->NeedToGather) 1423 continue; 1424 1425 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 1426 1427 Type *Ty = Scalar->getType(); 1428 if (!Ty->isVoidTy()) { 1429 for (Value::use_iterator User = Scalar->use_begin(), UE = Scalar->use_end(); 1430 User != UE; ++User) { 1431 DEBUG(dbgs() << "SLP: \tvalidating user:" << **User << ".\n"); 1432 assert(!MustGather.count(*User) && 1433 "Replacing gathered value with undef"); 1434 assert(ScalarToTreeEntry.count(*User) && 1435 "Replacing out-of-tree value with undef"); 1436 } 1437 Value *Undef = UndefValue::get(Ty); 1438 Scalar->replaceAllUsesWith(Undef); 1439 } 1440 DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 1441 cast<Instruction>(Scalar)->eraseFromParent(); 1442 } 1443 } 1444 1445 for (Function::iterator it = F->begin(), e = F->end(); it != e; ++it) { 1446 BlocksNumbers[it].forget(); 1447 } 1448 Builder.ClearInsertionPoint(); 1449 } 1450 1451 void BoUpSLP::optimizeGatherSequence() { 1452 DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size() 1453 << " gather sequences instructions.\n"); 1454 // LICM InsertElementInst sequences. 1455 for (SetVector<Instruction *>::iterator it = GatherSeq.begin(), 1456 e = GatherSeq.end(); it != e; ++it) { 1457 InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it); 1458 1459 if (!Insert) 1460 continue; 1461 1462 // Check if this block is inside a loop. 1463 Loop *L = LI->getLoopFor(Insert->getParent()); 1464 if (!L) 1465 continue; 1466 1467 // Check if it has a preheader. 1468 BasicBlock *PreHeader = L->getLoopPreheader(); 1469 if (!PreHeader) 1470 continue; 1471 1472 // If the vector or the element that we insert into it are 1473 // instructions that are defined in this basic block then we can't 1474 // hoist this instruction. 1475 Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0)); 1476 Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1)); 1477 if (CurrVec && L->contains(CurrVec)) 1478 continue; 1479 if (NewElem && L->contains(NewElem)) 1480 continue; 1481 1482 // We can hoist this instruction. Move it to the pre-header. 1483 Insert->moveBefore(PreHeader->getTerminator()); 1484 } 1485 1486 // Perform O(N^2) search over the gather sequences and merge identical 1487 // instructions. TODO: We can further optimize this scan if we split the 1488 // instructions into different buckets based on the insert lane. 1489 SmallPtrSet<Instruction*, 16> Visited; 1490 SmallVector<Instruction*, 16> ToRemove; 1491 ReversePostOrderTraversal<Function*> RPOT(F); 1492 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(), 1493 E = RPOT.end(); I != E; ++I) { 1494 BasicBlock *BB = *I; 1495 // For all instructions in the function: 1496 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 1497 Instruction *In = it; 1498 if ((!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In)) || 1499 !GatherSeq.count(In)) 1500 continue; 1501 1502 // Check if we can replace this instruction with any of the 1503 // visited instructions. 1504 for (SmallPtrSet<Instruction*, 16>::iterator v = Visited.begin(), 1505 ve = Visited.end(); v != ve; ++v) { 1506 if (In->isIdenticalTo(*v) && 1507 DT->dominates((*v)->getParent(), In->getParent())) { 1508 In->replaceAllUsesWith(*v); 1509 ToRemove.push_back(In); 1510 In = 0; 1511 break; 1512 } 1513 } 1514 if (In) 1515 Visited.insert(In); 1516 } 1517 } 1518 1519 // Erase all of the instructions that we RAUWed. 1520 for (SmallVectorImpl<Instruction *>::iterator v = ToRemove.begin(), 1521 ve = ToRemove.end(); v != ve; ++v) { 1522 assert((*v)->getNumUses() == 0 && "Can't remove instructions with uses"); 1523 (*v)->eraseFromParent(); 1524 } 1525 } 1526 1527 /// The SLPVectorizer Pass. 1528 struct SLPVectorizer : public FunctionPass { 1529 typedef SmallVector<StoreInst *, 8> StoreList; 1530 typedef MapVector<Value *, StoreList> StoreListMap; 1531 1532 /// Pass identification, replacement for typeid 1533 static char ID; 1534 1535 explicit SLPVectorizer() : FunctionPass(ID) { 1536 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 1537 } 1538 1539 ScalarEvolution *SE; 1540 DataLayout *DL; 1541 TargetTransformInfo *TTI; 1542 AliasAnalysis *AA; 1543 LoopInfo *LI; 1544 DominatorTree *DT; 1545 1546 virtual bool runOnFunction(Function &F) { 1547 SE = &getAnalysis<ScalarEvolution>(); 1548 DL = getAnalysisIfAvailable<DataLayout>(); 1549 TTI = &getAnalysis<TargetTransformInfo>(); 1550 AA = &getAnalysis<AliasAnalysis>(); 1551 LI = &getAnalysis<LoopInfo>(); 1552 DT = &getAnalysis<DominatorTree>(); 1553 1554 StoreRefs.clear(); 1555 bool Changed = false; 1556 1557 // Must have DataLayout. We can't require it because some tests run w/o 1558 // triple. 1559 if (!DL) 1560 return false; 1561 1562 DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 1563 1564 // Use the bollom up slp vectorizer to construct chains that start with 1565 // he store instructions. 1566 BoUpSLP R(&F, SE, DL, TTI, AA, LI, DT); 1567 1568 // Scan the blocks in the function in post order. 1569 for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()), 1570 e = po_end(&F.getEntryBlock()); it != e; ++it) { 1571 BasicBlock *BB = *it; 1572 1573 // Vectorize trees that end at stores. 1574 if (unsigned count = collectStores(BB, R)) { 1575 (void)count; 1576 DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n"); 1577 Changed |= vectorizeStoreChains(R); 1578 } 1579 1580 // Vectorize trees that end at reductions. 1581 Changed |= vectorizeChainsInBlock(BB, R); 1582 } 1583 1584 if (Changed) { 1585 R.optimizeGatherSequence(); 1586 DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 1587 DEBUG(verifyFunction(F)); 1588 } 1589 return Changed; 1590 } 1591 1592 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 1593 FunctionPass::getAnalysisUsage(AU); 1594 AU.addRequired<ScalarEvolution>(); 1595 AU.addRequired<AliasAnalysis>(); 1596 AU.addRequired<TargetTransformInfo>(); 1597 AU.addRequired<LoopInfo>(); 1598 AU.addRequired<DominatorTree>(); 1599 AU.addPreserved<LoopInfo>(); 1600 AU.addPreserved<DominatorTree>(); 1601 AU.setPreservesCFG(); 1602 } 1603 1604 private: 1605 1606 /// \brief Collect memory references and sort them according to their base 1607 /// object. We sort the stores to their base objects to reduce the cost of the 1608 /// quadratic search on the stores. TODO: We can further reduce this cost 1609 /// if we flush the chain creation every time we run into a memory barrier. 1610 unsigned collectStores(BasicBlock *BB, BoUpSLP &R); 1611 1612 /// \brief Try to vectorize a chain that starts at two arithmetic instrs. 1613 bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R); 1614 1615 /// \brief Try to vectorize a list of operands. 1616 /// \returns true if a value was vectorized. 1617 bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R); 1618 1619 /// \brief Try to vectorize a chain that may start at the operands of \V; 1620 bool tryToVectorize(BinaryOperator *V, BoUpSLP &R); 1621 1622 /// \brief Vectorize the stores that were collected in StoreRefs. 1623 bool vectorizeStoreChains(BoUpSLP &R); 1624 1625 /// \brief Scan the basic block and look for patterns that are likely to start 1626 /// a vectorization chain. 1627 bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R); 1628 1629 bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold, 1630 BoUpSLP &R); 1631 1632 bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold, 1633 BoUpSLP &R); 1634 private: 1635 StoreListMap StoreRefs; 1636 }; 1637 1638 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain, 1639 int CostThreshold, BoUpSLP &R) { 1640 unsigned ChainLen = Chain.size(); 1641 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen 1642 << "\n"); 1643 Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType(); 1644 unsigned Sz = DL->getTypeSizeInBits(StoreTy); 1645 unsigned VF = MinVecRegSize / Sz; 1646 1647 if (!isPowerOf2_32(Sz) || VF < 2) 1648 return false; 1649 1650 bool Changed = false; 1651 // Look for profitable vectorizable trees at all offsets, starting at zero. 1652 for (unsigned i = 0, e = ChainLen; i < e; ++i) { 1653 if (i + VF > e) 1654 break; 1655 DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i 1656 << "\n"); 1657 ArrayRef<Value *> Operands = Chain.slice(i, VF); 1658 1659 R.buildTree(Operands); 1660 1661 int Cost = R.getTreeCost(); 1662 1663 DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n"); 1664 if (Cost < CostThreshold) { 1665 DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n"); 1666 R.vectorizeTree(); 1667 1668 // Move to the next bundle. 1669 i += VF - 1; 1670 Changed = true; 1671 } 1672 } 1673 1674 if (Changed || ChainLen > VF) 1675 return Changed; 1676 1677 // Handle short chains. This helps us catch types such as <3 x float> that 1678 // are smaller than vector size. 1679 R.buildTree(Chain); 1680 1681 int Cost = R.getTreeCost(); 1682 1683 if (Cost < CostThreshold) { 1684 DEBUG(dbgs() << "SLP: Found store chain cost = " << Cost 1685 << " for size = " << ChainLen << "\n"); 1686 R.vectorizeTree(); 1687 return true; 1688 } 1689 1690 return false; 1691 } 1692 1693 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores, 1694 int costThreshold, BoUpSLP &R) { 1695 SetVector<Value *> Heads, Tails; 1696 SmallDenseMap<Value *, Value *> ConsecutiveChain; 1697 1698 // We may run into multiple chains that merge into a single chain. We mark the 1699 // stores that we vectorized so that we don't visit the same store twice. 1700 BoUpSLP::ValueSet VectorizedStores; 1701 bool Changed = false; 1702 1703 // Do a quadratic search on all of the given stores and find 1704 // all of the pairs of stores that follow each other. 1705 for (unsigned i = 0, e = Stores.size(); i < e; ++i) { 1706 if (Heads.count(Stores[i])) 1707 continue; 1708 for (unsigned j = 0; j < e; ++j) { 1709 if (i == j || Tails.count(Stores[j])) 1710 continue; 1711 1712 if (R.isConsecutiveAccess(Stores[i], Stores[j])) { 1713 Tails.insert(Stores[j]); 1714 Heads.insert(Stores[i]); 1715 ConsecutiveChain[Stores[i]] = Stores[j]; 1716 } 1717 } 1718 } 1719 1720 // For stores that start but don't end a link in the chain: 1721 for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end(); 1722 it != e; ++it) { 1723 if (Tails.count(*it)) 1724 continue; 1725 1726 // We found a store instr that starts a chain. Now follow the chain and try 1727 // to vectorize it. 1728 BoUpSLP::ValueList Operands; 1729 Value *I = *it; 1730 // Collect the chain into a list. 1731 while (Tails.count(I) || Heads.count(I)) { 1732 if (VectorizedStores.count(I)) 1733 break; 1734 Operands.push_back(I); 1735 // Move to the next value in the chain. 1736 I = ConsecutiveChain[I]; 1737 } 1738 1739 bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R); 1740 1741 // Mark the vectorized stores so that we don't vectorize them again. 1742 if (Vectorized) 1743 VectorizedStores.insert(Operands.begin(), Operands.end()); 1744 Changed |= Vectorized; 1745 } 1746 1747 return Changed; 1748 } 1749 1750 1751 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) { 1752 unsigned count = 0; 1753 StoreRefs.clear(); 1754 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 1755 StoreInst *SI = dyn_cast<StoreInst>(it); 1756 if (!SI) 1757 continue; 1758 1759 // Check that the pointer points to scalars. 1760 Type *Ty = SI->getValueOperand()->getType(); 1761 if (Ty->isAggregateType() || Ty->isVectorTy()) 1762 return 0; 1763 1764 // Find the base of the GEP. 1765 Value *Ptr = SI->getPointerOperand(); 1766 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) 1767 Ptr = GEP->getPointerOperand(); 1768 1769 // Save the store locations. 1770 StoreRefs[Ptr].push_back(SI); 1771 count++; 1772 } 1773 return count; 1774 } 1775 1776 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 1777 if (!A || !B) 1778 return false; 1779 Value *VL[] = { A, B }; 1780 return tryToVectorizeList(VL, R); 1781 } 1782 1783 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R) { 1784 if (VL.size() < 2) 1785 return false; 1786 1787 DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n"); 1788 1789 // Check that all of the parts are scalar instructions of the same type. 1790 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 1791 if (!I0) 1792 return 0; 1793 1794 unsigned Opcode0 = I0->getOpcode(); 1795 1796 for (int i = 0, e = VL.size(); i < e; ++i) { 1797 Type *Ty = VL[i]->getType(); 1798 if (Ty->isAggregateType() || Ty->isVectorTy()) 1799 return 0; 1800 Instruction *Inst = dyn_cast<Instruction>(VL[i]); 1801 if (!Inst || Inst->getOpcode() != Opcode0) 1802 return 0; 1803 } 1804 1805 R.buildTree(VL); 1806 int Cost = R.getTreeCost(); 1807 1808 if (Cost >= -SLPCostThreshold) 1809 return false; 1810 1811 DEBUG(dbgs() << "SLP: Vectorizing pair at cost:" << Cost << ".\n"); 1812 R.vectorizeTree(); 1813 return true; 1814 } 1815 1816 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) { 1817 if (!V) 1818 return false; 1819 1820 // Try to vectorize V. 1821 if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R)) 1822 return true; 1823 1824 BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0)); 1825 BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1)); 1826 // Try to skip B. 1827 if (B && B->hasOneUse()) { 1828 BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 1829 BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 1830 if (tryToVectorizePair(A, B0, R)) { 1831 B->moveBefore(V); 1832 return true; 1833 } 1834 if (tryToVectorizePair(A, B1, R)) { 1835 B->moveBefore(V); 1836 return true; 1837 } 1838 } 1839 1840 // Try to skip A. 1841 if (A && A->hasOneUse()) { 1842 BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 1843 BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 1844 if (tryToVectorizePair(A0, B, R)) { 1845 A->moveBefore(V); 1846 return true; 1847 } 1848 if (tryToVectorizePair(A1, B, R)) { 1849 A->moveBefore(V); 1850 return true; 1851 } 1852 } 1853 return 0; 1854 } 1855 1856 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 1857 bool Changed = false; 1858 SmallVector<Value *, 4> Incoming; 1859 // Collect the incoming values from the PHIs. 1860 for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie; 1861 ++instr) { 1862 PHINode *P = dyn_cast<PHINode>(instr); 1863 1864 if (!P) 1865 break; 1866 1867 // Stop constructing the list when you reach a different type. 1868 if (Incoming.size() && P->getType() != Incoming[0]->getType()) { 1869 Changed |= tryToVectorizeList(Incoming, R); 1870 Incoming.clear(); 1871 } 1872 1873 Incoming.push_back(P); 1874 } 1875 1876 if (Incoming.size() > 1) 1877 Changed |= tryToVectorizeList(Incoming, R); 1878 1879 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 1880 if (isa<DbgInfoIntrinsic>(it)) 1881 continue; 1882 1883 // Try to vectorize reductions that use PHINodes. 1884 if (PHINode *P = dyn_cast<PHINode>(it)) { 1885 // Check that the PHI is a reduction PHI. 1886 if (P->getNumIncomingValues() != 2) 1887 return Changed; 1888 Value *Rdx = 1889 (P->getIncomingBlock(0) == BB 1890 ? (P->getIncomingValue(0)) 1891 : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1) : 0)); 1892 // Check if this is a Binary Operator. 1893 BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx); 1894 if (!BI) 1895 continue; 1896 1897 Value *Inst = BI->getOperand(0); 1898 if (Inst == P) 1899 Inst = BI->getOperand(1); 1900 1901 Changed |= tryToVectorize(dyn_cast<BinaryOperator>(Inst), R); 1902 continue; 1903 } 1904 1905 // Try to vectorize trees that start at compare instructions. 1906 if (CmpInst *CI = dyn_cast<CmpInst>(it)) { 1907 if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) { 1908 Changed |= true; 1909 continue; 1910 } 1911 for (int i = 0; i < 2; ++i) 1912 if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) 1913 Changed |= 1914 tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R); 1915 continue; 1916 } 1917 } 1918 1919 return Changed; 1920 } 1921 1922 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) { 1923 bool Changed = false; 1924 // Attempt to sort and vectorize each of the store-groups. 1925 for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end(); 1926 it != e; ++it) { 1927 if (it->second.size() < 2) 1928 continue; 1929 1930 DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 1931 << it->second.size() << ".\n"); 1932 1933 // Process the stores in chunks of 16. 1934 for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) { 1935 unsigned Len = std::min<unsigned>(CE - CI, 16); 1936 ArrayRef<StoreInst *> Chunk(&it->second[CI], Len); 1937 Changed |= vectorizeStores(Chunk, -SLPCostThreshold, R); 1938 } 1939 } 1940 return Changed; 1941 } 1942 1943 } // end anonymous namespace 1944 1945 char SLPVectorizer::ID = 0; 1946 static const char lv_name[] = "SLP Vectorizer"; 1947 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 1948 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 1949 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 1950 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 1951 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 1952 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 1953 1954 namespace llvm { 1955 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); } 1956 } 1957