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