1 //===------- VectorCombine.cpp - Optimize partial vector operations -------===// 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 optimizes scalar/vector interactions using target cost models. The 10 // transforms implemented here may not fit in traditional loop-based or SLP 11 // vectorization passes. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Vectorize/VectorCombine.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/BasicAliasAnalysis.h" 18 #include "llvm/Analysis/GlobalsModRef.h" 19 #include "llvm/Analysis/Loads.h" 20 #include "llvm/Analysis/TargetTransformInfo.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/Analysis/VectorUtils.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/IRBuilder.h" 26 #include "llvm/IR/PatternMatch.h" 27 #include "llvm/InitializePasses.h" 28 #include "llvm/Pass.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Transforms/Utils/Local.h" 31 #include "llvm/Transforms/Vectorize.h" 32 33 using namespace llvm; 34 using namespace llvm::PatternMatch; 35 36 #define DEBUG_TYPE "vector-combine" 37 STATISTIC(NumVecLoad, "Number of vector loads formed"); 38 STATISTIC(NumVecCmp, "Number of vector compares formed"); 39 STATISTIC(NumVecBO, "Number of vector binops formed"); 40 STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed"); 41 STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast"); 42 STATISTIC(NumScalarBO, "Number of scalar binops formed"); 43 STATISTIC(NumScalarCmp, "Number of scalar compares formed"); 44 45 static cl::opt<bool> DisableVectorCombine( 46 "disable-vector-combine", cl::init(false), cl::Hidden, 47 cl::desc("Disable all vector combine transforms")); 48 49 static cl::opt<bool> DisableBinopExtractShuffle( 50 "disable-binop-extract-shuffle", cl::init(false), cl::Hidden, 51 cl::desc("Disable binop extract to shuffle transforms")); 52 53 static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max(); 54 55 namespace { 56 class VectorCombine { 57 public: 58 VectorCombine(Function &F, const TargetTransformInfo &TTI, 59 const DominatorTree &DT) 60 : F(F), Builder(F.getContext()), TTI(TTI), DT(DT) {} 61 62 bool run(); 63 64 private: 65 Function &F; 66 IRBuilder<> Builder; 67 const TargetTransformInfo &TTI; 68 const DominatorTree &DT; 69 70 bool vectorizeLoadInsert(Instruction &I); 71 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0, 72 ExtractElementInst *Ext1, 73 unsigned PreferredExtractIndex) const; 74 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 75 unsigned Opcode, 76 ExtractElementInst *&ConvertToShuffle, 77 unsigned PreferredExtractIndex); 78 void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 79 Instruction &I); 80 void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 81 Instruction &I); 82 bool foldExtractExtract(Instruction &I); 83 bool foldBitcastShuf(Instruction &I); 84 bool scalarizeBinopOrCmp(Instruction &I); 85 bool foldExtractedCmps(Instruction &I); 86 }; 87 } // namespace 88 89 static void replaceValue(Value &Old, Value &New) { 90 Old.replaceAllUsesWith(&New); 91 New.takeName(&Old); 92 } 93 94 bool VectorCombine::vectorizeLoadInsert(Instruction &I) { 95 // Match insert of scalar load. 96 Value *Scalar; 97 if (!match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt()))) 98 return false; 99 auto *Load = dyn_cast<LoadInst>(Scalar); 100 Type *ScalarTy = Scalar->getType(); 101 if (!Load || !Load->isSimple()) 102 return false; 103 auto *Ty = dyn_cast<FixedVectorType>(I.getType()); 104 if (!Ty) 105 return false; 106 107 // TODO: Extend this to match GEP with constant offsets. 108 Value *PtrOp = Load->getPointerOperand()->stripPointerCasts(); 109 assert(isa<PointerType>(PtrOp->getType()) && "Expected a pointer type"); 110 111 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth(); 112 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits(); 113 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0) 114 return false; 115 116 // Check safety of replacing the scalar load with a larger vector load. 117 unsigned MinVecNumElts = MinVectorSize / ScalarSize; 118 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false); 119 Align Alignment = Load->getAlign(); 120 const DataLayout &DL = I.getModule()->getDataLayout(); 121 if (!isSafeToLoadUnconditionally(PtrOp, MinVecTy, Alignment, DL, Load, &DT)) 122 return false; 123 124 unsigned AS = Load->getPointerAddressSpace(); 125 126 // Original pattern: insertelt undef, load [free casts of] ScalarPtr, 0 127 int OldCost = TTI.getMemoryOpCost(Instruction::Load, ScalarTy, Alignment, AS); 128 APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0); 129 OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts, true, false); 130 131 // New pattern: load VecPtr 132 int NewCost = TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS); 133 134 // We can aggressively convert to the vector form because the backend can 135 // invert this transform if it does not result in a performance win. 136 if (OldCost < NewCost) 137 return false; 138 139 // It is safe and potentially profitable to load a vector directly: 140 // inselt undef, load Scalar, 0 --> load VecPtr 141 IRBuilder<> Builder(Load); 142 Value *CastedPtr = Builder.CreateBitCast(PtrOp, MinVecTy->getPointerTo(AS)); 143 Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment); 144 145 // If the insert type does not match the target's minimum vector type, 146 // use an identity shuffle to shrink/grow the vector. 147 if (Ty != MinVecTy) { 148 unsigned OutputNumElts = Ty->getNumElements(); 149 SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem); 150 for (unsigned i = 0; i < OutputNumElts && i < MinVecNumElts; ++i) 151 Mask[i] = i; 152 VecLd = Builder.CreateShuffleVector(VecLd, UndefValue::get(MinVecTy), Mask); 153 } 154 replaceValue(I, *VecLd); 155 ++NumVecLoad; 156 return true; 157 } 158 159 /// Determine which, if any, of the inputs should be replaced by a shuffle 160 /// followed by extract from a different index. 161 ExtractElementInst *VectorCombine::getShuffleExtract( 162 ExtractElementInst *Ext0, ExtractElementInst *Ext1, 163 unsigned PreferredExtractIndex = InvalidIndex) const { 164 assert(isa<ConstantInt>(Ext0->getIndexOperand()) && 165 isa<ConstantInt>(Ext1->getIndexOperand()) && 166 "Expected constant extract indexes"); 167 168 unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue(); 169 unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue(); 170 171 // If the extract indexes are identical, no shuffle is needed. 172 if (Index0 == Index1) 173 return nullptr; 174 175 Type *VecTy = Ext0->getVectorOperand()->getType(); 176 assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types"); 177 int Cost0 = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0); 178 int Cost1 = TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1); 179 180 // We are extracting from 2 different indexes, so one operand must be shuffled 181 // before performing a vector operation and/or extract. The more expensive 182 // extract will be replaced by a shuffle. 183 if (Cost0 > Cost1) 184 return Ext0; 185 if (Cost1 > Cost0) 186 return Ext1; 187 188 // If the costs are equal and there is a preferred extract index, shuffle the 189 // opposite operand. 190 if (PreferredExtractIndex == Index0) 191 return Ext1; 192 if (PreferredExtractIndex == Index1) 193 return Ext0; 194 195 // Otherwise, replace the extract with the higher index. 196 return Index0 > Index1 ? Ext0 : Ext1; 197 } 198 199 /// Compare the relative costs of 2 extracts followed by scalar operation vs. 200 /// vector operation(s) followed by extract. Return true if the existing 201 /// instructions are cheaper than a vector alternative. Otherwise, return false 202 /// and if one of the extracts should be transformed to a shufflevector, set 203 /// \p ConvertToShuffle to that extract instruction. 204 bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0, 205 ExtractElementInst *Ext1, 206 unsigned Opcode, 207 ExtractElementInst *&ConvertToShuffle, 208 unsigned PreferredExtractIndex) { 209 assert(isa<ConstantInt>(Ext0->getOperand(1)) && 210 isa<ConstantInt>(Ext1->getOperand(1)) && 211 "Expected constant extract indexes"); 212 Type *ScalarTy = Ext0->getType(); 213 auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType()); 214 int ScalarOpCost, VectorOpCost; 215 216 // Get cost estimates for scalar and vector versions of the operation. 217 bool IsBinOp = Instruction::isBinaryOp(Opcode); 218 if (IsBinOp) { 219 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy); 220 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy); 221 } else { 222 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && 223 "Expected a compare"); 224 ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy, 225 CmpInst::makeCmpResultType(ScalarTy)); 226 VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy, 227 CmpInst::makeCmpResultType(VecTy)); 228 } 229 230 // Get cost estimates for the extract elements. These costs will factor into 231 // both sequences. 232 unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue(); 233 unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue(); 234 235 int Extract0Cost = 236 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index); 237 int Extract1Cost = 238 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index); 239 240 // A more expensive extract will always be replaced by a splat shuffle. 241 // For example, if Ext0 is more expensive: 242 // opcode (extelt V0, Ext0), (ext V1, Ext1) --> 243 // extelt (opcode (splat V0, Ext0), V1), Ext1 244 // TODO: Evaluate whether that always results in lowest cost. Alternatively, 245 // check the cost of creating a broadcast shuffle and shuffling both 246 // operands to element 0. 247 int CheapExtractCost = std::min(Extract0Cost, Extract1Cost); 248 249 // Extra uses of the extracts mean that we include those costs in the 250 // vector total because those instructions will not be eliminated. 251 int OldCost, NewCost; 252 if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) { 253 // Handle a special case. If the 2 extracts are identical, adjust the 254 // formulas to account for that. The extra use charge allows for either the 255 // CSE'd pattern or an unoptimized form with identical values: 256 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C 257 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2) 258 : !Ext0->hasOneUse() || !Ext1->hasOneUse(); 259 OldCost = CheapExtractCost + ScalarOpCost; 260 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost; 261 } else { 262 // Handle the general case. Each extract is actually a different value: 263 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C 264 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost; 265 NewCost = VectorOpCost + CheapExtractCost + 266 !Ext0->hasOneUse() * Extract0Cost + 267 !Ext1->hasOneUse() * Extract1Cost; 268 } 269 270 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex); 271 if (ConvertToShuffle) { 272 if (IsBinOp && DisableBinopExtractShuffle) 273 return true; 274 275 // If we are extracting from 2 different indexes, then one operand must be 276 // shuffled before performing the vector operation. The shuffle mask is 277 // undefined except for 1 lane that is being translated to the remaining 278 // extraction lane. Therefore, it is a splat shuffle. Ex: 279 // ShufMask = { undef, undef, 0, undef } 280 // TODO: The cost model has an option for a "broadcast" shuffle 281 // (splat-from-element-0), but no option for a more general splat. 282 NewCost += 283 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy); 284 } 285 286 // Aggressively form a vector op if the cost is equal because the transform 287 // may enable further optimization. 288 // Codegen can reverse this transform (scalarize) if it was not profitable. 289 return OldCost < NewCost; 290 } 291 292 /// Create a shuffle that translates (shifts) 1 element from the input vector 293 /// to a new element location. 294 static Value *createShiftShuffle(Value *Vec, unsigned OldIndex, 295 unsigned NewIndex, IRBuilder<> &Builder) { 296 // The shuffle mask is undefined except for 1 lane that is being translated 297 // to the new element index. Example for OldIndex == 2 and NewIndex == 0: 298 // ShufMask = { 2, undef, undef, undef } 299 auto *VecTy = cast<FixedVectorType>(Vec->getType()); 300 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem); 301 ShufMask[NewIndex] = OldIndex; 302 Value *Undef = UndefValue::get(VecTy); 303 return Builder.CreateShuffleVector(Vec, Undef, ShufMask, "shift"); 304 } 305 306 /// Given an extract element instruction with constant index operand, shuffle 307 /// the source vector (shift the scalar element) to a NewIndex for extraction. 308 /// Return null if the input can be constant folded, so that we are not creating 309 /// unnecessary instructions. 310 static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt, 311 unsigned NewIndex, 312 IRBuilder<> &Builder) { 313 // If the extract can be constant-folded, this code is unsimplified. Defer 314 // to other passes to handle that. 315 Value *X = ExtElt->getVectorOperand(); 316 Value *C = ExtElt->getIndexOperand(); 317 assert(isa<ConstantInt>(C) && "Expected a constant index operand"); 318 if (isa<Constant>(X)) 319 return nullptr; 320 321 Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(), 322 NewIndex, Builder); 323 return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex)); 324 } 325 326 /// Try to reduce extract element costs by converting scalar compares to vector 327 /// compares followed by extract. 328 /// cmp (ext0 V0, C), (ext1 V1, C) 329 void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0, 330 ExtractElementInst *Ext1, Instruction &I) { 331 assert(isa<CmpInst>(&I) && "Expected a compare"); 332 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() == 333 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() && 334 "Expected matching constant extract indexes"); 335 336 // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C 337 ++NumVecCmp; 338 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate(); 339 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand(); 340 Value *VecCmp = Builder.CreateCmp(Pred, V0, V1); 341 Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand()); 342 replaceValue(I, *NewExt); 343 } 344 345 /// Try to reduce extract element costs by converting scalar binops to vector 346 /// binops followed by extract. 347 /// bo (ext0 V0, C), (ext1 V1, C) 348 void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0, 349 ExtractElementInst *Ext1, Instruction &I) { 350 assert(isa<BinaryOperator>(&I) && "Expected a binary operator"); 351 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() == 352 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() && 353 "Expected matching constant extract indexes"); 354 355 // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C 356 ++NumVecBO; 357 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand(); 358 Value *VecBO = 359 Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1); 360 361 // All IR flags are safe to back-propagate because any potential poison 362 // created in unused vector elements is discarded by the extract. 363 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO)) 364 VecBOInst->copyIRFlags(&I); 365 366 Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand()); 367 replaceValue(I, *NewExt); 368 } 369 370 /// Match an instruction with extracted vector operands. 371 bool VectorCombine::foldExtractExtract(Instruction &I) { 372 // It is not safe to transform things like div, urem, etc. because we may 373 // create undefined behavior when executing those on unknown vector elements. 374 if (!isSafeToSpeculativelyExecute(&I)) 375 return false; 376 377 Instruction *I0, *I1; 378 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE; 379 if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) && 380 !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1)))) 381 return false; 382 383 Value *V0, *V1; 384 uint64_t C0, C1; 385 if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) || 386 !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) || 387 V0->getType() != V1->getType()) 388 return false; 389 390 // If the scalar value 'I' is going to be re-inserted into a vector, then try 391 // to create an extract to that same element. The extract/insert can be 392 // reduced to a "select shuffle". 393 // TODO: If we add a larger pattern match that starts from an insert, this 394 // probably becomes unnecessary. 395 auto *Ext0 = cast<ExtractElementInst>(I0); 396 auto *Ext1 = cast<ExtractElementInst>(I1); 397 uint64_t InsertIndex = InvalidIndex; 398 if (I.hasOneUse()) 399 match(I.user_back(), 400 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex))); 401 402 ExtractElementInst *ExtractToChange; 403 if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), ExtractToChange, 404 InsertIndex)) 405 return false; 406 407 if (ExtractToChange) { 408 unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0; 409 ExtractElementInst *NewExtract = 410 translateExtract(ExtractToChange, CheapExtractIdx, Builder); 411 if (!NewExtract) 412 return false; 413 if (ExtractToChange == Ext0) 414 Ext0 = NewExtract; 415 else 416 Ext1 = NewExtract; 417 } 418 419 if (Pred != CmpInst::BAD_ICMP_PREDICATE) 420 foldExtExtCmp(Ext0, Ext1, I); 421 else 422 foldExtExtBinop(Ext0, Ext1, I); 423 424 return true; 425 } 426 427 /// If this is a bitcast of a shuffle, try to bitcast the source vector to the 428 /// destination type followed by shuffle. This can enable further transforms by 429 /// moving bitcasts or shuffles together. 430 bool VectorCombine::foldBitcastShuf(Instruction &I) { 431 Value *V; 432 ArrayRef<int> Mask; 433 if (!match(&I, m_BitCast( 434 m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask)))))) 435 return false; 436 437 // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for 438 // scalable type is unknown; Second, we cannot reason if the narrowed shuffle 439 // mask for scalable type is a splat or not. 440 // 2) Disallow non-vector casts and length-changing shuffles. 441 // TODO: We could allow any shuffle. 442 auto *DestTy = dyn_cast<FixedVectorType>(I.getType()); 443 auto *SrcTy = dyn_cast<FixedVectorType>(V->getType()); 444 if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy) 445 return false; 446 447 // The new shuffle must not cost more than the old shuffle. The bitcast is 448 // moved ahead of the shuffle, so assume that it has the same cost as before. 449 if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) > 450 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy)) 451 return false; 452 453 unsigned DestNumElts = DestTy->getNumElements(); 454 unsigned SrcNumElts = SrcTy->getNumElements(); 455 SmallVector<int, 16> NewMask; 456 if (SrcNumElts <= DestNumElts) { 457 // The bitcast is from wide to narrow/equal elements. The shuffle mask can 458 // always be expanded to the equivalent form choosing narrower elements. 459 assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask"); 460 unsigned ScaleFactor = DestNumElts / SrcNumElts; 461 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask); 462 } else { 463 // The bitcast is from narrow elements to wide elements. The shuffle mask 464 // must choose consecutive elements to allow casting first. 465 assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask"); 466 unsigned ScaleFactor = SrcNumElts / DestNumElts; 467 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask)) 468 return false; 469 } 470 // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC' 471 ++NumShufOfBitcast; 472 Value *CastV = Builder.CreateBitCast(V, DestTy); 473 Value *Shuf = 474 Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask); 475 replaceValue(I, *Shuf); 476 return true; 477 } 478 479 /// Match a vector binop or compare instruction with at least one inserted 480 /// scalar operand and convert to scalar binop/cmp followed by insertelement. 481 bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) { 482 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE; 483 Value *Ins0, *Ins1; 484 if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) && 485 !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1)))) 486 return false; 487 488 // Do not convert the vector condition of a vector select into a scalar 489 // condition. That may cause problems for codegen because of differences in 490 // boolean formats and register-file transfers. 491 // TODO: Can we account for that in the cost model? 492 bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE; 493 if (IsCmp) 494 for (User *U : I.users()) 495 if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value()))) 496 return false; 497 498 // Match against one or both scalar values being inserted into constant 499 // vectors: 500 // vec_op VecC0, (inselt VecC1, V1, Index) 501 // vec_op (inselt VecC0, V0, Index), VecC1 502 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) 503 // TODO: Deal with mismatched index constants and variable indexes? 504 Constant *VecC0 = nullptr, *VecC1 = nullptr; 505 Value *V0 = nullptr, *V1 = nullptr; 506 uint64_t Index0 = 0, Index1 = 0; 507 if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0), 508 m_ConstantInt(Index0))) && 509 !match(Ins0, m_Constant(VecC0))) 510 return false; 511 if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1), 512 m_ConstantInt(Index1))) && 513 !match(Ins1, m_Constant(VecC1))) 514 return false; 515 516 bool IsConst0 = !V0; 517 bool IsConst1 = !V1; 518 if (IsConst0 && IsConst1) 519 return false; 520 if (!IsConst0 && !IsConst1 && Index0 != Index1) 521 return false; 522 523 // Bail for single insertion if it is a load. 524 // TODO: Handle this once getVectorInstrCost can cost for load/stores. 525 auto *I0 = dyn_cast_or_null<Instruction>(V0); 526 auto *I1 = dyn_cast_or_null<Instruction>(V1); 527 if ((IsConst0 && I1 && I1->mayReadFromMemory()) || 528 (IsConst1 && I0 && I0->mayReadFromMemory())) 529 return false; 530 531 uint64_t Index = IsConst0 ? Index1 : Index0; 532 Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType(); 533 Type *VecTy = I.getType(); 534 assert(VecTy->isVectorTy() && 535 (IsConst0 || IsConst1 || V0->getType() == V1->getType()) && 536 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() || 537 ScalarTy->isPointerTy()) && 538 "Unexpected types for insert element into binop or cmp"); 539 540 unsigned Opcode = I.getOpcode(); 541 int ScalarOpCost, VectorOpCost; 542 if (IsCmp) { 543 ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy); 544 VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy); 545 } else { 546 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy); 547 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy); 548 } 549 550 // Get cost estimate for the insert element. This cost will factor into 551 // both sequences. 552 int InsertCost = 553 TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index); 554 int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + 555 VectorOpCost; 556 int NewCost = ScalarOpCost + InsertCost + 557 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) + 558 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost); 559 560 // We want to scalarize unless the vector variant actually has lower cost. 561 if (OldCost < NewCost) 562 return false; 563 564 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) --> 565 // inselt NewVecC, (scalar_op V0, V1), Index 566 if (IsCmp) 567 ++NumScalarCmp; 568 else 569 ++NumScalarBO; 570 571 // For constant cases, extract the scalar element, this should constant fold. 572 if (IsConst0) 573 V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index)); 574 if (IsConst1) 575 V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index)); 576 577 Value *Scalar = 578 IsCmp ? Builder.CreateCmp(Pred, V0, V1) 579 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1); 580 581 Scalar->setName(I.getName() + ".scalar"); 582 583 // All IR flags are safe to back-propagate. There is no potential for extra 584 // poison to be created by the scalar instruction. 585 if (auto *ScalarInst = dyn_cast<Instruction>(Scalar)) 586 ScalarInst->copyIRFlags(&I); 587 588 // Fold the vector constants in the original vectors into a new base vector. 589 Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1) 590 : ConstantExpr::get(Opcode, VecC0, VecC1); 591 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index); 592 replaceValue(I, *Insert); 593 return true; 594 } 595 596 /// Try to combine a scalar binop + 2 scalar compares of extracted elements of 597 /// a vector into vector operations followed by extract. Note: The SLP pass 598 /// may miss this pattern because of implementation problems. 599 bool VectorCombine::foldExtractedCmps(Instruction &I) { 600 // We are looking for a scalar binop of booleans. 601 // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1) 602 if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1)) 603 return false; 604 605 // The compare predicates should match, and each compare should have a 606 // constant operand. 607 // TODO: Relax the one-use constraints. 608 Value *B0 = I.getOperand(0), *B1 = I.getOperand(1); 609 Instruction *I0, *I1; 610 Constant *C0, *C1; 611 CmpInst::Predicate P0, P1; 612 if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) || 613 !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) || 614 P0 != P1) 615 return false; 616 617 // The compare operands must be extracts of the same vector with constant 618 // extract indexes. 619 // TODO: Relax the one-use constraints. 620 Value *X; 621 uint64_t Index0, Index1; 622 if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) || 623 !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1))))) 624 return false; 625 626 auto *Ext0 = cast<ExtractElementInst>(I0); 627 auto *Ext1 = cast<ExtractElementInst>(I1); 628 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1); 629 if (!ConvertToShuf) 630 return false; 631 632 // The original scalar pattern is: 633 // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1) 634 CmpInst::Predicate Pred = P0; 635 unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp 636 : Instruction::ICmp; 637 auto *VecTy = dyn_cast<FixedVectorType>(X->getType()); 638 if (!VecTy) 639 return false; 640 641 int OldCost = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0); 642 OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1); 643 OldCost += TTI.getCmpSelInstrCost(CmpOpcode, I0->getType()) * 2; 644 OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType()); 645 646 // The proposed vector pattern is: 647 // vcmp = cmp Pred X, VecC 648 // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0 649 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0; 650 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1; 651 auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType())); 652 int NewCost = TTI.getCmpSelInstrCost(CmpOpcode, X->getType()); 653 NewCost += 654 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy); 655 NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy); 656 NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex); 657 658 // Aggressively form vector ops if the cost is equal because the transform 659 // may enable further optimization. 660 // Codegen can reverse this transform (scalarize) if it was not profitable. 661 if (OldCost < NewCost) 662 return false; 663 664 // Create a vector constant from the 2 scalar constants. 665 SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(), 666 UndefValue::get(VecTy->getElementType())); 667 CmpC[Index0] = C0; 668 CmpC[Index1] = C1; 669 Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC)); 670 671 Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder); 672 Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(), 673 VCmp, Shuf); 674 Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex); 675 replaceValue(I, *NewExt); 676 ++NumVecCmpBO; 677 return true; 678 } 679 680 /// This is the entry point for all transforms. Pass manager differences are 681 /// handled in the callers of this function. 682 bool VectorCombine::run() { 683 if (DisableVectorCombine) 684 return false; 685 686 // Don't attempt vectorization if the target does not support vectors. 687 if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true))) 688 return false; 689 690 bool MadeChange = false; 691 for (BasicBlock &BB : F) { 692 // Ignore unreachable basic blocks. 693 if (!DT.isReachableFromEntry(&BB)) 694 continue; 695 // Do not delete instructions under here and invalidate the iterator. 696 // Walk the block forwards to enable simple iterative chains of transforms. 697 // TODO: It could be more efficient to remove dead instructions 698 // iteratively in this loop rather than waiting until the end. 699 for (Instruction &I : BB) { 700 if (isa<DbgInfoIntrinsic>(I)) 701 continue; 702 Builder.SetInsertPoint(&I); 703 MadeChange |= vectorizeLoadInsert(I); 704 MadeChange |= foldExtractExtract(I); 705 MadeChange |= foldBitcastShuf(I); 706 MadeChange |= scalarizeBinopOrCmp(I); 707 MadeChange |= foldExtractedCmps(I); 708 } 709 } 710 711 // We're done with transforms, so remove dead instructions. 712 if (MadeChange) 713 for (BasicBlock &BB : F) 714 SimplifyInstructionsInBlock(&BB); 715 716 return MadeChange; 717 } 718 719 // Pass manager boilerplate below here. 720 721 namespace { 722 class VectorCombineLegacyPass : public FunctionPass { 723 public: 724 static char ID; 725 VectorCombineLegacyPass() : FunctionPass(ID) { 726 initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry()); 727 } 728 729 void getAnalysisUsage(AnalysisUsage &AU) const override { 730 AU.addRequired<DominatorTreeWrapperPass>(); 731 AU.addRequired<TargetTransformInfoWrapperPass>(); 732 AU.setPreservesCFG(); 733 AU.addPreserved<DominatorTreeWrapperPass>(); 734 AU.addPreserved<GlobalsAAWrapperPass>(); 735 AU.addPreserved<AAResultsWrapperPass>(); 736 AU.addPreserved<BasicAAWrapperPass>(); 737 FunctionPass::getAnalysisUsage(AU); 738 } 739 740 bool runOnFunction(Function &F) override { 741 if (skipFunction(F)) 742 return false; 743 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 744 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 745 VectorCombine Combiner(F, TTI, DT); 746 return Combiner.run(); 747 } 748 }; 749 } // namespace 750 751 char VectorCombineLegacyPass::ID = 0; 752 INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine", 753 "Optimize scalar/vector ops", false, 754 false) 755 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 756 INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine", 757 "Optimize scalar/vector ops", false, false) 758 Pass *llvm::createVectorCombinePass() { 759 return new VectorCombineLegacyPass(); 760 } 761 762 PreservedAnalyses VectorCombinePass::run(Function &F, 763 FunctionAnalysisManager &FAM) { 764 TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); 765 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); 766 VectorCombine Combiner(F, TTI, DT); 767 if (!Combiner.run()) 768 return PreservedAnalyses::all(); 769 PreservedAnalyses PA; 770 PA.preserveSet<CFGAnalyses>(); 771 PA.preserve<GlobalsAA>(); 772 PA.preserve<AAManager>(); 773 PA.preserve<BasicAA>(); 774 return PA; 775 } 776