1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===// 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 munges the code in the input function to better prepare it for 10 // SelectionDAG-based code generation. This works around limitations in it's 11 // basic-block-at-a-time approach. It should eventually be removed. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/MapVector.h" 19 #include "llvm/ADT/PointerIntPair.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/BlockFrequencyInfo.h" 25 #include "llvm/Analysis/BranchProbabilityInfo.h" 26 #include "llvm/Analysis/ConstantFolding.h" 27 #include "llvm/Analysis/InstructionSimplify.h" 28 #include "llvm/Analysis/LoopInfo.h" 29 #include "llvm/Analysis/MemoryBuiltins.h" 30 #include "llvm/Analysis/ProfileSummaryInfo.h" 31 #include "llvm/Analysis/TargetLibraryInfo.h" 32 #include "llvm/Analysis/TargetTransformInfo.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/Analysis/VectorUtils.h" 35 #include "llvm/CodeGen/Analysis.h" 36 #include "llvm/CodeGen/ISDOpcodes.h" 37 #include "llvm/CodeGen/SelectionDAGNodes.h" 38 #include "llvm/CodeGen/TargetLowering.h" 39 #include "llvm/CodeGen/TargetPassConfig.h" 40 #include "llvm/CodeGen/TargetSubtargetInfo.h" 41 #include "llvm/CodeGen/ValueTypes.h" 42 #include "llvm/Config/llvm-config.h" 43 #include "llvm/IR/Argument.h" 44 #include "llvm/IR/Attributes.h" 45 #include "llvm/IR/BasicBlock.h" 46 #include "llvm/IR/Constant.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DerivedTypes.h" 50 #include "llvm/IR/Dominators.h" 51 #include "llvm/IR/Function.h" 52 #include "llvm/IR/GetElementPtrTypeIterator.h" 53 #include "llvm/IR/GlobalValue.h" 54 #include "llvm/IR/GlobalVariable.h" 55 #include "llvm/IR/IRBuilder.h" 56 #include "llvm/IR/InlineAsm.h" 57 #include "llvm/IR/InstrTypes.h" 58 #include "llvm/IR/Instruction.h" 59 #include "llvm/IR/Instructions.h" 60 #include "llvm/IR/IntrinsicInst.h" 61 #include "llvm/IR/Intrinsics.h" 62 #include "llvm/IR/IntrinsicsAArch64.h" 63 #include "llvm/IR/IntrinsicsX86.h" 64 #include "llvm/IR/LLVMContext.h" 65 #include "llvm/IR/MDBuilder.h" 66 #include "llvm/IR/Module.h" 67 #include "llvm/IR/Operator.h" 68 #include "llvm/IR/PatternMatch.h" 69 #include "llvm/IR/Statepoint.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/User.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/IR/ValueHandle.h" 75 #include "llvm/IR/ValueMap.h" 76 #include "llvm/InitializePasses.h" 77 #include "llvm/Pass.h" 78 #include "llvm/Support/BlockFrequency.h" 79 #include "llvm/Support/BranchProbability.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CommandLine.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/Debug.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/MachineValueType.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Target/TargetMachine.h" 89 #include "llvm/Target/TargetOptions.h" 90 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 91 #include "llvm/Transforms/Utils/BypassSlowDivision.h" 92 #include "llvm/Transforms/Utils/Local.h" 93 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 94 #include "llvm/Transforms/Utils/SizeOpts.h" 95 #include <algorithm> 96 #include <cassert> 97 #include <cstdint> 98 #include <iterator> 99 #include <limits> 100 #include <memory> 101 #include <utility> 102 #include <vector> 103 104 using namespace llvm; 105 using namespace llvm::PatternMatch; 106 107 #define DEBUG_TYPE "codegenprepare" 108 109 STATISTIC(NumBlocksElim, "Number of blocks eliminated"); 110 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); 111 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); 112 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " 113 "sunken Cmps"); 114 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " 115 "of sunken Casts"); 116 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " 117 "computations were sunk"); 118 STATISTIC(NumMemoryInstsPhiCreated, 119 "Number of phis created when address " 120 "computations were sunk to memory instructions"); 121 STATISTIC(NumMemoryInstsSelectCreated, 122 "Number of select created when address " 123 "computations were sunk to memory instructions"); 124 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); 125 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); 126 STATISTIC(NumAndsAdded, 127 "Number of and mask instructions added to form ext loads"); 128 STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); 129 STATISTIC(NumRetsDup, "Number of return instructions duplicated"); 130 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); 131 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); 132 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); 133 134 static cl::opt<bool> DisableBranchOpts( 135 "disable-cgp-branch-opts", cl::Hidden, cl::init(false), 136 cl::desc("Disable branch optimizations in CodeGenPrepare")); 137 138 static cl::opt<bool> 139 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), 140 cl::desc("Disable GC optimizations in CodeGenPrepare")); 141 142 static cl::opt<bool> DisableSelectToBranch( 143 "disable-cgp-select2branch", cl::Hidden, cl::init(false), 144 cl::desc("Disable select to branch conversion.")); 145 146 static cl::opt<bool> AddrSinkUsingGEPs( 147 "addr-sink-using-gep", cl::Hidden, cl::init(true), 148 cl::desc("Address sinking in CGP using GEPs.")); 149 150 static cl::opt<bool> EnableAndCmpSinking( 151 "enable-andcmp-sinking", cl::Hidden, cl::init(true), 152 cl::desc("Enable sinkinig and/cmp into branches.")); 153 154 static cl::opt<bool> DisableStoreExtract( 155 "disable-cgp-store-extract", cl::Hidden, cl::init(false), 156 cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); 157 158 static cl::opt<bool> StressStoreExtract( 159 "stress-cgp-store-extract", cl::Hidden, cl::init(false), 160 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); 161 162 static cl::opt<bool> DisableExtLdPromotion( 163 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), 164 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " 165 "CodeGenPrepare")); 166 167 static cl::opt<bool> StressExtLdPromotion( 168 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), 169 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " 170 "optimization in CodeGenPrepare")); 171 172 static cl::opt<bool> DisablePreheaderProtect( 173 "disable-preheader-prot", cl::Hidden, cl::init(false), 174 cl::desc("Disable protection against removing loop preheaders")); 175 176 static cl::opt<bool> ProfileGuidedSectionPrefix( 177 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore, 178 cl::desc("Use profile info to add section prefix for hot/cold functions")); 179 180 static cl::opt<bool> ProfileUnknownInSpecialSection( 181 "profile-unknown-in-special-section", cl::Hidden, cl::init(false), 182 cl::ZeroOrMore, 183 cl::desc("In profiling mode like sampleFDO, if a function doesn't have " 184 "profile, we cannot tell the function is cold for sure because " 185 "it may be a function newly added without ever being sampled. " 186 "With the flag enabled, compiler can put such profile unknown " 187 "functions into a special section, so runtime system can choose " 188 "to handle it in a different way than .text section, to save " 189 "RAM for example. ")); 190 191 static cl::opt<unsigned> FreqRatioToSkipMerge( 192 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), 193 cl::desc("Skip merging empty blocks if (frequency of empty block) / " 194 "(frequency of destination block) is greater than this ratio")); 195 196 static cl::opt<bool> ForceSplitStore( 197 "force-split-store", cl::Hidden, cl::init(false), 198 cl::desc("Force store splitting no matter what the target query says.")); 199 200 static cl::opt<bool> 201 EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, 202 cl::desc("Enable merging of redundant sexts when one is dominating" 203 " the other."), cl::init(true)); 204 205 static cl::opt<bool> DisableComplexAddrModes( 206 "disable-complex-addr-modes", cl::Hidden, cl::init(false), 207 cl::desc("Disables combining addressing modes with different parts " 208 "in optimizeMemoryInst.")); 209 210 static cl::opt<bool> 211 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), 212 cl::desc("Allow creation of Phis in Address sinking.")); 213 214 static cl::opt<bool> 215 AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true), 216 cl::desc("Allow creation of selects in Address sinking.")); 217 218 static cl::opt<bool> AddrSinkCombineBaseReg( 219 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true), 220 cl::desc("Allow combining of BaseReg field in Address sinking.")); 221 222 static cl::opt<bool> AddrSinkCombineBaseGV( 223 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true), 224 cl::desc("Allow combining of BaseGV field in Address sinking.")); 225 226 static cl::opt<bool> AddrSinkCombineBaseOffs( 227 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true), 228 cl::desc("Allow combining of BaseOffs field in Address sinking.")); 229 230 static cl::opt<bool> AddrSinkCombineScaledReg( 231 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), 232 cl::desc("Allow combining of ScaledReg field in Address sinking.")); 233 234 static cl::opt<bool> 235 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden, 236 cl::init(true), 237 cl::desc("Enable splitting large offset of GEP.")); 238 239 static cl::opt<bool> EnableICMP_EQToICMP_ST( 240 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false), 241 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion.")); 242 243 static cl::opt<bool> 244 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false), 245 cl::desc("Enable BFI update verification for " 246 "CodeGenPrepare.")); 247 248 namespace { 249 250 enum ExtType { 251 ZeroExtension, // Zero extension has been seen. 252 SignExtension, // Sign extension has been seen. 253 BothExtension // This extension type is used if we saw sext after 254 // ZeroExtension had been set, or if we saw zext after 255 // SignExtension had been set. It makes the type 256 // information of a promoted instruction invalid. 257 }; 258 259 using SetOfInstrs = SmallPtrSet<Instruction *, 16>; 260 using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>; 261 using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>; 262 using SExts = SmallVector<Instruction *, 16>; 263 using ValueToSExts = DenseMap<Value *, SExts>; 264 265 class TypePromotionTransaction; 266 267 class CodeGenPrepare : public FunctionPass { 268 const TargetMachine *TM = nullptr; 269 const TargetSubtargetInfo *SubtargetInfo; 270 const TargetLowering *TLI = nullptr; 271 const TargetRegisterInfo *TRI; 272 const TargetTransformInfo *TTI = nullptr; 273 const TargetLibraryInfo *TLInfo; 274 const LoopInfo *LI; 275 std::unique_ptr<BlockFrequencyInfo> BFI; 276 std::unique_ptr<BranchProbabilityInfo> BPI; 277 ProfileSummaryInfo *PSI; 278 279 /// As we scan instructions optimizing them, this is the next instruction 280 /// to optimize. Transforms that can invalidate this should update it. 281 BasicBlock::iterator CurInstIterator; 282 283 /// Keeps track of non-local addresses that have been sunk into a block. 284 /// This allows us to avoid inserting duplicate code for blocks with 285 /// multiple load/stores of the same address. The usage of WeakTrackingVH 286 /// enables SunkAddrs to be treated as a cache whose entries can be 287 /// invalidated if a sunken address computation has been erased. 288 ValueMap<Value*, WeakTrackingVH> SunkAddrs; 289 290 /// Keeps track of all instructions inserted for the current function. 291 SetOfInstrs InsertedInsts; 292 293 /// Keeps track of the type of the related instruction before their 294 /// promotion for the current function. 295 InstrToOrigTy PromotedInsts; 296 297 /// Keep track of instructions removed during promotion. 298 SetOfInstrs RemovedInsts; 299 300 /// Keep track of sext chains based on their initial value. 301 DenseMap<Value *, Instruction *> SeenChainsForSExt; 302 303 /// Keep track of GEPs accessing the same data structures such as structs or 304 /// arrays that are candidates to be split later because of their large 305 /// size. 306 MapVector< 307 AssertingVH<Value>, 308 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>> 309 LargeOffsetGEPMap; 310 311 /// Keep track of new GEP base after splitting the GEPs having large offset. 312 SmallSet<AssertingVH<Value>, 2> NewGEPBases; 313 314 /// Map serial numbers to Large offset GEPs. 315 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID; 316 317 /// Keep track of SExt promoted. 318 ValueToSExts ValToSExtendedUses; 319 320 /// True if the function has the OptSize attribute. 321 bool OptSize; 322 323 /// DataLayout for the Function being processed. 324 const DataLayout *DL = nullptr; 325 326 /// Building the dominator tree can be expensive, so we only build it 327 /// lazily and update it when required. 328 std::unique_ptr<DominatorTree> DT; 329 330 public: 331 static char ID; // Pass identification, replacement for typeid 332 333 CodeGenPrepare() : FunctionPass(ID) { 334 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); 335 } 336 337 bool runOnFunction(Function &F) override; 338 339 StringRef getPassName() const override { return "CodeGen Prepare"; } 340 341 void getAnalysisUsage(AnalysisUsage &AU) const override { 342 // FIXME: When we can selectively preserve passes, preserve the domtree. 343 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 344 AU.addRequired<TargetLibraryInfoWrapperPass>(); 345 AU.addRequired<TargetPassConfig>(); 346 AU.addRequired<TargetTransformInfoWrapperPass>(); 347 AU.addRequired<LoopInfoWrapperPass>(); 348 } 349 350 private: 351 template <typename F> 352 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) { 353 // Substituting can cause recursive simplifications, which can invalidate 354 // our iterator. Use a WeakTrackingVH to hold onto it in case this 355 // happens. 356 Value *CurValue = &*CurInstIterator; 357 WeakTrackingVH IterHandle(CurValue); 358 359 f(); 360 361 // If the iterator instruction was recursively deleted, start over at the 362 // start of the block. 363 if (IterHandle != CurValue) { 364 CurInstIterator = BB->begin(); 365 SunkAddrs.clear(); 366 } 367 } 368 369 // Get the DominatorTree, building if necessary. 370 DominatorTree &getDT(Function &F) { 371 if (!DT) 372 DT = std::make_unique<DominatorTree>(F); 373 return *DT; 374 } 375 376 bool eliminateFallThrough(Function &F); 377 bool eliminateMostlyEmptyBlocks(Function &F); 378 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); 379 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; 380 void eliminateMostlyEmptyBlock(BasicBlock *BB); 381 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, 382 bool isPreheader); 383 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT); 384 bool optimizeInst(Instruction *I, bool &ModifiedDT); 385 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, 386 Type *AccessTy, unsigned AddrSpace); 387 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr); 388 bool optimizeInlineAsmInst(CallInst *CS); 389 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT); 390 bool optimizeExt(Instruction *&I); 391 bool optimizeExtUses(Instruction *I); 392 bool optimizeLoadExt(LoadInst *Load); 393 bool optimizeShiftInst(BinaryOperator *BO); 394 bool optimizeFunnelShift(IntrinsicInst *Fsh); 395 bool optimizeSelectInst(SelectInst *SI); 396 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI); 397 bool optimizeSwitchInst(SwitchInst *SI); 398 bool optimizeExtractElementInst(Instruction *Inst); 399 bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT); 400 bool fixupDbgValue(Instruction *I); 401 bool placeDbgValues(Function &F); 402 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts, 403 LoadInst *&LI, Instruction *&Inst, bool HasPromoted); 404 bool tryToPromoteExts(TypePromotionTransaction &TPT, 405 const SmallVectorImpl<Instruction *> &Exts, 406 SmallVectorImpl<Instruction *> &ProfitablyMovedExts, 407 unsigned CreatedInstsCost = 0); 408 bool mergeSExts(Function &F); 409 bool splitLargeGEPOffsets(); 410 bool performAddressTypePromotion( 411 Instruction *&Inst, 412 bool AllowPromotionWithoutCommonHeader, 413 bool HasPromoted, TypePromotionTransaction &TPT, 414 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts); 415 bool splitBranchCondition(Function &F, bool &ModifiedDT); 416 bool simplifyOffsetableRelocate(Instruction &I); 417 418 bool tryToSinkFreeOperands(Instruction *I); 419 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, 420 Value *Arg1, CmpInst *Cmp, 421 Intrinsic::ID IID); 422 bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT); 423 bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT); 424 bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT); 425 void verifyBFIUpdates(Function &F); 426 }; 427 428 } // end anonymous namespace 429 430 char CodeGenPrepare::ID = 0; 431 432 INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE, 433 "Optimize for code generation", false, false) 434 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 435 INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE, 436 "Optimize for code generation", false, false) 437 438 FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); } 439 440 bool CodeGenPrepare::runOnFunction(Function &F) { 441 if (skipFunction(F)) 442 return false; 443 444 DL = &F.getParent()->getDataLayout(); 445 446 bool EverMadeChange = false; 447 // Clear per function information. 448 InsertedInsts.clear(); 449 PromotedInsts.clear(); 450 451 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>(); 452 SubtargetInfo = TM->getSubtargetImpl(F); 453 TLI = SubtargetInfo->getTargetLowering(); 454 TRI = SubtargetInfo->getRegisterInfo(); 455 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 456 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 457 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 458 BPI.reset(new BranchProbabilityInfo(F, *LI)); 459 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI)); 460 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 461 OptSize = F.hasOptSize(); 462 if (ProfileGuidedSectionPrefix) { 463 if (PSI->isFunctionHotInCallGraph(&F, *BFI)) 464 F.setSectionPrefix(".hot"); 465 else if (PSI->isFunctionColdInCallGraph(&F, *BFI)) 466 F.setSectionPrefix(".unlikely"); 467 else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() && 468 PSI->isFunctionHotnessUnknown(F)) 469 F.setSectionPrefix(".unknown"); 470 } 471 472 /// This optimization identifies DIV instructions that can be 473 /// profitably bypassed and carried out with a shorter, faster divide. 474 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) { 475 const DenseMap<unsigned int, unsigned int> &BypassWidths = 476 TLI->getBypassSlowDivWidths(); 477 BasicBlock* BB = &*F.begin(); 478 while (BB != nullptr) { 479 // bypassSlowDivision may create new BBs, but we don't want to reapply the 480 // optimization to those blocks. 481 BasicBlock* Next = BB->getNextNode(); 482 // F.hasOptSize is already checked in the outer if statement. 483 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get())) 484 EverMadeChange |= bypassSlowDivision(BB, BypassWidths); 485 BB = Next; 486 } 487 } 488 489 // Eliminate blocks that contain only PHI nodes and an 490 // unconditional branch. 491 EverMadeChange |= eliminateMostlyEmptyBlocks(F); 492 493 bool ModifiedDT = false; 494 if (!DisableBranchOpts) 495 EverMadeChange |= splitBranchCondition(F, ModifiedDT); 496 497 // Split some critical edges where one of the sources is an indirect branch, 498 // to help generate sane code for PHIs involving such edges. 499 EverMadeChange |= SplitIndirectBrCriticalEdges(F); 500 501 bool MadeChange = true; 502 while (MadeChange) { 503 MadeChange = false; 504 DT.reset(); 505 for (Function::iterator I = F.begin(); I != F.end(); ) { 506 BasicBlock *BB = &*I++; 507 bool ModifiedDTOnIteration = false; 508 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); 509 510 // Restart BB iteration if the dominator tree of the Function was changed 511 if (ModifiedDTOnIteration) 512 break; 513 } 514 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty()) 515 MadeChange |= mergeSExts(F); 516 if (!LargeOffsetGEPMap.empty()) 517 MadeChange |= splitLargeGEPOffsets(); 518 519 if (MadeChange) 520 eliminateFallThrough(F); 521 522 // Really free removed instructions during promotion. 523 for (Instruction *I : RemovedInsts) 524 I->deleteValue(); 525 526 EverMadeChange |= MadeChange; 527 SeenChainsForSExt.clear(); 528 ValToSExtendedUses.clear(); 529 RemovedInsts.clear(); 530 LargeOffsetGEPMap.clear(); 531 LargeOffsetGEPID.clear(); 532 } 533 534 SunkAddrs.clear(); 535 536 if (!DisableBranchOpts) { 537 MadeChange = false; 538 // Use a set vector to get deterministic iteration order. The order the 539 // blocks are removed may affect whether or not PHI nodes in successors 540 // are removed. 541 SmallSetVector<BasicBlock*, 8> WorkList; 542 for (BasicBlock &BB : F) { 543 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); 544 MadeChange |= ConstantFoldTerminator(&BB, true); 545 if (!MadeChange) continue; 546 547 for (SmallVectorImpl<BasicBlock*>::iterator 548 II = Successors.begin(), IE = Successors.end(); II != IE; ++II) 549 if (pred_begin(*II) == pred_end(*II)) 550 WorkList.insert(*II); 551 } 552 553 // Delete the dead blocks and any of their dead successors. 554 MadeChange |= !WorkList.empty(); 555 while (!WorkList.empty()) { 556 BasicBlock *BB = WorkList.pop_back_val(); 557 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); 558 559 DeleteDeadBlock(BB); 560 561 for (SmallVectorImpl<BasicBlock*>::iterator 562 II = Successors.begin(), IE = Successors.end(); II != IE; ++II) 563 if (pred_begin(*II) == pred_end(*II)) 564 WorkList.insert(*II); 565 } 566 567 // Merge pairs of basic blocks with unconditional branches, connected by 568 // a single edge. 569 if (EverMadeChange || MadeChange) 570 MadeChange |= eliminateFallThrough(F); 571 572 EverMadeChange |= MadeChange; 573 } 574 575 if (!DisableGCOpts) { 576 SmallVector<Instruction *, 2> Statepoints; 577 for (BasicBlock &BB : F) 578 for (Instruction &I : BB) 579 if (isa<GCStatepointInst>(I)) 580 Statepoints.push_back(&I); 581 for (auto &I : Statepoints) 582 EverMadeChange |= simplifyOffsetableRelocate(*I); 583 } 584 585 // Do this last to clean up use-before-def scenarios introduced by other 586 // preparatory transforms. 587 EverMadeChange |= placeDbgValues(F); 588 589 #ifndef NDEBUG 590 if (VerifyBFIUpdates) 591 verifyBFIUpdates(F); 592 #endif 593 594 return EverMadeChange; 595 } 596 597 // Verify BFI has been updated correctly by recomputing BFI and comparing them. 598 void LLVM_ATTRIBUTE_UNUSED CodeGenPrepare::verifyBFIUpdates(Function &F) { 599 DominatorTree NewDT(F); 600 LoopInfo NewLI(NewDT); 601 BranchProbabilityInfo NewBPI(F, NewLI, TLInfo); 602 BlockFrequencyInfo NewBFI(F, NewBPI, NewLI); 603 NewBFI.verifyMatch(*BFI); 604 } 605 606 /// Merge basic blocks which are connected by a single edge, where one of the 607 /// basic blocks has a single successor pointing to the other basic block, 608 /// which has a single predecessor. 609 bool CodeGenPrepare::eliminateFallThrough(Function &F) { 610 bool Changed = false; 611 // Scan all of the blocks in the function, except for the entry block. 612 // Use a temporary array to avoid iterator being invalidated when 613 // deleting blocks. 614 SmallVector<WeakTrackingVH, 16> Blocks; 615 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end())) 616 Blocks.push_back(&Block); 617 618 for (auto &Block : Blocks) { 619 auto *BB = cast_or_null<BasicBlock>(Block); 620 if (!BB) 621 continue; 622 // If the destination block has a single pred, then this is a trivial 623 // edge, just collapse it. 624 BasicBlock *SinglePred = BB->getSinglePredecessor(); 625 626 // Don't merge if BB's address is taken. 627 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; 628 629 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); 630 if (Term && !Term->isConditional()) { 631 Changed = true; 632 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n"); 633 634 // Merge BB into SinglePred and delete it. 635 MergeBlockIntoPredecessor(BB); 636 } 637 } 638 return Changed; 639 } 640 641 /// Find a destination block from BB if BB is mergeable empty block. 642 BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { 643 // If this block doesn't end with an uncond branch, ignore it. 644 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); 645 if (!BI || !BI->isUnconditional()) 646 return nullptr; 647 648 // If the instruction before the branch (skipping debug info) isn't a phi 649 // node, then other stuff is happening here. 650 BasicBlock::iterator BBI = BI->getIterator(); 651 if (BBI != BB->begin()) { 652 --BBI; 653 while (isa<DbgInfoIntrinsic>(BBI)) { 654 if (BBI == BB->begin()) 655 break; 656 --BBI; 657 } 658 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) 659 return nullptr; 660 } 661 662 // Do not break infinite loops. 663 BasicBlock *DestBB = BI->getSuccessor(0); 664 if (DestBB == BB) 665 return nullptr; 666 667 if (!canMergeBlocks(BB, DestBB)) 668 DestBB = nullptr; 669 670 return DestBB; 671 } 672 673 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an 674 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split 675 /// edges in ways that are non-optimal for isel. Start by eliminating these 676 /// blocks so we can split them the way we want them. 677 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { 678 SmallPtrSet<BasicBlock *, 16> Preheaders; 679 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); 680 while (!LoopList.empty()) { 681 Loop *L = LoopList.pop_back_val(); 682 LoopList.insert(LoopList.end(), L->begin(), L->end()); 683 if (BasicBlock *Preheader = L->getLoopPreheader()) 684 Preheaders.insert(Preheader); 685 } 686 687 bool MadeChange = false; 688 // Copy blocks into a temporary array to avoid iterator invalidation issues 689 // as we remove them. 690 // Note that this intentionally skips the entry block. 691 SmallVector<WeakTrackingVH, 16> Blocks; 692 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end())) 693 Blocks.push_back(&Block); 694 695 for (auto &Block : Blocks) { 696 BasicBlock *BB = cast_or_null<BasicBlock>(Block); 697 if (!BB) 698 continue; 699 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); 700 if (!DestBB || 701 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) 702 continue; 703 704 eliminateMostlyEmptyBlock(BB); 705 MadeChange = true; 706 } 707 return MadeChange; 708 } 709 710 bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, 711 BasicBlock *DestBB, 712 bool isPreheader) { 713 // Do not delete loop preheaders if doing so would create a critical edge. 714 // Loop preheaders can be good locations to spill registers. If the 715 // preheader is deleted and we create a critical edge, registers may be 716 // spilled in the loop body instead. 717 if (!DisablePreheaderProtect && isPreheader && 718 !(BB->getSinglePredecessor() && 719 BB->getSinglePredecessor()->getSingleSuccessor())) 720 return false; 721 722 // Skip merging if the block's successor is also a successor to any callbr 723 // that leads to this block. 724 // FIXME: Is this really needed? Is this a correctness issue? 725 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 726 if (auto *CBI = dyn_cast<CallBrInst>((*PI)->getTerminator())) 727 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i) 728 if (DestBB == CBI->getSuccessor(i)) 729 return false; 730 } 731 732 // Try to skip merging if the unique predecessor of BB is terminated by a 733 // switch or indirect branch instruction, and BB is used as an incoming block 734 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to 735 // add COPY instructions in the predecessor of BB instead of BB (if it is not 736 // merged). Note that the critical edge created by merging such blocks wont be 737 // split in MachineSink because the jump table is not analyzable. By keeping 738 // such empty block (BB), ISel will place COPY instructions in BB, not in the 739 // predecessor of BB. 740 BasicBlock *Pred = BB->getUniquePredecessor(); 741 if (!Pred || 742 !(isa<SwitchInst>(Pred->getTerminator()) || 743 isa<IndirectBrInst>(Pred->getTerminator()))) 744 return true; 745 746 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg()) 747 return true; 748 749 // We use a simple cost heuristic which determine skipping merging is 750 // profitable if the cost of skipping merging is less than the cost of 751 // merging : Cost(skipping merging) < Cost(merging BB), where the 752 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and 753 // the Cost(merging BB) is Freq(Pred) * Cost(Copy). 754 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : 755 // Freq(Pred) / Freq(BB) > 2. 756 // Note that if there are multiple empty blocks sharing the same incoming 757 // value for the PHIs in the DestBB, we consider them together. In such 758 // case, Cost(merging BB) will be the sum of their frequencies. 759 760 if (!isa<PHINode>(DestBB->begin())) 761 return true; 762 763 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; 764 765 // Find all other incoming blocks from which incoming values of all PHIs in 766 // DestBB are the same as the ones from BB. 767 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E; 768 ++PI) { 769 BasicBlock *DestBBPred = *PI; 770 if (DestBBPred == BB) 771 continue; 772 773 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) { 774 return DestPN.getIncomingValueForBlock(BB) == 775 DestPN.getIncomingValueForBlock(DestBBPred); 776 })) 777 SameIncomingValueBBs.insert(DestBBPred); 778 } 779 780 // See if all BB's incoming values are same as the value from Pred. In this 781 // case, no reason to skip merging because COPYs are expected to be place in 782 // Pred already. 783 if (SameIncomingValueBBs.count(Pred)) 784 return true; 785 786 BlockFrequency PredFreq = BFI->getBlockFreq(Pred); 787 BlockFrequency BBFreq = BFI->getBlockFreq(BB); 788 789 for (auto SameValueBB : SameIncomingValueBBs) 790 if (SameValueBB->getUniquePredecessor() == Pred && 791 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) 792 BBFreq += BFI->getBlockFreq(SameValueBB); 793 794 return PredFreq.getFrequency() <= 795 BBFreq.getFrequency() * FreqRatioToSkipMerge; 796 } 797 798 /// Return true if we can merge BB into DestBB if there is a single 799 /// unconditional branch between them, and BB contains no other non-phi 800 /// instructions. 801 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, 802 const BasicBlock *DestBB) const { 803 // We only want to eliminate blocks whose phi nodes are used by phi nodes in 804 // the successor. If there are more complex condition (e.g. preheaders), 805 // don't mess around with them. 806 for (const PHINode &PN : BB->phis()) { 807 for (const User *U : PN.users()) { 808 const Instruction *UI = cast<Instruction>(U); 809 if (UI->getParent() != DestBB || !isa<PHINode>(UI)) 810 return false; 811 // If User is inside DestBB block and it is a PHINode then check 812 // incoming value. If incoming value is not from BB then this is 813 // a complex condition (e.g. preheaders) we want to avoid here. 814 if (UI->getParent() == DestBB) { 815 if (const PHINode *UPN = dyn_cast<PHINode>(UI)) 816 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { 817 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); 818 if (Insn && Insn->getParent() == BB && 819 Insn->getParent() != UPN->getIncomingBlock(I)) 820 return false; 821 } 822 } 823 } 824 } 825 826 // If BB and DestBB contain any common predecessors, then the phi nodes in BB 827 // and DestBB may have conflicting incoming values for the block. If so, we 828 // can't merge the block. 829 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); 830 if (!DestBBPN) return true; // no conflict. 831 832 // Collect the preds of BB. 833 SmallPtrSet<const BasicBlock*, 16> BBPreds; 834 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { 835 // It is faster to get preds from a PHI than with pred_iterator. 836 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) 837 BBPreds.insert(BBPN->getIncomingBlock(i)); 838 } else { 839 BBPreds.insert(pred_begin(BB), pred_end(BB)); 840 } 841 842 // Walk the preds of DestBB. 843 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { 844 BasicBlock *Pred = DestBBPN->getIncomingBlock(i); 845 if (BBPreds.count(Pred)) { // Common predecessor? 846 for (const PHINode &PN : DestBB->phis()) { 847 const Value *V1 = PN.getIncomingValueForBlock(Pred); 848 const Value *V2 = PN.getIncomingValueForBlock(BB); 849 850 // If V2 is a phi node in BB, look up what the mapped value will be. 851 if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) 852 if (V2PN->getParent() == BB) 853 V2 = V2PN->getIncomingValueForBlock(Pred); 854 855 // If there is a conflict, bail out. 856 if (V1 != V2) return false; 857 } 858 } 859 } 860 861 return true; 862 } 863 864 /// Eliminate a basic block that has only phi's and an unconditional branch in 865 /// it. 866 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { 867 BranchInst *BI = cast<BranchInst>(BB->getTerminator()); 868 BasicBlock *DestBB = BI->getSuccessor(0); 869 870 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" 871 << *BB << *DestBB); 872 873 // If the destination block has a single pred, then this is a trivial edge, 874 // just collapse it. 875 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { 876 if (SinglePred != DestBB) { 877 assert(SinglePred == BB && 878 "Single predecessor not the same as predecessor"); 879 // Merge DestBB into SinglePred/BB and delete it. 880 MergeBlockIntoPredecessor(DestBB); 881 // Note: BB(=SinglePred) will not be deleted on this path. 882 // DestBB(=its single successor) is the one that was deleted. 883 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n"); 884 return; 885 } 886 } 887 888 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB 889 // to handle the new incoming edges it is about to have. 890 for (PHINode &PN : DestBB->phis()) { 891 // Remove the incoming value for BB, and remember it. 892 Value *InVal = PN.removeIncomingValue(BB, false); 893 894 // Two options: either the InVal is a phi node defined in BB or it is some 895 // value that dominates BB. 896 PHINode *InValPhi = dyn_cast<PHINode>(InVal); 897 if (InValPhi && InValPhi->getParent() == BB) { 898 // Add all of the input values of the input PHI as inputs of this phi. 899 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) 900 PN.addIncoming(InValPhi->getIncomingValue(i), 901 InValPhi->getIncomingBlock(i)); 902 } else { 903 // Otherwise, add one instance of the dominating value for each edge that 904 // we will be adding. 905 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { 906 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) 907 PN.addIncoming(InVal, BBPN->getIncomingBlock(i)); 908 } else { 909 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 910 PN.addIncoming(InVal, *PI); 911 } 912 } 913 } 914 915 // The PHIs are now updated, change everything that refers to BB to use 916 // DestBB and remove BB. 917 BB->replaceAllUsesWith(DestBB); 918 BB->eraseFromParent(); 919 ++NumBlocksElim; 920 921 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); 922 } 923 924 // Computes a map of base pointer relocation instructions to corresponding 925 // derived pointer relocation instructions given a vector of all relocate calls 926 static void computeBaseDerivedRelocateMap( 927 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, 928 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> 929 &RelocateInstMap) { 930 // Collect information in two maps: one primarily for locating the base object 931 // while filling the second map; the second map is the final structure holding 932 // a mapping between Base and corresponding Derived relocate calls 933 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; 934 for (auto *ThisRelocate : AllRelocateCalls) { 935 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), 936 ThisRelocate->getDerivedPtrIndex()); 937 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); 938 } 939 for (auto &Item : RelocateIdxMap) { 940 std::pair<unsigned, unsigned> Key = Item.first; 941 if (Key.first == Key.second) 942 // Base relocation: nothing to insert 943 continue; 944 945 GCRelocateInst *I = Item.second; 946 auto BaseKey = std::make_pair(Key.first, Key.first); 947 948 // We're iterating over RelocateIdxMap so we cannot modify it. 949 auto MaybeBase = RelocateIdxMap.find(BaseKey); 950 if (MaybeBase == RelocateIdxMap.end()) 951 // TODO: We might want to insert a new base object relocate and gep off 952 // that, if there are enough derived object relocates. 953 continue; 954 955 RelocateInstMap[MaybeBase->second].push_back(I); 956 } 957 } 958 959 // Accepts a GEP and extracts the operands into a vector provided they're all 960 // small integer constants 961 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, 962 SmallVectorImpl<Value *> &OffsetV) { 963 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 964 // Only accept small constant integer operands 965 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); 966 if (!Op || Op->getZExtValue() > 20) 967 return false; 968 } 969 970 for (unsigned i = 1; i < GEP->getNumOperands(); i++) 971 OffsetV.push_back(GEP->getOperand(i)); 972 return true; 973 } 974 975 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to 976 // replace, computes a replacement, and affects it. 977 static bool 978 simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, 979 const SmallVectorImpl<GCRelocateInst *> &Targets) { 980 bool MadeChange = false; 981 // We must ensure the relocation of derived pointer is defined after 982 // relocation of base pointer. If we find a relocation corresponding to base 983 // defined earlier than relocation of base then we move relocation of base 984 // right before found relocation. We consider only relocation in the same 985 // basic block as relocation of base. Relocations from other basic block will 986 // be skipped by optimization and we do not care about them. 987 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt(); 988 &*R != RelocatedBase; ++R) 989 if (auto RI = dyn_cast<GCRelocateInst>(R)) 990 if (RI->getStatepoint() == RelocatedBase->getStatepoint()) 991 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) { 992 RelocatedBase->moveBefore(RI); 993 break; 994 } 995 996 for (GCRelocateInst *ToReplace : Targets) { 997 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && 998 "Not relocating a derived object of the original base object"); 999 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { 1000 // A duplicate relocate call. TODO: coalesce duplicates. 1001 continue; 1002 } 1003 1004 if (RelocatedBase->getParent() != ToReplace->getParent()) { 1005 // Base and derived relocates are in different basic blocks. 1006 // In this case transform is only valid when base dominates derived 1007 // relocate. However it would be too expensive to check dominance 1008 // for each such relocate, so we skip the whole transformation. 1009 continue; 1010 } 1011 1012 Value *Base = ToReplace->getBasePtr(); 1013 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); 1014 if (!Derived || Derived->getPointerOperand() != Base) 1015 continue; 1016 1017 SmallVector<Value *, 2> OffsetV; 1018 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) 1019 continue; 1020 1021 // Create a Builder and replace the target callsite with a gep 1022 assert(RelocatedBase->getNextNode() && 1023 "Should always have one since it's not a terminator"); 1024 1025 // Insert after RelocatedBase 1026 IRBuilder<> Builder(RelocatedBase->getNextNode()); 1027 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); 1028 1029 // If gc_relocate does not match the actual type, cast it to the right type. 1030 // In theory, there must be a bitcast after gc_relocate if the type does not 1031 // match, and we should reuse it to get the derived pointer. But it could be 1032 // cases like this: 1033 // bb1: 1034 // ... 1035 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) 1036 // br label %merge 1037 // 1038 // bb2: 1039 // ... 1040 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) 1041 // br label %merge 1042 // 1043 // merge: 1044 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] 1045 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* 1046 // 1047 // In this case, we can not find the bitcast any more. So we insert a new bitcast 1048 // no matter there is already one or not. In this way, we can handle all cases, and 1049 // the extra bitcast should be optimized away in later passes. 1050 Value *ActualRelocatedBase = RelocatedBase; 1051 if (RelocatedBase->getType() != Base->getType()) { 1052 ActualRelocatedBase = 1053 Builder.CreateBitCast(RelocatedBase, Base->getType()); 1054 } 1055 Value *Replacement = Builder.CreateGEP( 1056 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); 1057 Replacement->takeName(ToReplace); 1058 // If the newly generated derived pointer's type does not match the original derived 1059 // pointer's type, cast the new derived pointer to match it. Same reasoning as above. 1060 Value *ActualReplacement = Replacement; 1061 if (Replacement->getType() != ToReplace->getType()) { 1062 ActualReplacement = 1063 Builder.CreateBitCast(Replacement, ToReplace->getType()); 1064 } 1065 ToReplace->replaceAllUsesWith(ActualReplacement); 1066 ToReplace->eraseFromParent(); 1067 1068 MadeChange = true; 1069 } 1070 return MadeChange; 1071 } 1072 1073 // Turns this: 1074 // 1075 // %base = ... 1076 // %ptr = gep %base + 15 1077 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) 1078 // %base' = relocate(%tok, i32 4, i32 4) 1079 // %ptr' = relocate(%tok, i32 4, i32 5) 1080 // %val = load %ptr' 1081 // 1082 // into this: 1083 // 1084 // %base = ... 1085 // %ptr = gep %base + 15 1086 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) 1087 // %base' = gc.relocate(%tok, i32 4, i32 4) 1088 // %ptr' = gep %base' + 15 1089 // %val = load %ptr' 1090 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { 1091 bool MadeChange = false; 1092 SmallVector<GCRelocateInst *, 2> AllRelocateCalls; 1093 1094 for (auto *U : I.users()) 1095 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) 1096 // Collect all the relocate calls associated with a statepoint 1097 AllRelocateCalls.push_back(Relocate); 1098 1099 // We need at least one base pointer relocation + one derived pointer 1100 // relocation to mangle 1101 if (AllRelocateCalls.size() < 2) 1102 return false; 1103 1104 // RelocateInstMap is a mapping from the base relocate instruction to the 1105 // corresponding derived relocate instructions 1106 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; 1107 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); 1108 if (RelocateInstMap.empty()) 1109 return false; 1110 1111 for (auto &Item : RelocateInstMap) 1112 // Item.first is the RelocatedBase to offset against 1113 // Item.second is the vector of Targets to replace 1114 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); 1115 return MadeChange; 1116 } 1117 1118 /// Sink the specified cast instruction into its user blocks. 1119 static bool SinkCast(CastInst *CI) { 1120 BasicBlock *DefBB = CI->getParent(); 1121 1122 /// InsertedCasts - Only insert a cast in each block once. 1123 DenseMap<BasicBlock*, CastInst*> InsertedCasts; 1124 1125 bool MadeChange = false; 1126 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); 1127 UI != E; ) { 1128 Use &TheUse = UI.getUse(); 1129 Instruction *User = cast<Instruction>(*UI); 1130 1131 // Figure out which BB this cast is used in. For PHI's this is the 1132 // appropriate predecessor block. 1133 BasicBlock *UserBB = User->getParent(); 1134 if (PHINode *PN = dyn_cast<PHINode>(User)) { 1135 UserBB = PN->getIncomingBlock(TheUse); 1136 } 1137 1138 // Preincrement use iterator so we don't invalidate it. 1139 ++UI; 1140 1141 // The first insertion point of a block containing an EH pad is after the 1142 // pad. If the pad is the user, we cannot sink the cast past the pad. 1143 if (User->isEHPad()) 1144 continue; 1145 1146 // If the block selected to receive the cast is an EH pad that does not 1147 // allow non-PHI instructions before the terminator, we can't sink the 1148 // cast. 1149 if (UserBB->getTerminator()->isEHPad()) 1150 continue; 1151 1152 // If this user is in the same block as the cast, don't change the cast. 1153 if (UserBB == DefBB) continue; 1154 1155 // If we have already inserted a cast into this block, use it. 1156 CastInst *&InsertedCast = InsertedCasts[UserBB]; 1157 1158 if (!InsertedCast) { 1159 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); 1160 assert(InsertPt != UserBB->end()); 1161 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), 1162 CI->getType(), "", &*InsertPt); 1163 InsertedCast->setDebugLoc(CI->getDebugLoc()); 1164 } 1165 1166 // Replace a use of the cast with a use of the new cast. 1167 TheUse = InsertedCast; 1168 MadeChange = true; 1169 ++NumCastUses; 1170 } 1171 1172 // If we removed all uses, nuke the cast. 1173 if (CI->use_empty()) { 1174 salvageDebugInfo(*CI); 1175 CI->eraseFromParent(); 1176 MadeChange = true; 1177 } 1178 1179 return MadeChange; 1180 } 1181 1182 /// If the specified cast instruction is a noop copy (e.g. it's casting from 1183 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to 1184 /// reduce the number of virtual registers that must be created and coalesced. 1185 /// 1186 /// Return true if any changes are made. 1187 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, 1188 const DataLayout &DL) { 1189 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition 1190 // than sinking only nop casts, but is helpful on some platforms. 1191 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { 1192 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(), 1193 ASC->getDestAddressSpace())) 1194 return false; 1195 } 1196 1197 // If this is a noop copy, 1198 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); 1199 EVT DstVT = TLI.getValueType(DL, CI->getType()); 1200 1201 // This is an fp<->int conversion? 1202 if (SrcVT.isInteger() != DstVT.isInteger()) 1203 return false; 1204 1205 // If this is an extension, it will be a zero or sign extension, which 1206 // isn't a noop. 1207 if (SrcVT.bitsLT(DstVT)) return false; 1208 1209 // If these values will be promoted, find out what they will be promoted 1210 // to. This helps us consider truncates on PPC as noop copies when they 1211 // are. 1212 if (TLI.getTypeAction(CI->getContext(), SrcVT) == 1213 TargetLowering::TypePromoteInteger) 1214 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); 1215 if (TLI.getTypeAction(CI->getContext(), DstVT) == 1216 TargetLowering::TypePromoteInteger) 1217 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); 1218 1219 // If, after promotion, these are the same types, this is a noop copy. 1220 if (SrcVT != DstVT) 1221 return false; 1222 1223 return SinkCast(CI); 1224 } 1225 1226 bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO, 1227 Value *Arg0, Value *Arg1, 1228 CmpInst *Cmp, 1229 Intrinsic::ID IID) { 1230 if (BO->getParent() != Cmp->getParent()) { 1231 // We used to use a dominator tree here to allow multi-block optimization. 1232 // But that was problematic because: 1233 // 1. It could cause a perf regression by hoisting the math op into the 1234 // critical path. 1235 // 2. It could cause a perf regression by creating a value that was live 1236 // across multiple blocks and increasing register pressure. 1237 // 3. Use of a dominator tree could cause large compile-time regression. 1238 // This is because we recompute the DT on every change in the main CGP 1239 // run-loop. The recomputing is probably unnecessary in many cases, so if 1240 // that was fixed, using a DT here would be ok. 1241 return false; 1242 } 1243 1244 // We allow matching the canonical IR (add X, C) back to (usubo X, -C). 1245 if (BO->getOpcode() == Instruction::Add && 1246 IID == Intrinsic::usub_with_overflow) { 1247 assert(isa<Constant>(Arg1) && "Unexpected input for usubo"); 1248 Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1)); 1249 } 1250 1251 // Insert at the first instruction of the pair. 1252 Instruction *InsertPt = nullptr; 1253 for (Instruction &Iter : *Cmp->getParent()) { 1254 // If BO is an XOR, it is not guaranteed that it comes after both inputs to 1255 // the overflow intrinsic are defined. 1256 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) { 1257 InsertPt = &Iter; 1258 break; 1259 } 1260 } 1261 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop"); 1262 1263 IRBuilder<> Builder(InsertPt); 1264 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1); 1265 if (BO->getOpcode() != Instruction::Xor) { 1266 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math"); 1267 BO->replaceAllUsesWith(Math); 1268 } else 1269 assert(BO->hasOneUse() && 1270 "Patterns with XOr should use the BO only in the compare"); 1271 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov"); 1272 Cmp->replaceAllUsesWith(OV); 1273 Cmp->eraseFromParent(); 1274 BO->eraseFromParent(); 1275 return true; 1276 } 1277 1278 /// Match special-case patterns that check for unsigned add overflow. 1279 static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, 1280 BinaryOperator *&Add) { 1281 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val) 1282 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero) 1283 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1); 1284 1285 // We are not expecting non-canonical/degenerate code. Just bail out. 1286 if (isa<Constant>(A)) 1287 return false; 1288 1289 ICmpInst::Predicate Pred = Cmp->getPredicate(); 1290 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes())) 1291 B = ConstantInt::get(B->getType(), 1); 1292 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) 1293 B = ConstantInt::get(B->getType(), -1); 1294 else 1295 return false; 1296 1297 // Check the users of the variable operand of the compare looking for an add 1298 // with the adjusted constant. 1299 for (User *U : A->users()) { 1300 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) { 1301 Add = cast<BinaryOperator>(U); 1302 return true; 1303 } 1304 } 1305 return false; 1306 } 1307 1308 /// Try to combine the compare into a call to the llvm.uadd.with.overflow 1309 /// intrinsic. Return true if any changes were made. 1310 bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp, 1311 bool &ModifiedDT) { 1312 Value *A, *B; 1313 BinaryOperator *Add; 1314 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) { 1315 if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add)) 1316 return false; 1317 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases. 1318 A = Add->getOperand(0); 1319 B = Add->getOperand(1); 1320 } 1321 1322 if (!TLI->shouldFormOverflowOp(ISD::UADDO, 1323 TLI->getValueType(*DL, Add->getType()), 1324 Add->hasNUsesOrMore(2))) 1325 return false; 1326 1327 // We don't want to move around uses of condition values this late, so we 1328 // check if it is legal to create the call to the intrinsic in the basic 1329 // block containing the icmp. 1330 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse()) 1331 return false; 1332 1333 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp, 1334 Intrinsic::uadd_with_overflow)) 1335 return false; 1336 1337 // Reset callers - do not crash by iterating over a dead instruction. 1338 ModifiedDT = true; 1339 return true; 1340 } 1341 1342 bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp, 1343 bool &ModifiedDT) { 1344 // We are not expecting non-canonical/degenerate code. Just bail out. 1345 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1); 1346 if (isa<Constant>(A) && isa<Constant>(B)) 1347 return false; 1348 1349 // Convert (A u> B) to (A u< B) to simplify pattern matching. 1350 ICmpInst::Predicate Pred = Cmp->getPredicate(); 1351 if (Pred == ICmpInst::ICMP_UGT) { 1352 std::swap(A, B); 1353 Pred = ICmpInst::ICMP_ULT; 1354 } 1355 // Convert special-case: (A == 0) is the same as (A u< 1). 1356 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) { 1357 B = ConstantInt::get(B->getType(), 1); 1358 Pred = ICmpInst::ICMP_ULT; 1359 } 1360 // Convert special-case: (A != 0) is the same as (0 u< A). 1361 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) { 1362 std::swap(A, B); 1363 Pred = ICmpInst::ICMP_ULT; 1364 } 1365 if (Pred != ICmpInst::ICMP_ULT) 1366 return false; 1367 1368 // Walk the users of a variable operand of a compare looking for a subtract or 1369 // add with that same operand. Also match the 2nd operand of the compare to 1370 // the add/sub, but that may be a negated constant operand of an add. 1371 Value *CmpVariableOperand = isa<Constant>(A) ? B : A; 1372 BinaryOperator *Sub = nullptr; 1373 for (User *U : CmpVariableOperand->users()) { 1374 // A - B, A u< B --> usubo(A, B) 1375 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) { 1376 Sub = cast<BinaryOperator>(U); 1377 break; 1378 } 1379 1380 // A + (-C), A u< C (canonicalized form of (sub A, C)) 1381 const APInt *CmpC, *AddC; 1382 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) && 1383 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) { 1384 Sub = cast<BinaryOperator>(U); 1385 break; 1386 } 1387 } 1388 if (!Sub) 1389 return false; 1390 1391 if (!TLI->shouldFormOverflowOp(ISD::USUBO, 1392 TLI->getValueType(*DL, Sub->getType()), 1393 Sub->hasNUsesOrMore(2))) 1394 return false; 1395 1396 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1), 1397 Cmp, Intrinsic::usub_with_overflow)) 1398 return false; 1399 1400 // Reset callers - do not crash by iterating over a dead instruction. 1401 ModifiedDT = true; 1402 return true; 1403 } 1404 1405 /// Sink the given CmpInst into user blocks to reduce the number of virtual 1406 /// registers that must be created and coalesced. This is a clear win except on 1407 /// targets with multiple condition code registers (PowerPC), where it might 1408 /// lose; some adjustment may be wanted there. 1409 /// 1410 /// Return true if any changes are made. 1411 static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) { 1412 if (TLI.hasMultipleConditionRegisters()) 1413 return false; 1414 1415 // Avoid sinking soft-FP comparisons, since this can move them into a loop. 1416 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp)) 1417 return false; 1418 1419 // Only insert a cmp in each block once. 1420 DenseMap<BasicBlock*, CmpInst*> InsertedCmps; 1421 1422 bool MadeChange = false; 1423 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end(); 1424 UI != E; ) { 1425 Use &TheUse = UI.getUse(); 1426 Instruction *User = cast<Instruction>(*UI); 1427 1428 // Preincrement use iterator so we don't invalidate it. 1429 ++UI; 1430 1431 // Don't bother for PHI nodes. 1432 if (isa<PHINode>(User)) 1433 continue; 1434 1435 // Figure out which BB this cmp is used in. 1436 BasicBlock *UserBB = User->getParent(); 1437 BasicBlock *DefBB = Cmp->getParent(); 1438 1439 // If this user is in the same block as the cmp, don't change the cmp. 1440 if (UserBB == DefBB) continue; 1441 1442 // If we have already inserted a cmp into this block, use it. 1443 CmpInst *&InsertedCmp = InsertedCmps[UserBB]; 1444 1445 if (!InsertedCmp) { 1446 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); 1447 assert(InsertPt != UserBB->end()); 1448 InsertedCmp = 1449 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), 1450 Cmp->getOperand(0), Cmp->getOperand(1), "", 1451 &*InsertPt); 1452 // Propagate the debug info. 1453 InsertedCmp->setDebugLoc(Cmp->getDebugLoc()); 1454 } 1455 1456 // Replace a use of the cmp with a use of the new cmp. 1457 TheUse = InsertedCmp; 1458 MadeChange = true; 1459 ++NumCmpUses; 1460 } 1461 1462 // If we removed all uses, nuke the cmp. 1463 if (Cmp->use_empty()) { 1464 Cmp->eraseFromParent(); 1465 MadeChange = true; 1466 } 1467 1468 return MadeChange; 1469 } 1470 1471 /// For pattern like: 1472 /// 1473 /// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB) 1474 /// ... 1475 /// DomBB: 1476 /// ... 1477 /// br DomCond, TrueBB, CmpBB 1478 /// CmpBB: (with DomBB being the single predecessor) 1479 /// ... 1480 /// Cmp = icmp eq CmpOp0, CmpOp1 1481 /// ... 1482 /// 1483 /// It would use two comparison on targets that lowering of icmp sgt/slt is 1484 /// different from lowering of icmp eq (PowerPC). This function try to convert 1485 /// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'. 1486 /// After that, DomCond and Cmp can use the same comparison so reduce one 1487 /// comparison. 1488 /// 1489 /// Return true if any changes are made. 1490 static bool foldICmpWithDominatingICmp(CmpInst *Cmp, 1491 const TargetLowering &TLI) { 1492 if (!EnableICMP_EQToICMP_ST && TLI.isEqualityCmpFoldedWithSignedCmp()) 1493 return false; 1494 1495 ICmpInst::Predicate Pred = Cmp->getPredicate(); 1496 if (Pred != ICmpInst::ICMP_EQ) 1497 return false; 1498 1499 // If icmp eq has users other than BranchInst and SelectInst, converting it to 1500 // icmp slt/sgt would introduce more redundant LLVM IR. 1501 for (User *U : Cmp->users()) { 1502 if (isa<BranchInst>(U)) 1503 continue; 1504 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp) 1505 continue; 1506 return false; 1507 } 1508 1509 // This is a cheap/incomplete check for dominance - just match a single 1510 // predecessor with a conditional branch. 1511 BasicBlock *CmpBB = Cmp->getParent(); 1512 BasicBlock *DomBB = CmpBB->getSinglePredecessor(); 1513 if (!DomBB) 1514 return false; 1515 1516 // We want to ensure that the only way control gets to the comparison of 1517 // interest is that a less/greater than comparison on the same operands is 1518 // false. 1519 Value *DomCond; 1520 BasicBlock *TrueBB, *FalseBB; 1521 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB))) 1522 return false; 1523 if (CmpBB != FalseBB) 1524 return false; 1525 1526 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1); 1527 ICmpInst::Predicate DomPred; 1528 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1)))) 1529 return false; 1530 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT) 1531 return false; 1532 1533 // Convert the equality comparison to the opposite of the dominating 1534 // comparison and swap the direction for all branch/select users. 1535 // We have conceptually converted: 1536 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>; 1537 // to 1538 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>; 1539 // And similarly for branches. 1540 for (User *U : Cmp->users()) { 1541 if (auto *BI = dyn_cast<BranchInst>(U)) { 1542 assert(BI->isConditional() && "Must be conditional"); 1543 BI->swapSuccessors(); 1544 continue; 1545 } 1546 if (auto *SI = dyn_cast<SelectInst>(U)) { 1547 // Swap operands 1548 SI->swapValues(); 1549 SI->swapProfMetadata(); 1550 continue; 1551 } 1552 llvm_unreachable("Must be a branch or a select"); 1553 } 1554 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred)); 1555 return true; 1556 } 1557 1558 bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) { 1559 if (sinkCmpExpression(Cmp, *TLI)) 1560 return true; 1561 1562 if (combineToUAddWithOverflow(Cmp, ModifiedDT)) 1563 return true; 1564 1565 if (combineToUSubWithOverflow(Cmp, ModifiedDT)) 1566 return true; 1567 1568 if (foldICmpWithDominatingICmp(Cmp, *TLI)) 1569 return true; 1570 1571 return false; 1572 } 1573 1574 /// Duplicate and sink the given 'and' instruction into user blocks where it is 1575 /// used in a compare to allow isel to generate better code for targets where 1576 /// this operation can be combined. 1577 /// 1578 /// Return true if any changes are made. 1579 static bool sinkAndCmp0Expression(Instruction *AndI, 1580 const TargetLowering &TLI, 1581 SetOfInstrs &InsertedInsts) { 1582 // Double-check that we're not trying to optimize an instruction that was 1583 // already optimized by some other part of this pass. 1584 assert(!InsertedInsts.count(AndI) && 1585 "Attempting to optimize already optimized and instruction"); 1586 (void) InsertedInsts; 1587 1588 // Nothing to do for single use in same basic block. 1589 if (AndI->hasOneUse() && 1590 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent()) 1591 return false; 1592 1593 // Try to avoid cases where sinking/duplicating is likely to increase register 1594 // pressure. 1595 if (!isa<ConstantInt>(AndI->getOperand(0)) && 1596 !isa<ConstantInt>(AndI->getOperand(1)) && 1597 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse()) 1598 return false; 1599 1600 for (auto *U : AndI->users()) { 1601 Instruction *User = cast<Instruction>(U); 1602 1603 // Only sink 'and' feeding icmp with 0. 1604 if (!isa<ICmpInst>(User)) 1605 return false; 1606 1607 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1)); 1608 if (!CmpC || !CmpC->isZero()) 1609 return false; 1610 } 1611 1612 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI)) 1613 return false; 1614 1615 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n"); 1616 LLVM_DEBUG(AndI->getParent()->dump()); 1617 1618 // Push the 'and' into the same block as the icmp 0. There should only be 1619 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any 1620 // others, so we don't need to keep track of which BBs we insert into. 1621 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end(); 1622 UI != E; ) { 1623 Use &TheUse = UI.getUse(); 1624 Instruction *User = cast<Instruction>(*UI); 1625 1626 // Preincrement use iterator so we don't invalidate it. 1627 ++UI; 1628 1629 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n"); 1630 1631 // Keep the 'and' in the same place if the use is already in the same block. 1632 Instruction *InsertPt = 1633 User->getParent() == AndI->getParent() ? AndI : User; 1634 Instruction *InsertedAnd = 1635 BinaryOperator::Create(Instruction::And, AndI->getOperand(0), 1636 AndI->getOperand(1), "", InsertPt); 1637 // Propagate the debug info. 1638 InsertedAnd->setDebugLoc(AndI->getDebugLoc()); 1639 1640 // Replace a use of the 'and' with a use of the new 'and'. 1641 TheUse = InsertedAnd; 1642 ++NumAndUses; 1643 LLVM_DEBUG(User->getParent()->dump()); 1644 } 1645 1646 // We removed all uses, nuke the and. 1647 AndI->eraseFromParent(); 1648 return true; 1649 } 1650 1651 /// Check if the candidates could be combined with a shift instruction, which 1652 /// includes: 1653 /// 1. Truncate instruction 1654 /// 2. And instruction and the imm is a mask of the low bits: 1655 /// imm & (imm+1) == 0 1656 static bool isExtractBitsCandidateUse(Instruction *User) { 1657 if (!isa<TruncInst>(User)) { 1658 if (User->getOpcode() != Instruction::And || 1659 !isa<ConstantInt>(User->getOperand(1))) 1660 return false; 1661 1662 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); 1663 1664 if ((Cimm & (Cimm + 1)).getBoolValue()) 1665 return false; 1666 } 1667 return true; 1668 } 1669 1670 /// Sink both shift and truncate instruction to the use of truncate's BB. 1671 static bool 1672 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, 1673 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, 1674 const TargetLowering &TLI, const DataLayout &DL) { 1675 BasicBlock *UserBB = User->getParent(); 1676 DenseMap<BasicBlock *, CastInst *> InsertedTruncs; 1677 auto *TruncI = cast<TruncInst>(User); 1678 bool MadeChange = false; 1679 1680 for (Value::user_iterator TruncUI = TruncI->user_begin(), 1681 TruncE = TruncI->user_end(); 1682 TruncUI != TruncE;) { 1683 1684 Use &TruncTheUse = TruncUI.getUse(); 1685 Instruction *TruncUser = cast<Instruction>(*TruncUI); 1686 // Preincrement use iterator so we don't invalidate it. 1687 1688 ++TruncUI; 1689 1690 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); 1691 if (!ISDOpcode) 1692 continue; 1693 1694 // If the use is actually a legal node, there will not be an 1695 // implicit truncate. 1696 // FIXME: always querying the result type is just an 1697 // approximation; some nodes' legality is determined by the 1698 // operand or other means. There's no good way to find out though. 1699 if (TLI.isOperationLegalOrCustom( 1700 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) 1701 continue; 1702 1703 // Don't bother for PHI nodes. 1704 if (isa<PHINode>(TruncUser)) 1705 continue; 1706 1707 BasicBlock *TruncUserBB = TruncUser->getParent(); 1708 1709 if (UserBB == TruncUserBB) 1710 continue; 1711 1712 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; 1713 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; 1714 1715 if (!InsertedShift && !InsertedTrunc) { 1716 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); 1717 assert(InsertPt != TruncUserBB->end()); 1718 // Sink the shift 1719 if (ShiftI->getOpcode() == Instruction::AShr) 1720 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, 1721 "", &*InsertPt); 1722 else 1723 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, 1724 "", &*InsertPt); 1725 InsertedShift->setDebugLoc(ShiftI->getDebugLoc()); 1726 1727 // Sink the trunc 1728 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); 1729 TruncInsertPt++; 1730 assert(TruncInsertPt != TruncUserBB->end()); 1731 1732 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, 1733 TruncI->getType(), "", &*TruncInsertPt); 1734 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc()); 1735 1736 MadeChange = true; 1737 1738 TruncTheUse = InsertedTrunc; 1739 } 1740 } 1741 return MadeChange; 1742 } 1743 1744 /// Sink the shift *right* instruction into user blocks if the uses could 1745 /// potentially be combined with this shift instruction and generate BitExtract 1746 /// instruction. It will only be applied if the architecture supports BitExtract 1747 /// instruction. Here is an example: 1748 /// BB1: 1749 /// %x.extract.shift = lshr i64 %arg1, 32 1750 /// BB2: 1751 /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 1752 /// ==> 1753 /// 1754 /// BB2: 1755 /// %x.extract.shift.1 = lshr i64 %arg1, 32 1756 /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 1757 /// 1758 /// CodeGen will recognize the pattern in BB2 and generate BitExtract 1759 /// instruction. 1760 /// Return true if any changes are made. 1761 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, 1762 const TargetLowering &TLI, 1763 const DataLayout &DL) { 1764 BasicBlock *DefBB = ShiftI->getParent(); 1765 1766 /// Only insert instructions in each block once. 1767 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; 1768 1769 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); 1770 1771 bool MadeChange = false; 1772 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); 1773 UI != E;) { 1774 Use &TheUse = UI.getUse(); 1775 Instruction *User = cast<Instruction>(*UI); 1776 // Preincrement use iterator so we don't invalidate it. 1777 ++UI; 1778 1779 // Don't bother for PHI nodes. 1780 if (isa<PHINode>(User)) 1781 continue; 1782 1783 if (!isExtractBitsCandidateUse(User)) 1784 continue; 1785 1786 BasicBlock *UserBB = User->getParent(); 1787 1788 if (UserBB == DefBB) { 1789 // If the shift and truncate instruction are in the same BB. The use of 1790 // the truncate(TruncUse) may still introduce another truncate if not 1791 // legal. In this case, we would like to sink both shift and truncate 1792 // instruction to the BB of TruncUse. 1793 // for example: 1794 // BB1: 1795 // i64 shift.result = lshr i64 opnd, imm 1796 // trunc.result = trunc shift.result to i16 1797 // 1798 // BB2: 1799 // ----> We will have an implicit truncate here if the architecture does 1800 // not have i16 compare. 1801 // cmp i16 trunc.result, opnd2 1802 // 1803 if (isa<TruncInst>(User) && shiftIsLegal 1804 // If the type of the truncate is legal, no truncate will be 1805 // introduced in other basic blocks. 1806 && 1807 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) 1808 MadeChange = 1809 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); 1810 1811 continue; 1812 } 1813 // If we have already inserted a shift into this block, use it. 1814 BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; 1815 1816 if (!InsertedShift) { 1817 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); 1818 assert(InsertPt != UserBB->end()); 1819 1820 if (ShiftI->getOpcode() == Instruction::AShr) 1821 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, 1822 "", &*InsertPt); 1823 else 1824 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, 1825 "", &*InsertPt); 1826 InsertedShift->setDebugLoc(ShiftI->getDebugLoc()); 1827 1828 MadeChange = true; 1829 } 1830 1831 // Replace a use of the shift with a use of the new shift. 1832 TheUse = InsertedShift; 1833 } 1834 1835 // If we removed all uses, or there are none, nuke the shift. 1836 if (ShiftI->use_empty()) { 1837 salvageDebugInfo(*ShiftI); 1838 ShiftI->eraseFromParent(); 1839 MadeChange = true; 1840 } 1841 1842 return MadeChange; 1843 } 1844 1845 /// If counting leading or trailing zeros is an expensive operation and a zero 1846 /// input is defined, add a check for zero to avoid calling the intrinsic. 1847 /// 1848 /// We want to transform: 1849 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) 1850 /// 1851 /// into: 1852 /// entry: 1853 /// %cmpz = icmp eq i64 %A, 0 1854 /// br i1 %cmpz, label %cond.end, label %cond.false 1855 /// cond.false: 1856 /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) 1857 /// br label %cond.end 1858 /// cond.end: 1859 /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] 1860 /// 1861 /// If the transform is performed, return true and set ModifiedDT to true. 1862 static bool despeculateCountZeros(IntrinsicInst *CountZeros, 1863 const TargetLowering *TLI, 1864 const DataLayout *DL, 1865 bool &ModifiedDT) { 1866 // If a zero input is undefined, it doesn't make sense to despeculate that. 1867 if (match(CountZeros->getOperand(1), m_One())) 1868 return false; 1869 1870 // If it's cheap to speculate, there's nothing to do. 1871 auto IntrinsicID = CountZeros->getIntrinsicID(); 1872 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || 1873 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) 1874 return false; 1875 1876 // Only handle legal scalar cases. Anything else requires too much work. 1877 Type *Ty = CountZeros->getType(); 1878 unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); 1879 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) 1880 return false; 1881 1882 // The intrinsic will be sunk behind a compare against zero and branch. 1883 BasicBlock *StartBlock = CountZeros->getParent(); 1884 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); 1885 1886 // Create another block after the count zero intrinsic. A PHI will be added 1887 // in this block to select the result of the intrinsic or the bit-width 1888 // constant if the input to the intrinsic is zero. 1889 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); 1890 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); 1891 1892 // Set up a builder to create a compare, conditional branch, and PHI. 1893 IRBuilder<> Builder(CountZeros->getContext()); 1894 Builder.SetInsertPoint(StartBlock->getTerminator()); 1895 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); 1896 1897 // Replace the unconditional branch that was created by the first split with 1898 // a compare against zero and a conditional branch. 1899 Value *Zero = Constant::getNullValue(Ty); 1900 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); 1901 Builder.CreateCondBr(Cmp, EndBlock, CallBlock); 1902 StartBlock->getTerminator()->eraseFromParent(); 1903 1904 // Create a PHI in the end block to select either the output of the intrinsic 1905 // or the bit width of the operand. 1906 Builder.SetInsertPoint(&EndBlock->front()); 1907 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); 1908 CountZeros->replaceAllUsesWith(PN); 1909 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); 1910 PN->addIncoming(BitWidth, StartBlock); 1911 PN->addIncoming(CountZeros, CallBlock); 1912 1913 // We are explicitly handling the zero case, so we can set the intrinsic's 1914 // undefined zero argument to 'true'. This will also prevent reprocessing the 1915 // intrinsic; we only despeculate when a zero input is defined. 1916 CountZeros->setArgOperand(1, Builder.getTrue()); 1917 ModifiedDT = true; 1918 return true; 1919 } 1920 1921 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) { 1922 BasicBlock *BB = CI->getParent(); 1923 1924 // Lower inline assembly if we can. 1925 // If we found an inline asm expession, and if the target knows how to 1926 // lower it to normal LLVM code, do so now. 1927 if (CI->isInlineAsm()) { 1928 if (TLI->ExpandInlineAsm(CI)) { 1929 // Avoid invalidating the iterator. 1930 CurInstIterator = BB->begin(); 1931 // Avoid processing instructions out of order, which could cause 1932 // reuse before a value is defined. 1933 SunkAddrs.clear(); 1934 return true; 1935 } 1936 // Sink address computing for memory operands into the block. 1937 if (optimizeInlineAsmInst(CI)) 1938 return true; 1939 } 1940 1941 // Align the pointer arguments to this call if the target thinks it's a good 1942 // idea 1943 unsigned MinSize, PrefAlign; 1944 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { 1945 for (auto &Arg : CI->arg_operands()) { 1946 // We want to align both objects whose address is used directly and 1947 // objects whose address is used in casts and GEPs, though it only makes 1948 // sense for GEPs if the offset is a multiple of the desired alignment and 1949 // if size - offset meets the size threshold. 1950 if (!Arg->getType()->isPointerTy()) 1951 continue; 1952 APInt Offset(DL->getIndexSizeInBits( 1953 cast<PointerType>(Arg->getType())->getAddressSpace()), 1954 0); 1955 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); 1956 uint64_t Offset2 = Offset.getLimitedValue(); 1957 if ((Offset2 & (PrefAlign-1)) != 0) 1958 continue; 1959 AllocaInst *AI; 1960 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && 1961 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) 1962 AI->setAlignment(Align(PrefAlign)); 1963 // Global variables can only be aligned if they are defined in this 1964 // object (i.e. they are uniquely initialized in this object), and 1965 // over-aligning global variables that have an explicit section is 1966 // forbidden. 1967 GlobalVariable *GV; 1968 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && 1969 GV->getPointerAlignment(*DL) < PrefAlign && 1970 DL->getTypeAllocSize(GV->getValueType()) >= 1971 MinSize + Offset2) 1972 GV->setAlignment(MaybeAlign(PrefAlign)); 1973 } 1974 // If this is a memcpy (or similar) then we may be able to improve the 1975 // alignment 1976 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { 1977 Align DestAlign = getKnownAlignment(MI->getDest(), *DL); 1978 MaybeAlign MIDestAlign = MI->getDestAlign(); 1979 if (!MIDestAlign || DestAlign > *MIDestAlign) 1980 MI->setDestAlignment(DestAlign); 1981 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { 1982 MaybeAlign MTISrcAlign = MTI->getSourceAlign(); 1983 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL); 1984 if (!MTISrcAlign || SrcAlign > *MTISrcAlign) 1985 MTI->setSourceAlignment(SrcAlign); 1986 } 1987 } 1988 } 1989 1990 // If we have a cold call site, try to sink addressing computation into the 1991 // cold block. This interacts with our handling for loads and stores to 1992 // ensure that we can fold all uses of a potential addressing computation 1993 // into their uses. TODO: generalize this to work over profiling data 1994 if (CI->hasFnAttr(Attribute::Cold) && 1995 !OptSize && !llvm::shouldOptimizeForSize(BB, PSI, BFI.get())) 1996 for (auto &Arg : CI->arg_operands()) { 1997 if (!Arg->getType()->isPointerTy()) 1998 continue; 1999 unsigned AS = Arg->getType()->getPointerAddressSpace(); 2000 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); 2001 } 2002 2003 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); 2004 if (II) { 2005 switch (II->getIntrinsicID()) { 2006 default: break; 2007 case Intrinsic::assume: { 2008 II->eraseFromParent(); 2009 return true; 2010 } 2011 2012 case Intrinsic::experimental_widenable_condition: { 2013 // Give up on future widening oppurtunties so that we can fold away dead 2014 // paths and merge blocks before going into block-local instruction 2015 // selection. 2016 if (II->use_empty()) { 2017 II->eraseFromParent(); 2018 return true; 2019 } 2020 Constant *RetVal = ConstantInt::getTrue(II->getContext()); 2021 resetIteratorIfInvalidatedWhileCalling(BB, [&]() { 2022 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); 2023 }); 2024 return true; 2025 } 2026 case Intrinsic::objectsize: 2027 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 2028 case Intrinsic::is_constant: 2029 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 2030 case Intrinsic::aarch64_stlxr: 2031 case Intrinsic::aarch64_stxr: { 2032 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); 2033 if (!ExtVal || !ExtVal->hasOneUse() || 2034 ExtVal->getParent() == CI->getParent()) 2035 return false; 2036 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. 2037 ExtVal->moveBefore(CI); 2038 // Mark this instruction as "inserted by CGP", so that other 2039 // optimizations don't touch it. 2040 InsertedInsts.insert(ExtVal); 2041 return true; 2042 } 2043 2044 case Intrinsic::launder_invariant_group: 2045 case Intrinsic::strip_invariant_group: { 2046 Value *ArgVal = II->getArgOperand(0); 2047 auto it = LargeOffsetGEPMap.find(II); 2048 if (it != LargeOffsetGEPMap.end()) { 2049 // Merge entries in LargeOffsetGEPMap to reflect the RAUW. 2050 // Make sure not to have to deal with iterator invalidation 2051 // after possibly adding ArgVal to LargeOffsetGEPMap. 2052 auto GEPs = std::move(it->second); 2053 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end()); 2054 LargeOffsetGEPMap.erase(II); 2055 } 2056 2057 II->replaceAllUsesWith(ArgVal); 2058 II->eraseFromParent(); 2059 return true; 2060 } 2061 case Intrinsic::cttz: 2062 case Intrinsic::ctlz: 2063 // If counting zeros is expensive, try to avoid it. 2064 return despeculateCountZeros(II, TLI, DL, ModifiedDT); 2065 case Intrinsic::fshl: 2066 case Intrinsic::fshr: 2067 return optimizeFunnelShift(II); 2068 case Intrinsic::dbg_value: 2069 return fixupDbgValue(II); 2070 case Intrinsic::vscale: { 2071 // If datalayout has no special restrictions on vector data layout, 2072 // replace `llvm.vscale` by an equivalent constant expression 2073 // to benefit from cheap constant propagation. 2074 Type *ScalableVectorTy = 2075 VectorType::get(Type::getInt8Ty(II->getContext()), 1, true); 2076 if (DL->getTypeAllocSize(ScalableVectorTy).getKnownMinSize() == 8) { 2077 auto Null = Constant::getNullValue(ScalableVectorTy->getPointerTo()); 2078 auto One = ConstantInt::getSigned(II->getType(), 1); 2079 auto *CGep = 2080 ConstantExpr::getGetElementPtr(ScalableVectorTy, Null, One); 2081 II->replaceAllUsesWith(ConstantExpr::getPtrToInt(CGep, II->getType())); 2082 II->eraseFromParent(); 2083 return true; 2084 } 2085 break; 2086 } 2087 case Intrinsic::masked_gather: 2088 return optimizeGatherScatterInst(II, II->getArgOperand(0)); 2089 case Intrinsic::masked_scatter: 2090 return optimizeGatherScatterInst(II, II->getArgOperand(1)); 2091 } 2092 2093 SmallVector<Value *, 2> PtrOps; 2094 Type *AccessTy; 2095 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy)) 2096 while (!PtrOps.empty()) { 2097 Value *PtrVal = PtrOps.pop_back_val(); 2098 unsigned AS = PtrVal->getType()->getPointerAddressSpace(); 2099 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS)) 2100 return true; 2101 } 2102 } 2103 2104 // From here on out we're working with named functions. 2105 if (!CI->getCalledFunction()) return false; 2106 2107 // Lower all default uses of _chk calls. This is very similar 2108 // to what InstCombineCalls does, but here we are only lowering calls 2109 // to fortified library functions (e.g. __memcpy_chk) that have the default 2110 // "don't know" as the objectsize. Anything else should be left alone. 2111 FortifiedLibCallSimplifier Simplifier(TLInfo, true); 2112 IRBuilder<> Builder(CI); 2113 if (Value *V = Simplifier.optimizeCall(CI, Builder)) { 2114 CI->replaceAllUsesWith(V); 2115 CI->eraseFromParent(); 2116 return true; 2117 } 2118 2119 return false; 2120 } 2121 2122 /// Look for opportunities to duplicate return instructions to the predecessor 2123 /// to enable tail call optimizations. The case it is currently looking for is: 2124 /// @code 2125 /// bb0: 2126 /// %tmp0 = tail call i32 @f0() 2127 /// br label %return 2128 /// bb1: 2129 /// %tmp1 = tail call i32 @f1() 2130 /// br label %return 2131 /// bb2: 2132 /// %tmp2 = tail call i32 @f2() 2133 /// br label %return 2134 /// return: 2135 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] 2136 /// ret i32 %retval 2137 /// @endcode 2138 /// 2139 /// => 2140 /// 2141 /// @code 2142 /// bb0: 2143 /// %tmp0 = tail call i32 @f0() 2144 /// ret i32 %tmp0 2145 /// bb1: 2146 /// %tmp1 = tail call i32 @f1() 2147 /// ret i32 %tmp1 2148 /// bb2: 2149 /// %tmp2 = tail call i32 @f2() 2150 /// ret i32 %tmp2 2151 /// @endcode 2152 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) { 2153 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); 2154 if (!RetI) 2155 return false; 2156 2157 PHINode *PN = nullptr; 2158 ExtractValueInst *EVI = nullptr; 2159 BitCastInst *BCI = nullptr; 2160 Value *V = RetI->getReturnValue(); 2161 if (V) { 2162 BCI = dyn_cast<BitCastInst>(V); 2163 if (BCI) 2164 V = BCI->getOperand(0); 2165 2166 EVI = dyn_cast<ExtractValueInst>(V); 2167 if (EVI) { 2168 V = EVI->getOperand(0); 2169 if (!std::all_of(EVI->idx_begin(), EVI->idx_end(), 2170 [](unsigned idx) { return idx == 0; })) 2171 return false; 2172 } 2173 2174 PN = dyn_cast<PHINode>(V); 2175 if (!PN) 2176 return false; 2177 } 2178 2179 if (PN && PN->getParent() != BB) 2180 return false; 2181 2182 // Make sure there are no instructions between the PHI and return, or that the 2183 // return is the first instruction in the block. 2184 if (PN) { 2185 BasicBlock::iterator BI = BB->begin(); 2186 // Skip over debug and the bitcast. 2187 do { 2188 ++BI; 2189 } while (isa<DbgInfoIntrinsic>(BI) || &*BI == BCI || &*BI == EVI); 2190 if (&*BI != RetI) 2191 return false; 2192 } else { 2193 BasicBlock::iterator BI = BB->begin(); 2194 while (isa<DbgInfoIntrinsic>(BI)) ++BI; 2195 if (&*BI != RetI) 2196 return false; 2197 } 2198 2199 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail 2200 /// call. 2201 const Function *F = BB->getParent(); 2202 SmallVector<BasicBlock*, 4> TailCallBBs; 2203 if (PN) { 2204 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { 2205 // Look through bitcasts. 2206 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts(); 2207 CallInst *CI = dyn_cast<CallInst>(IncomingVal); 2208 BasicBlock *PredBB = PN->getIncomingBlock(I); 2209 // Make sure the phi value is indeed produced by the tail call. 2210 if (CI && CI->hasOneUse() && CI->getParent() == PredBB && 2211 TLI->mayBeEmittedAsTailCall(CI) && 2212 attributesPermitTailCall(F, CI, RetI, *TLI)) 2213 TailCallBBs.push_back(PredBB); 2214 } 2215 } else { 2216 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 2217 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) { 2218 if (!VisitedBBs.insert(*PI).second) 2219 continue; 2220 2221 BasicBlock::InstListType &InstList = (*PI)->getInstList(); 2222 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); 2223 BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); 2224 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); 2225 if (RI == RE) 2226 continue; 2227 2228 CallInst *CI = dyn_cast<CallInst>(&*RI); 2229 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && 2230 attributesPermitTailCall(F, CI, RetI, *TLI)) 2231 TailCallBBs.push_back(*PI); 2232 } 2233 } 2234 2235 bool Changed = false; 2236 for (auto const &TailCallBB : TailCallBBs) { 2237 // Make sure the call instruction is followed by an unconditional branch to 2238 // the return block. 2239 BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator()); 2240 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) 2241 continue; 2242 2243 // Duplicate the return into TailCallBB. 2244 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB); 2245 assert(!VerifyBFIUpdates || 2246 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB)); 2247 BFI->setBlockFreq( 2248 BB, 2249 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency()); 2250 ModifiedDT = Changed = true; 2251 ++NumRetsDup; 2252 } 2253 2254 // If we eliminated all predecessors of the block, delete the block now. 2255 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) 2256 BB->eraseFromParent(); 2257 2258 return Changed; 2259 } 2260 2261 //===----------------------------------------------------------------------===// 2262 // Memory Optimization 2263 //===----------------------------------------------------------------------===// 2264 2265 namespace { 2266 2267 /// This is an extended version of TargetLowering::AddrMode 2268 /// which holds actual Value*'s for register values. 2269 struct ExtAddrMode : public TargetLowering::AddrMode { 2270 Value *BaseReg = nullptr; 2271 Value *ScaledReg = nullptr; 2272 Value *OriginalValue = nullptr; 2273 bool InBounds = true; 2274 2275 enum FieldName { 2276 NoField = 0x00, 2277 BaseRegField = 0x01, 2278 BaseGVField = 0x02, 2279 BaseOffsField = 0x04, 2280 ScaledRegField = 0x08, 2281 ScaleField = 0x10, 2282 MultipleFields = 0xff 2283 }; 2284 2285 2286 ExtAddrMode() = default; 2287 2288 void print(raw_ostream &OS) const; 2289 void dump() const; 2290 2291 FieldName compare(const ExtAddrMode &other) { 2292 // First check that the types are the same on each field, as differing types 2293 // is something we can't cope with later on. 2294 if (BaseReg && other.BaseReg && 2295 BaseReg->getType() != other.BaseReg->getType()) 2296 return MultipleFields; 2297 if (BaseGV && other.BaseGV && 2298 BaseGV->getType() != other.BaseGV->getType()) 2299 return MultipleFields; 2300 if (ScaledReg && other.ScaledReg && 2301 ScaledReg->getType() != other.ScaledReg->getType()) 2302 return MultipleFields; 2303 2304 // Conservatively reject 'inbounds' mismatches. 2305 if (InBounds != other.InBounds) 2306 return MultipleFields; 2307 2308 // Check each field to see if it differs. 2309 unsigned Result = NoField; 2310 if (BaseReg != other.BaseReg) 2311 Result |= BaseRegField; 2312 if (BaseGV != other.BaseGV) 2313 Result |= BaseGVField; 2314 if (BaseOffs != other.BaseOffs) 2315 Result |= BaseOffsField; 2316 if (ScaledReg != other.ScaledReg) 2317 Result |= ScaledRegField; 2318 // Don't count 0 as being a different scale, because that actually means 2319 // unscaled (which will already be counted by having no ScaledReg). 2320 if (Scale && other.Scale && Scale != other.Scale) 2321 Result |= ScaleField; 2322 2323 if (countPopulation(Result) > 1) 2324 return MultipleFields; 2325 else 2326 return static_cast<FieldName>(Result); 2327 } 2328 2329 // An AddrMode is trivial if it involves no calculation i.e. it is just a base 2330 // with no offset. 2331 bool isTrivial() { 2332 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is 2333 // trivial if at most one of these terms is nonzero, except that BaseGV and 2334 // BaseReg both being zero actually means a null pointer value, which we 2335 // consider to be 'non-zero' here. 2336 return !BaseOffs && !Scale && !(BaseGV && BaseReg); 2337 } 2338 2339 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) { 2340 switch (Field) { 2341 default: 2342 return nullptr; 2343 case BaseRegField: 2344 return BaseReg; 2345 case BaseGVField: 2346 return BaseGV; 2347 case ScaledRegField: 2348 return ScaledReg; 2349 case BaseOffsField: 2350 return ConstantInt::get(IntPtrTy, BaseOffs); 2351 } 2352 } 2353 2354 void SetCombinedField(FieldName Field, Value *V, 2355 const SmallVectorImpl<ExtAddrMode> &AddrModes) { 2356 switch (Field) { 2357 default: 2358 llvm_unreachable("Unhandled fields are expected to be rejected earlier"); 2359 break; 2360 case ExtAddrMode::BaseRegField: 2361 BaseReg = V; 2362 break; 2363 case ExtAddrMode::BaseGVField: 2364 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes 2365 // in the BaseReg field. 2366 assert(BaseReg == nullptr); 2367 BaseReg = V; 2368 BaseGV = nullptr; 2369 break; 2370 case ExtAddrMode::ScaledRegField: 2371 ScaledReg = V; 2372 // If we have a mix of scaled and unscaled addrmodes then we want scale 2373 // to be the scale and not zero. 2374 if (!Scale) 2375 for (const ExtAddrMode &AM : AddrModes) 2376 if (AM.Scale) { 2377 Scale = AM.Scale; 2378 break; 2379 } 2380 break; 2381 case ExtAddrMode::BaseOffsField: 2382 // The offset is no longer a constant, so it goes in ScaledReg with a 2383 // scale of 1. 2384 assert(ScaledReg == nullptr); 2385 ScaledReg = V; 2386 Scale = 1; 2387 BaseOffs = 0; 2388 break; 2389 } 2390 } 2391 }; 2392 2393 } // end anonymous namespace 2394 2395 #ifndef NDEBUG 2396 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { 2397 AM.print(OS); 2398 return OS; 2399 } 2400 #endif 2401 2402 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2403 void ExtAddrMode::print(raw_ostream &OS) const { 2404 bool NeedPlus = false; 2405 OS << "["; 2406 if (InBounds) 2407 OS << "inbounds "; 2408 if (BaseGV) { 2409 OS << (NeedPlus ? " + " : "") 2410 << "GV:"; 2411 BaseGV->printAsOperand(OS, /*PrintType=*/false); 2412 NeedPlus = true; 2413 } 2414 2415 if (BaseOffs) { 2416 OS << (NeedPlus ? " + " : "") 2417 << BaseOffs; 2418 NeedPlus = true; 2419 } 2420 2421 if (BaseReg) { 2422 OS << (NeedPlus ? " + " : "") 2423 << "Base:"; 2424 BaseReg->printAsOperand(OS, /*PrintType=*/false); 2425 NeedPlus = true; 2426 } 2427 if (Scale) { 2428 OS << (NeedPlus ? " + " : "") 2429 << Scale << "*"; 2430 ScaledReg->printAsOperand(OS, /*PrintType=*/false); 2431 } 2432 2433 OS << ']'; 2434 } 2435 2436 LLVM_DUMP_METHOD void ExtAddrMode::dump() const { 2437 print(dbgs()); 2438 dbgs() << '\n'; 2439 } 2440 #endif 2441 2442 namespace { 2443 2444 /// This class provides transaction based operation on the IR. 2445 /// Every change made through this class is recorded in the internal state and 2446 /// can be undone (rollback) until commit is called. 2447 class TypePromotionTransaction { 2448 /// This represents the common interface of the individual transaction. 2449 /// Each class implements the logic for doing one specific modification on 2450 /// the IR via the TypePromotionTransaction. 2451 class TypePromotionAction { 2452 protected: 2453 /// The Instruction modified. 2454 Instruction *Inst; 2455 2456 public: 2457 /// Constructor of the action. 2458 /// The constructor performs the related action on the IR. 2459 TypePromotionAction(Instruction *Inst) : Inst(Inst) {} 2460 2461 virtual ~TypePromotionAction() = default; 2462 2463 /// Undo the modification done by this action. 2464 /// When this method is called, the IR must be in the same state as it was 2465 /// before this action was applied. 2466 /// \pre Undoing the action works if and only if the IR is in the exact same 2467 /// state as it was directly after this action was applied. 2468 virtual void undo() = 0; 2469 2470 /// Advocate every change made by this action. 2471 /// When the results on the IR of the action are to be kept, it is important 2472 /// to call this function, otherwise hidden information may be kept forever. 2473 virtual void commit() { 2474 // Nothing to be done, this action is not doing anything. 2475 } 2476 }; 2477 2478 /// Utility to remember the position of an instruction. 2479 class InsertionHandler { 2480 /// Position of an instruction. 2481 /// Either an instruction: 2482 /// - Is the first in a basic block: BB is used. 2483 /// - Has a previous instruction: PrevInst is used. 2484 union { 2485 Instruction *PrevInst; 2486 BasicBlock *BB; 2487 } Point; 2488 2489 /// Remember whether or not the instruction had a previous instruction. 2490 bool HasPrevInstruction; 2491 2492 public: 2493 /// Record the position of \p Inst. 2494 InsertionHandler(Instruction *Inst) { 2495 BasicBlock::iterator It = Inst->getIterator(); 2496 HasPrevInstruction = (It != (Inst->getParent()->begin())); 2497 if (HasPrevInstruction) 2498 Point.PrevInst = &*--It; 2499 else 2500 Point.BB = Inst->getParent(); 2501 } 2502 2503 /// Insert \p Inst at the recorded position. 2504 void insert(Instruction *Inst) { 2505 if (HasPrevInstruction) { 2506 if (Inst->getParent()) 2507 Inst->removeFromParent(); 2508 Inst->insertAfter(Point.PrevInst); 2509 } else { 2510 Instruction *Position = &*Point.BB->getFirstInsertionPt(); 2511 if (Inst->getParent()) 2512 Inst->moveBefore(Position); 2513 else 2514 Inst->insertBefore(Position); 2515 } 2516 } 2517 }; 2518 2519 /// Move an instruction before another. 2520 class InstructionMoveBefore : public TypePromotionAction { 2521 /// Original position of the instruction. 2522 InsertionHandler Position; 2523 2524 public: 2525 /// Move \p Inst before \p Before. 2526 InstructionMoveBefore(Instruction *Inst, Instruction *Before) 2527 : TypePromotionAction(Inst), Position(Inst) { 2528 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before 2529 << "\n"); 2530 Inst->moveBefore(Before); 2531 } 2532 2533 /// Move the instruction back to its original position. 2534 void undo() override { 2535 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); 2536 Position.insert(Inst); 2537 } 2538 }; 2539 2540 /// Set the operand of an instruction with a new value. 2541 class OperandSetter : public TypePromotionAction { 2542 /// Original operand of the instruction. 2543 Value *Origin; 2544 2545 /// Index of the modified instruction. 2546 unsigned Idx; 2547 2548 public: 2549 /// Set \p Idx operand of \p Inst with \p NewVal. 2550 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) 2551 : TypePromotionAction(Inst), Idx(Idx) { 2552 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" 2553 << "for:" << *Inst << "\n" 2554 << "with:" << *NewVal << "\n"); 2555 Origin = Inst->getOperand(Idx); 2556 Inst->setOperand(Idx, NewVal); 2557 } 2558 2559 /// Restore the original value of the instruction. 2560 void undo() override { 2561 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" 2562 << "for: " << *Inst << "\n" 2563 << "with: " << *Origin << "\n"); 2564 Inst->setOperand(Idx, Origin); 2565 } 2566 }; 2567 2568 /// Hide the operands of an instruction. 2569 /// Do as if this instruction was not using any of its operands. 2570 class OperandsHider : public TypePromotionAction { 2571 /// The list of original operands. 2572 SmallVector<Value *, 4> OriginalValues; 2573 2574 public: 2575 /// Remove \p Inst from the uses of the operands of \p Inst. 2576 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { 2577 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); 2578 unsigned NumOpnds = Inst->getNumOperands(); 2579 OriginalValues.reserve(NumOpnds); 2580 for (unsigned It = 0; It < NumOpnds; ++It) { 2581 // Save the current operand. 2582 Value *Val = Inst->getOperand(It); 2583 OriginalValues.push_back(Val); 2584 // Set a dummy one. 2585 // We could use OperandSetter here, but that would imply an overhead 2586 // that we are not willing to pay. 2587 Inst->setOperand(It, UndefValue::get(Val->getType())); 2588 } 2589 } 2590 2591 /// Restore the original list of uses. 2592 void undo() override { 2593 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); 2594 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) 2595 Inst->setOperand(It, OriginalValues[It]); 2596 } 2597 }; 2598 2599 /// Build a truncate instruction. 2600 class TruncBuilder : public TypePromotionAction { 2601 Value *Val; 2602 2603 public: 2604 /// Build a truncate instruction of \p Opnd producing a \p Ty 2605 /// result. 2606 /// trunc Opnd to Ty. 2607 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { 2608 IRBuilder<> Builder(Opnd); 2609 Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); 2610 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); 2611 } 2612 2613 /// Get the built value. 2614 Value *getBuiltValue() { return Val; } 2615 2616 /// Remove the built instruction. 2617 void undo() override { 2618 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); 2619 if (Instruction *IVal = dyn_cast<Instruction>(Val)) 2620 IVal->eraseFromParent(); 2621 } 2622 }; 2623 2624 /// Build a sign extension instruction. 2625 class SExtBuilder : public TypePromotionAction { 2626 Value *Val; 2627 2628 public: 2629 /// Build a sign extension instruction of \p Opnd producing a \p Ty 2630 /// result. 2631 /// sext Opnd to Ty. 2632 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) 2633 : TypePromotionAction(InsertPt) { 2634 IRBuilder<> Builder(InsertPt); 2635 Val = Builder.CreateSExt(Opnd, Ty, "promoted"); 2636 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); 2637 } 2638 2639 /// Get the built value. 2640 Value *getBuiltValue() { return Val; } 2641 2642 /// Remove the built instruction. 2643 void undo() override { 2644 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); 2645 if (Instruction *IVal = dyn_cast<Instruction>(Val)) 2646 IVal->eraseFromParent(); 2647 } 2648 }; 2649 2650 /// Build a zero extension instruction. 2651 class ZExtBuilder : public TypePromotionAction { 2652 Value *Val; 2653 2654 public: 2655 /// Build a zero extension instruction of \p Opnd producing a \p Ty 2656 /// result. 2657 /// zext Opnd to Ty. 2658 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) 2659 : TypePromotionAction(InsertPt) { 2660 IRBuilder<> Builder(InsertPt); 2661 Val = Builder.CreateZExt(Opnd, Ty, "promoted"); 2662 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); 2663 } 2664 2665 /// Get the built value. 2666 Value *getBuiltValue() { return Val; } 2667 2668 /// Remove the built instruction. 2669 void undo() override { 2670 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); 2671 if (Instruction *IVal = dyn_cast<Instruction>(Val)) 2672 IVal->eraseFromParent(); 2673 } 2674 }; 2675 2676 /// Mutate an instruction to another type. 2677 class TypeMutator : public TypePromotionAction { 2678 /// Record the original type. 2679 Type *OrigTy; 2680 2681 public: 2682 /// Mutate the type of \p Inst into \p NewTy. 2683 TypeMutator(Instruction *Inst, Type *NewTy) 2684 : TypePromotionAction(Inst), OrigTy(Inst->getType()) { 2685 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy 2686 << "\n"); 2687 Inst->mutateType(NewTy); 2688 } 2689 2690 /// Mutate the instruction back to its original type. 2691 void undo() override { 2692 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy 2693 << "\n"); 2694 Inst->mutateType(OrigTy); 2695 } 2696 }; 2697 2698 /// Replace the uses of an instruction by another instruction. 2699 class UsesReplacer : public TypePromotionAction { 2700 /// Helper structure to keep track of the replaced uses. 2701 struct InstructionAndIdx { 2702 /// The instruction using the instruction. 2703 Instruction *Inst; 2704 2705 /// The index where this instruction is used for Inst. 2706 unsigned Idx; 2707 2708 InstructionAndIdx(Instruction *Inst, unsigned Idx) 2709 : Inst(Inst), Idx(Idx) {} 2710 }; 2711 2712 /// Keep track of the original uses (pair Instruction, Index). 2713 SmallVector<InstructionAndIdx, 4> OriginalUses; 2714 /// Keep track of the debug users. 2715 SmallVector<DbgValueInst *, 1> DbgValues; 2716 2717 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator; 2718 2719 public: 2720 /// Replace all the use of \p Inst by \p New. 2721 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { 2722 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New 2723 << "\n"); 2724 // Record the original uses. 2725 for (Use &U : Inst->uses()) { 2726 Instruction *UserI = cast<Instruction>(U.getUser()); 2727 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); 2728 } 2729 // Record the debug uses separately. They are not in the instruction's 2730 // use list, but they are replaced by RAUW. 2731 findDbgValues(DbgValues, Inst); 2732 2733 // Now, we can replace the uses. 2734 Inst->replaceAllUsesWith(New); 2735 } 2736 2737 /// Reassign the original uses of Inst to Inst. 2738 void undo() override { 2739 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); 2740 for (use_iterator UseIt = OriginalUses.begin(), 2741 EndIt = OriginalUses.end(); 2742 UseIt != EndIt; ++UseIt) { 2743 UseIt->Inst->setOperand(UseIt->Idx, Inst); 2744 } 2745 // RAUW has replaced all original uses with references to the new value, 2746 // including the debug uses. Since we are undoing the replacements, 2747 // the original debug uses must also be reinstated to maintain the 2748 // correctness and utility of debug value instructions. 2749 for (auto *DVI: DbgValues) { 2750 LLVMContext &Ctx = Inst->getType()->getContext(); 2751 auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst)); 2752 DVI->setOperand(0, MV); 2753 } 2754 } 2755 }; 2756 2757 /// Remove an instruction from the IR. 2758 class InstructionRemover : public TypePromotionAction { 2759 /// Original position of the instruction. 2760 InsertionHandler Inserter; 2761 2762 /// Helper structure to hide all the link to the instruction. In other 2763 /// words, this helps to do as if the instruction was removed. 2764 OperandsHider Hider; 2765 2766 /// Keep track of the uses replaced, if any. 2767 UsesReplacer *Replacer = nullptr; 2768 2769 /// Keep track of instructions removed. 2770 SetOfInstrs &RemovedInsts; 2771 2772 public: 2773 /// Remove all reference of \p Inst and optionally replace all its 2774 /// uses with New. 2775 /// \p RemovedInsts Keep track of the instructions removed by this Action. 2776 /// \pre If !Inst->use_empty(), then New != nullptr 2777 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts, 2778 Value *New = nullptr) 2779 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), 2780 RemovedInsts(RemovedInsts) { 2781 if (New) 2782 Replacer = new UsesReplacer(Inst, New); 2783 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); 2784 RemovedInsts.insert(Inst); 2785 /// The instructions removed here will be freed after completing 2786 /// optimizeBlock() for all blocks as we need to keep track of the 2787 /// removed instructions during promotion. 2788 Inst->removeFromParent(); 2789 } 2790 2791 ~InstructionRemover() override { delete Replacer; } 2792 2793 /// Resurrect the instruction and reassign it to the proper uses if 2794 /// new value was provided when build this action. 2795 void undo() override { 2796 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); 2797 Inserter.insert(Inst); 2798 if (Replacer) 2799 Replacer->undo(); 2800 Hider.undo(); 2801 RemovedInsts.erase(Inst); 2802 } 2803 }; 2804 2805 public: 2806 /// Restoration point. 2807 /// The restoration point is a pointer to an action instead of an iterator 2808 /// because the iterator may be invalidated but not the pointer. 2809 using ConstRestorationPt = const TypePromotionAction *; 2810 2811 TypePromotionTransaction(SetOfInstrs &RemovedInsts) 2812 : RemovedInsts(RemovedInsts) {} 2813 2814 /// Advocate every changes made in that transaction. 2815 void commit(); 2816 2817 /// Undo all the changes made after the given point. 2818 void rollback(ConstRestorationPt Point); 2819 2820 /// Get the current restoration point. 2821 ConstRestorationPt getRestorationPoint() const; 2822 2823 /// \name API for IR modification with state keeping to support rollback. 2824 /// @{ 2825 /// Same as Instruction::setOperand. 2826 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); 2827 2828 /// Same as Instruction::eraseFromParent. 2829 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); 2830 2831 /// Same as Value::replaceAllUsesWith. 2832 void replaceAllUsesWith(Instruction *Inst, Value *New); 2833 2834 /// Same as Value::mutateType. 2835 void mutateType(Instruction *Inst, Type *NewTy); 2836 2837 /// Same as IRBuilder::createTrunc. 2838 Value *createTrunc(Instruction *Opnd, Type *Ty); 2839 2840 /// Same as IRBuilder::createSExt. 2841 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); 2842 2843 /// Same as IRBuilder::createZExt. 2844 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); 2845 2846 /// Same as Instruction::moveBefore. 2847 void moveBefore(Instruction *Inst, Instruction *Before); 2848 /// @} 2849 2850 private: 2851 /// The ordered list of actions made so far. 2852 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; 2853 2854 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator; 2855 2856 SetOfInstrs &RemovedInsts; 2857 }; 2858 2859 } // end anonymous namespace 2860 2861 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, 2862 Value *NewVal) { 2863 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>( 2864 Inst, Idx, NewVal)); 2865 } 2866 2867 void TypePromotionTransaction::eraseInstruction(Instruction *Inst, 2868 Value *NewVal) { 2869 Actions.push_back( 2870 std::make_unique<TypePromotionTransaction::InstructionRemover>( 2871 Inst, RemovedInsts, NewVal)); 2872 } 2873 2874 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, 2875 Value *New) { 2876 Actions.push_back( 2877 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); 2878 } 2879 2880 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { 2881 Actions.push_back( 2882 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); 2883 } 2884 2885 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, 2886 Type *Ty) { 2887 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); 2888 Value *Val = Ptr->getBuiltValue(); 2889 Actions.push_back(std::move(Ptr)); 2890 return Val; 2891 } 2892 2893 Value *TypePromotionTransaction::createSExt(Instruction *Inst, 2894 Value *Opnd, Type *Ty) { 2895 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); 2896 Value *Val = Ptr->getBuiltValue(); 2897 Actions.push_back(std::move(Ptr)); 2898 return Val; 2899 } 2900 2901 Value *TypePromotionTransaction::createZExt(Instruction *Inst, 2902 Value *Opnd, Type *Ty) { 2903 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); 2904 Value *Val = Ptr->getBuiltValue(); 2905 Actions.push_back(std::move(Ptr)); 2906 return Val; 2907 } 2908 2909 void TypePromotionTransaction::moveBefore(Instruction *Inst, 2910 Instruction *Before) { 2911 Actions.push_back( 2912 std::make_unique<TypePromotionTransaction::InstructionMoveBefore>( 2913 Inst, Before)); 2914 } 2915 2916 TypePromotionTransaction::ConstRestorationPt 2917 TypePromotionTransaction::getRestorationPoint() const { 2918 return !Actions.empty() ? Actions.back().get() : nullptr; 2919 } 2920 2921 void TypePromotionTransaction::commit() { 2922 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; 2923 ++It) 2924 (*It)->commit(); 2925 Actions.clear(); 2926 } 2927 2928 void TypePromotionTransaction::rollback( 2929 TypePromotionTransaction::ConstRestorationPt Point) { 2930 while (!Actions.empty() && Point != Actions.back().get()) { 2931 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); 2932 Curr->undo(); 2933 } 2934 } 2935 2936 namespace { 2937 2938 /// A helper class for matching addressing modes. 2939 /// 2940 /// This encapsulates the logic for matching the target-legal addressing modes. 2941 class AddressingModeMatcher { 2942 SmallVectorImpl<Instruction*> &AddrModeInsts; 2943 const TargetLowering &TLI; 2944 const TargetRegisterInfo &TRI; 2945 const DataLayout &DL; 2946 2947 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and 2948 /// the memory instruction that we're computing this address for. 2949 Type *AccessTy; 2950 unsigned AddrSpace; 2951 Instruction *MemoryInst; 2952 2953 /// This is the addressing mode that we're building up. This is 2954 /// part of the return value of this addressing mode matching stuff. 2955 ExtAddrMode &AddrMode; 2956 2957 /// The instructions inserted by other CodeGenPrepare optimizations. 2958 const SetOfInstrs &InsertedInsts; 2959 2960 /// A map from the instructions to their type before promotion. 2961 InstrToOrigTy &PromotedInsts; 2962 2963 /// The ongoing transaction where every action should be registered. 2964 TypePromotionTransaction &TPT; 2965 2966 // A GEP which has too large offset to be folded into the addressing mode. 2967 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP; 2968 2969 /// This is set to true when we should not do profitability checks. 2970 /// When true, IsProfitableToFoldIntoAddressingMode always returns true. 2971 bool IgnoreProfitability; 2972 2973 /// True if we are optimizing for size. 2974 bool OptSize; 2975 2976 ProfileSummaryInfo *PSI; 2977 BlockFrequencyInfo *BFI; 2978 2979 AddressingModeMatcher( 2980 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI, 2981 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI, 2982 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts, 2983 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT, 2984 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP, 2985 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) 2986 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), 2987 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), 2988 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), 2989 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP), 2990 OptSize(OptSize), PSI(PSI), BFI(BFI) { 2991 IgnoreProfitability = false; 2992 } 2993 2994 public: 2995 /// Find the maximal addressing mode that a load/store of V can fold, 2996 /// give an access type of AccessTy. This returns a list of involved 2997 /// instructions in AddrModeInsts. 2998 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare 2999 /// optimizations. 3000 /// \p PromotedInsts maps the instructions to their type before promotion. 3001 /// \p The ongoing transaction where every action should be registered. 3002 static ExtAddrMode 3003 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst, 3004 SmallVectorImpl<Instruction *> &AddrModeInsts, 3005 const TargetLowering &TLI, const TargetRegisterInfo &TRI, 3006 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts, 3007 TypePromotionTransaction &TPT, 3008 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP, 3009 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) { 3010 ExtAddrMode Result; 3011 3012 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS, 3013 MemoryInst, Result, InsertedInsts, 3014 PromotedInsts, TPT, LargeOffsetGEP, 3015 OptSize, PSI, BFI) 3016 .matchAddr(V, 0); 3017 (void)Success; assert(Success && "Couldn't select *anything*?"); 3018 return Result; 3019 } 3020 3021 private: 3022 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); 3023 bool matchAddr(Value *Addr, unsigned Depth); 3024 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth, 3025 bool *MovedAway = nullptr); 3026 bool isProfitableToFoldIntoAddressingMode(Instruction *I, 3027 ExtAddrMode &AMBefore, 3028 ExtAddrMode &AMAfter); 3029 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); 3030 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, 3031 Value *PromotedOperand) const; 3032 }; 3033 3034 class PhiNodeSet; 3035 3036 /// An iterator for PhiNodeSet. 3037 class PhiNodeSetIterator { 3038 PhiNodeSet * const Set; 3039 size_t CurrentIndex = 0; 3040 3041 public: 3042 /// The constructor. Start should point to either a valid element, or be equal 3043 /// to the size of the underlying SmallVector of the PhiNodeSet. 3044 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start); 3045 PHINode * operator*() const; 3046 PhiNodeSetIterator& operator++(); 3047 bool operator==(const PhiNodeSetIterator &RHS) const; 3048 bool operator!=(const PhiNodeSetIterator &RHS) const; 3049 }; 3050 3051 /// Keeps a set of PHINodes. 3052 /// 3053 /// This is a minimal set implementation for a specific use case: 3054 /// It is very fast when there are very few elements, but also provides good 3055 /// performance when there are many. It is similar to SmallPtrSet, but also 3056 /// provides iteration by insertion order, which is deterministic and stable 3057 /// across runs. It is also similar to SmallSetVector, but provides removing 3058 /// elements in O(1) time. This is achieved by not actually removing the element 3059 /// from the underlying vector, so comes at the cost of using more memory, but 3060 /// that is fine, since PhiNodeSets are used as short lived objects. 3061 class PhiNodeSet { 3062 friend class PhiNodeSetIterator; 3063 3064 using MapType = SmallDenseMap<PHINode *, size_t, 32>; 3065 using iterator = PhiNodeSetIterator; 3066 3067 /// Keeps the elements in the order of their insertion in the underlying 3068 /// vector. To achieve constant time removal, it never deletes any element. 3069 SmallVector<PHINode *, 32> NodeList; 3070 3071 /// Keeps the elements in the underlying set implementation. This (and not the 3072 /// NodeList defined above) is the source of truth on whether an element 3073 /// is actually in the collection. 3074 MapType NodeMap; 3075 3076 /// Points to the first valid (not deleted) element when the set is not empty 3077 /// and the value is not zero. Equals to the size of the underlying vector 3078 /// when the set is empty. When the value is 0, as in the beginning, the 3079 /// first element may or may not be valid. 3080 size_t FirstValidElement = 0; 3081 3082 public: 3083 /// Inserts a new element to the collection. 3084 /// \returns true if the element is actually added, i.e. was not in the 3085 /// collection before the operation. 3086 bool insert(PHINode *Ptr) { 3087 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) { 3088 NodeList.push_back(Ptr); 3089 return true; 3090 } 3091 return false; 3092 } 3093 3094 /// Removes the element from the collection. 3095 /// \returns whether the element is actually removed, i.e. was in the 3096 /// collection before the operation. 3097 bool erase(PHINode *Ptr) { 3098 auto it = NodeMap.find(Ptr); 3099 if (it != NodeMap.end()) { 3100 NodeMap.erase(Ptr); 3101 SkipRemovedElements(FirstValidElement); 3102 return true; 3103 } 3104 return false; 3105 } 3106 3107 /// Removes all elements and clears the collection. 3108 void clear() { 3109 NodeMap.clear(); 3110 NodeList.clear(); 3111 FirstValidElement = 0; 3112 } 3113 3114 /// \returns an iterator that will iterate the elements in the order of 3115 /// insertion. 3116 iterator begin() { 3117 if (FirstValidElement == 0) 3118 SkipRemovedElements(FirstValidElement); 3119 return PhiNodeSetIterator(this, FirstValidElement); 3120 } 3121 3122 /// \returns an iterator that points to the end of the collection. 3123 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); } 3124 3125 /// Returns the number of elements in the collection. 3126 size_t size() const { 3127 return NodeMap.size(); 3128 } 3129 3130 /// \returns 1 if the given element is in the collection, and 0 if otherwise. 3131 size_t count(PHINode *Ptr) const { 3132 return NodeMap.count(Ptr); 3133 } 3134 3135 private: 3136 /// Updates the CurrentIndex so that it will point to a valid element. 3137 /// 3138 /// If the element of NodeList at CurrentIndex is valid, it does not 3139 /// change it. If there are no more valid elements, it updates CurrentIndex 3140 /// to point to the end of the NodeList. 3141 void SkipRemovedElements(size_t &CurrentIndex) { 3142 while (CurrentIndex < NodeList.size()) { 3143 auto it = NodeMap.find(NodeList[CurrentIndex]); 3144 // If the element has been deleted and added again later, NodeMap will 3145 // point to a different index, so CurrentIndex will still be invalid. 3146 if (it != NodeMap.end() && it->second == CurrentIndex) 3147 break; 3148 ++CurrentIndex; 3149 } 3150 } 3151 }; 3152 3153 PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start) 3154 : Set(Set), CurrentIndex(Start) {} 3155 3156 PHINode * PhiNodeSetIterator::operator*() const { 3157 assert(CurrentIndex < Set->NodeList.size() && 3158 "PhiNodeSet access out of range"); 3159 return Set->NodeList[CurrentIndex]; 3160 } 3161 3162 PhiNodeSetIterator& PhiNodeSetIterator::operator++() { 3163 assert(CurrentIndex < Set->NodeList.size() && 3164 "PhiNodeSet access out of range"); 3165 ++CurrentIndex; 3166 Set->SkipRemovedElements(CurrentIndex); 3167 return *this; 3168 } 3169 3170 bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const { 3171 return CurrentIndex == RHS.CurrentIndex; 3172 } 3173 3174 bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const { 3175 return !((*this) == RHS); 3176 } 3177 3178 /// Keep track of simplification of Phi nodes. 3179 /// Accept the set of all phi nodes and erase phi node from this set 3180 /// if it is simplified. 3181 class SimplificationTracker { 3182 DenseMap<Value *, Value *> Storage; 3183 const SimplifyQuery &SQ; 3184 // Tracks newly created Phi nodes. The elements are iterated by insertion 3185 // order. 3186 PhiNodeSet AllPhiNodes; 3187 // Tracks newly created Select nodes. 3188 SmallPtrSet<SelectInst *, 32> AllSelectNodes; 3189 3190 public: 3191 SimplificationTracker(const SimplifyQuery &sq) 3192 : SQ(sq) {} 3193 3194 Value *Get(Value *V) { 3195 do { 3196 auto SV = Storage.find(V); 3197 if (SV == Storage.end()) 3198 return V; 3199 V = SV->second; 3200 } while (true); 3201 } 3202 3203 Value *Simplify(Value *Val) { 3204 SmallVector<Value *, 32> WorkList; 3205 SmallPtrSet<Value *, 32> Visited; 3206 WorkList.push_back(Val); 3207 while (!WorkList.empty()) { 3208 auto P = WorkList.pop_back_val(); 3209 if (!Visited.insert(P).second) 3210 continue; 3211 if (auto *PI = dyn_cast<Instruction>(P)) 3212 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) { 3213 for (auto *U : PI->users()) 3214 WorkList.push_back(cast<Value>(U)); 3215 Put(PI, V); 3216 PI->replaceAllUsesWith(V); 3217 if (auto *PHI = dyn_cast<PHINode>(PI)) 3218 AllPhiNodes.erase(PHI); 3219 if (auto *Select = dyn_cast<SelectInst>(PI)) 3220 AllSelectNodes.erase(Select); 3221 PI->eraseFromParent(); 3222 } 3223 } 3224 return Get(Val); 3225 } 3226 3227 void Put(Value *From, Value *To) { 3228 Storage.insert({ From, To }); 3229 } 3230 3231 void ReplacePhi(PHINode *From, PHINode *To) { 3232 Value* OldReplacement = Get(From); 3233 while (OldReplacement != From) { 3234 From = To; 3235 To = dyn_cast<PHINode>(OldReplacement); 3236 OldReplacement = Get(From); 3237 } 3238 assert(To && Get(To) == To && "Replacement PHI node is already replaced."); 3239 Put(From, To); 3240 From->replaceAllUsesWith(To); 3241 AllPhiNodes.erase(From); 3242 From->eraseFromParent(); 3243 } 3244 3245 PhiNodeSet& newPhiNodes() { return AllPhiNodes; } 3246 3247 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); } 3248 3249 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); } 3250 3251 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); } 3252 3253 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); } 3254 3255 void destroyNewNodes(Type *CommonType) { 3256 // For safe erasing, replace the uses with dummy value first. 3257 auto Dummy = UndefValue::get(CommonType); 3258 for (auto I : AllPhiNodes) { 3259 I->replaceAllUsesWith(Dummy); 3260 I->eraseFromParent(); 3261 } 3262 AllPhiNodes.clear(); 3263 for (auto I : AllSelectNodes) { 3264 I->replaceAllUsesWith(Dummy); 3265 I->eraseFromParent(); 3266 } 3267 AllSelectNodes.clear(); 3268 } 3269 }; 3270 3271 /// A helper class for combining addressing modes. 3272 class AddressingModeCombiner { 3273 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping; 3274 typedef std::pair<PHINode *, PHINode *> PHIPair; 3275 3276 private: 3277 /// The addressing modes we've collected. 3278 SmallVector<ExtAddrMode, 16> AddrModes; 3279 3280 /// The field in which the AddrModes differ, when we have more than one. 3281 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField; 3282 3283 /// Are the AddrModes that we have all just equal to their original values? 3284 bool AllAddrModesTrivial = true; 3285 3286 /// Common Type for all different fields in addressing modes. 3287 Type *CommonType; 3288 3289 /// SimplifyQuery for simplifyInstruction utility. 3290 const SimplifyQuery &SQ; 3291 3292 /// Original Address. 3293 Value *Original; 3294 3295 public: 3296 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue) 3297 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {} 3298 3299 /// Get the combined AddrMode 3300 const ExtAddrMode &getAddrMode() const { 3301 return AddrModes[0]; 3302 } 3303 3304 /// Add a new AddrMode if it's compatible with the AddrModes we already 3305 /// have. 3306 /// \return True iff we succeeded in doing so. 3307 bool addNewAddrMode(ExtAddrMode &NewAddrMode) { 3308 // Take note of if we have any non-trivial AddrModes, as we need to detect 3309 // when all AddrModes are trivial as then we would introduce a phi or select 3310 // which just duplicates what's already there. 3311 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial(); 3312 3313 // If this is the first addrmode then everything is fine. 3314 if (AddrModes.empty()) { 3315 AddrModes.emplace_back(NewAddrMode); 3316 return true; 3317 } 3318 3319 // Figure out how different this is from the other address modes, which we 3320 // can do just by comparing against the first one given that we only care 3321 // about the cumulative difference. 3322 ExtAddrMode::FieldName ThisDifferentField = 3323 AddrModes[0].compare(NewAddrMode); 3324 if (DifferentField == ExtAddrMode::NoField) 3325 DifferentField = ThisDifferentField; 3326 else if (DifferentField != ThisDifferentField) 3327 DifferentField = ExtAddrMode::MultipleFields; 3328 3329 // If NewAddrMode differs in more than one dimension we cannot handle it. 3330 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields; 3331 3332 // If Scale Field is different then we reject. 3333 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField; 3334 3335 // We also must reject the case when base offset is different and 3336 // scale reg is not null, we cannot handle this case due to merge of 3337 // different offsets will be used as ScaleReg. 3338 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField || 3339 !NewAddrMode.ScaledReg); 3340 3341 // We also must reject the case when GV is different and BaseReg installed 3342 // due to we want to use base reg as a merge of GV values. 3343 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField || 3344 !NewAddrMode.HasBaseReg); 3345 3346 // Even if NewAddMode is the same we still need to collect it due to 3347 // original value is different. And later we will need all original values 3348 // as anchors during finding the common Phi node. 3349 if (CanHandle) 3350 AddrModes.emplace_back(NewAddrMode); 3351 else 3352 AddrModes.clear(); 3353 3354 return CanHandle; 3355 } 3356 3357 /// Combine the addressing modes we've collected into a single 3358 /// addressing mode. 3359 /// \return True iff we successfully combined them or we only had one so 3360 /// didn't need to combine them anyway. 3361 bool combineAddrModes() { 3362 // If we have no AddrModes then they can't be combined. 3363 if (AddrModes.size() == 0) 3364 return false; 3365 3366 // A single AddrMode can trivially be combined. 3367 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField) 3368 return true; 3369 3370 // If the AddrModes we collected are all just equal to the value they are 3371 // derived from then combining them wouldn't do anything useful. 3372 if (AllAddrModesTrivial) 3373 return false; 3374 3375 if (!addrModeCombiningAllowed()) 3376 return false; 3377 3378 // Build a map between <original value, basic block where we saw it> to 3379 // value of base register. 3380 // Bail out if there is no common type. 3381 FoldAddrToValueMapping Map; 3382 if (!initializeMap(Map)) 3383 return false; 3384 3385 Value *CommonValue = findCommon(Map); 3386 if (CommonValue) 3387 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes); 3388 return CommonValue != nullptr; 3389 } 3390 3391 private: 3392 /// Initialize Map with anchor values. For address seen 3393 /// we set the value of different field saw in this address. 3394 /// At the same time we find a common type for different field we will 3395 /// use to create new Phi/Select nodes. Keep it in CommonType field. 3396 /// Return false if there is no common type found. 3397 bool initializeMap(FoldAddrToValueMapping &Map) { 3398 // Keep track of keys where the value is null. We will need to replace it 3399 // with constant null when we know the common type. 3400 SmallVector<Value *, 2> NullValue; 3401 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType()); 3402 for (auto &AM : AddrModes) { 3403 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy); 3404 if (DV) { 3405 auto *Type = DV->getType(); 3406 if (CommonType && CommonType != Type) 3407 return false; 3408 CommonType = Type; 3409 Map[AM.OriginalValue] = DV; 3410 } else { 3411 NullValue.push_back(AM.OriginalValue); 3412 } 3413 } 3414 assert(CommonType && "At least one non-null value must be!"); 3415 for (auto *V : NullValue) 3416 Map[V] = Constant::getNullValue(CommonType); 3417 return true; 3418 } 3419 3420 /// We have mapping between value A and other value B where B was a field in 3421 /// addressing mode represented by A. Also we have an original value C 3422 /// representing an address we start with. Traversing from C through phi and 3423 /// selects we ended up with A's in a map. This utility function tries to find 3424 /// a value V which is a field in addressing mode C and traversing through phi 3425 /// nodes and selects we will end up in corresponded values B in a map. 3426 /// The utility will create a new Phi/Selects if needed. 3427 // The simple example looks as follows: 3428 // BB1: 3429 // p1 = b1 + 40 3430 // br cond BB2, BB3 3431 // BB2: 3432 // p2 = b2 + 40 3433 // br BB3 3434 // BB3: 3435 // p = phi [p1, BB1], [p2, BB2] 3436 // v = load p 3437 // Map is 3438 // p1 -> b1 3439 // p2 -> b2 3440 // Request is 3441 // p -> ? 3442 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3. 3443 Value *findCommon(FoldAddrToValueMapping &Map) { 3444 // Tracks the simplification of newly created phi nodes. The reason we use 3445 // this mapping is because we will add new created Phi nodes in AddrToBase. 3446 // Simplification of Phi nodes is recursive, so some Phi node may 3447 // be simplified after we added it to AddrToBase. In reality this 3448 // simplification is possible only if original phi/selects were not 3449 // simplified yet. 3450 // Using this mapping we can find the current value in AddrToBase. 3451 SimplificationTracker ST(SQ); 3452 3453 // First step, DFS to create PHI nodes for all intermediate blocks. 3454 // Also fill traverse order for the second step. 3455 SmallVector<Value *, 32> TraverseOrder; 3456 InsertPlaceholders(Map, TraverseOrder, ST); 3457 3458 // Second Step, fill new nodes by merged values and simplify if possible. 3459 FillPlaceholders(Map, TraverseOrder, ST); 3460 3461 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) { 3462 ST.destroyNewNodes(CommonType); 3463 return nullptr; 3464 } 3465 3466 // Now we'd like to match New Phi nodes to existed ones. 3467 unsigned PhiNotMatchedCount = 0; 3468 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) { 3469 ST.destroyNewNodes(CommonType); 3470 return nullptr; 3471 } 3472 3473 auto *Result = ST.Get(Map.find(Original)->second); 3474 if (Result) { 3475 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount; 3476 NumMemoryInstsSelectCreated += ST.countNewSelectNodes(); 3477 } 3478 return Result; 3479 } 3480 3481 /// Try to match PHI node to Candidate. 3482 /// Matcher tracks the matched Phi nodes. 3483 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate, 3484 SmallSetVector<PHIPair, 8> &Matcher, 3485 PhiNodeSet &PhiNodesToMatch) { 3486 SmallVector<PHIPair, 8> WorkList; 3487 Matcher.insert({ PHI, Candidate }); 3488 SmallSet<PHINode *, 8> MatchedPHIs; 3489 MatchedPHIs.insert(PHI); 3490 WorkList.push_back({ PHI, Candidate }); 3491 SmallSet<PHIPair, 8> Visited; 3492 while (!WorkList.empty()) { 3493 auto Item = WorkList.pop_back_val(); 3494 if (!Visited.insert(Item).second) 3495 continue; 3496 // We iterate over all incoming values to Phi to compare them. 3497 // If values are different and both of them Phi and the first one is a 3498 // Phi we added (subject to match) and both of them is in the same basic 3499 // block then we can match our pair if values match. So we state that 3500 // these values match and add it to work list to verify that. 3501 for (auto B : Item.first->blocks()) { 3502 Value *FirstValue = Item.first->getIncomingValueForBlock(B); 3503 Value *SecondValue = Item.second->getIncomingValueForBlock(B); 3504 if (FirstValue == SecondValue) 3505 continue; 3506 3507 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue); 3508 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue); 3509 3510 // One of them is not Phi or 3511 // The first one is not Phi node from the set we'd like to match or 3512 // Phi nodes from different basic blocks then 3513 // we will not be able to match. 3514 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) || 3515 FirstPhi->getParent() != SecondPhi->getParent()) 3516 return false; 3517 3518 // If we already matched them then continue. 3519 if (Matcher.count({ FirstPhi, SecondPhi })) 3520 continue; 3521 // So the values are different and does not match. So we need them to 3522 // match. (But we register no more than one match per PHI node, so that 3523 // we won't later try to replace them twice.) 3524 if (MatchedPHIs.insert(FirstPhi).second) 3525 Matcher.insert({ FirstPhi, SecondPhi }); 3526 // But me must check it. 3527 WorkList.push_back({ FirstPhi, SecondPhi }); 3528 } 3529 } 3530 return true; 3531 } 3532 3533 /// For the given set of PHI nodes (in the SimplificationTracker) try 3534 /// to find their equivalents. 3535 /// Returns false if this matching fails and creation of new Phi is disabled. 3536 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes, 3537 unsigned &PhiNotMatchedCount) { 3538 // Matched and PhiNodesToMatch iterate their elements in a deterministic 3539 // order, so the replacements (ReplacePhi) are also done in a deterministic 3540 // order. 3541 SmallSetVector<PHIPair, 8> Matched; 3542 SmallPtrSet<PHINode *, 8> WillNotMatch; 3543 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes(); 3544 while (PhiNodesToMatch.size()) { 3545 PHINode *PHI = *PhiNodesToMatch.begin(); 3546 3547 // Add us, if no Phi nodes in the basic block we do not match. 3548 WillNotMatch.clear(); 3549 WillNotMatch.insert(PHI); 3550 3551 // Traverse all Phis until we found equivalent or fail to do that. 3552 bool IsMatched = false; 3553 for (auto &P : PHI->getParent()->phis()) { 3554 if (&P == PHI) 3555 continue; 3556 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch))) 3557 break; 3558 // If it does not match, collect all Phi nodes from matcher. 3559 // if we end up with no match, them all these Phi nodes will not match 3560 // later. 3561 for (auto M : Matched) 3562 WillNotMatch.insert(M.first); 3563 Matched.clear(); 3564 } 3565 if (IsMatched) { 3566 // Replace all matched values and erase them. 3567 for (auto MV : Matched) 3568 ST.ReplacePhi(MV.first, MV.second); 3569 Matched.clear(); 3570 continue; 3571 } 3572 // If we are not allowed to create new nodes then bail out. 3573 if (!AllowNewPhiNodes) 3574 return false; 3575 // Just remove all seen values in matcher. They will not match anything. 3576 PhiNotMatchedCount += WillNotMatch.size(); 3577 for (auto *P : WillNotMatch) 3578 PhiNodesToMatch.erase(P); 3579 } 3580 return true; 3581 } 3582 /// Fill the placeholders with values from predecessors and simplify them. 3583 void FillPlaceholders(FoldAddrToValueMapping &Map, 3584 SmallVectorImpl<Value *> &TraverseOrder, 3585 SimplificationTracker &ST) { 3586 while (!TraverseOrder.empty()) { 3587 Value *Current = TraverseOrder.pop_back_val(); 3588 assert(Map.find(Current) != Map.end() && "No node to fill!!!"); 3589 Value *V = Map[Current]; 3590 3591 if (SelectInst *Select = dyn_cast<SelectInst>(V)) { 3592 // CurrentValue also must be Select. 3593 auto *CurrentSelect = cast<SelectInst>(Current); 3594 auto *TrueValue = CurrentSelect->getTrueValue(); 3595 assert(Map.find(TrueValue) != Map.end() && "No True Value!"); 3596 Select->setTrueValue(ST.Get(Map[TrueValue])); 3597 auto *FalseValue = CurrentSelect->getFalseValue(); 3598 assert(Map.find(FalseValue) != Map.end() && "No False Value!"); 3599 Select->setFalseValue(ST.Get(Map[FalseValue])); 3600 } else { 3601 // Must be a Phi node then. 3602 auto *PHI = cast<PHINode>(V); 3603 // Fill the Phi node with values from predecessors. 3604 for (auto B : predecessors(PHI->getParent())) { 3605 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B); 3606 assert(Map.find(PV) != Map.end() && "No predecessor Value!"); 3607 PHI->addIncoming(ST.Get(Map[PV]), B); 3608 } 3609 } 3610 Map[Current] = ST.Simplify(V); 3611 } 3612 } 3613 3614 /// Starting from original value recursively iterates over def-use chain up to 3615 /// known ending values represented in a map. For each traversed phi/select 3616 /// inserts a placeholder Phi or Select. 3617 /// Reports all new created Phi/Select nodes by adding them to set. 3618 /// Also reports and order in what values have been traversed. 3619 void InsertPlaceholders(FoldAddrToValueMapping &Map, 3620 SmallVectorImpl<Value *> &TraverseOrder, 3621 SimplificationTracker &ST) { 3622 SmallVector<Value *, 32> Worklist; 3623 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) && 3624 "Address must be a Phi or Select node"); 3625 auto *Dummy = UndefValue::get(CommonType); 3626 Worklist.push_back(Original); 3627 while (!Worklist.empty()) { 3628 Value *Current = Worklist.pop_back_val(); 3629 // if it is already visited or it is an ending value then skip it. 3630 if (Map.find(Current) != Map.end()) 3631 continue; 3632 TraverseOrder.push_back(Current); 3633 3634 // CurrentValue must be a Phi node or select. All others must be covered 3635 // by anchors. 3636 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) { 3637 // Is it OK to get metadata from OrigSelect?! 3638 // Create a Select placeholder with dummy value. 3639 SelectInst *Select = SelectInst::Create( 3640 CurrentSelect->getCondition(), Dummy, Dummy, 3641 CurrentSelect->getName(), CurrentSelect, CurrentSelect); 3642 Map[Current] = Select; 3643 ST.insertNewSelect(Select); 3644 // We are interested in True and False values. 3645 Worklist.push_back(CurrentSelect->getTrueValue()); 3646 Worklist.push_back(CurrentSelect->getFalseValue()); 3647 } else { 3648 // It must be a Phi node then. 3649 PHINode *CurrentPhi = cast<PHINode>(Current); 3650 unsigned PredCount = CurrentPhi->getNumIncomingValues(); 3651 PHINode *PHI = 3652 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi); 3653 Map[Current] = PHI; 3654 ST.insertNewPhi(PHI); 3655 for (Value *P : CurrentPhi->incoming_values()) 3656 Worklist.push_back(P); 3657 } 3658 } 3659 } 3660 3661 bool addrModeCombiningAllowed() { 3662 if (DisableComplexAddrModes) 3663 return false; 3664 switch (DifferentField) { 3665 default: 3666 return false; 3667 case ExtAddrMode::BaseRegField: 3668 return AddrSinkCombineBaseReg; 3669 case ExtAddrMode::BaseGVField: 3670 return AddrSinkCombineBaseGV; 3671 case ExtAddrMode::BaseOffsField: 3672 return AddrSinkCombineBaseOffs; 3673 case ExtAddrMode::ScaledRegField: 3674 return AddrSinkCombineScaledReg; 3675 } 3676 } 3677 }; 3678 } // end anonymous namespace 3679 3680 /// Try adding ScaleReg*Scale to the current addressing mode. 3681 /// Return true and update AddrMode if this addr mode is legal for the target, 3682 /// false if not. 3683 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, 3684 unsigned Depth) { 3685 // If Scale is 1, then this is the same as adding ScaleReg to the addressing 3686 // mode. Just process that directly. 3687 if (Scale == 1) 3688 return matchAddr(ScaleReg, Depth); 3689 3690 // If the scale is 0, it takes nothing to add this. 3691 if (Scale == 0) 3692 return true; 3693 3694 // If we already have a scale of this value, we can add to it, otherwise, we 3695 // need an available scale field. 3696 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) 3697 return false; 3698 3699 ExtAddrMode TestAddrMode = AddrMode; 3700 3701 // Add scale to turn X*4+X*3 -> X*7. This could also do things like 3702 // [A+B + A*7] -> [B+A*8]. 3703 TestAddrMode.Scale += Scale; 3704 TestAddrMode.ScaledReg = ScaleReg; 3705 3706 // If the new address isn't legal, bail out. 3707 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) 3708 return false; 3709 3710 // It was legal, so commit it. 3711 AddrMode = TestAddrMode; 3712 3713 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now 3714 // to see if ScaleReg is actually X+C. If so, we can turn this into adding 3715 // X*Scale + C*Scale to addr mode. 3716 ConstantInt *CI = nullptr; Value *AddLHS = nullptr; 3717 if (isa<Instruction>(ScaleReg) && // not a constant expr. 3718 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) && 3719 CI->getValue().isSignedIntN(64)) { 3720 TestAddrMode.InBounds = false; 3721 TestAddrMode.ScaledReg = AddLHS; 3722 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale; 3723 3724 // If this addressing mode is legal, commit it and remember that we folded 3725 // this instruction. 3726 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { 3727 AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); 3728 AddrMode = TestAddrMode; 3729 return true; 3730 } 3731 } 3732 3733 // Otherwise, not (x+c)*scale, just return what we have. 3734 return true; 3735 } 3736 3737 /// This is a little filter, which returns true if an addressing computation 3738 /// involving I might be folded into a load/store accessing it. 3739 /// This doesn't need to be perfect, but needs to accept at least 3740 /// the set of instructions that MatchOperationAddr can. 3741 static bool MightBeFoldableInst(Instruction *I) { 3742 switch (I->getOpcode()) { 3743 case Instruction::BitCast: 3744 case Instruction::AddrSpaceCast: 3745 // Don't touch identity bitcasts. 3746 if (I->getType() == I->getOperand(0)->getType()) 3747 return false; 3748 return I->getType()->isIntOrPtrTy(); 3749 case Instruction::PtrToInt: 3750 // PtrToInt is always a noop, as we know that the int type is pointer sized. 3751 return true; 3752 case Instruction::IntToPtr: 3753 // We know the input is intptr_t, so this is foldable. 3754 return true; 3755 case Instruction::Add: 3756 return true; 3757 case Instruction::Mul: 3758 case Instruction::Shl: 3759 // Can only handle X*C and X << C. 3760 return isa<ConstantInt>(I->getOperand(1)); 3761 case Instruction::GetElementPtr: 3762 return true; 3763 default: 3764 return false; 3765 } 3766 } 3767 3768 /// Check whether or not \p Val is a legal instruction for \p TLI. 3769 /// \note \p Val is assumed to be the product of some type promotion. 3770 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed 3771 /// to be legal, as the non-promoted value would have had the same state. 3772 static bool isPromotedInstructionLegal(const TargetLowering &TLI, 3773 const DataLayout &DL, Value *Val) { 3774 Instruction *PromotedInst = dyn_cast<Instruction>(Val); 3775 if (!PromotedInst) 3776 return false; 3777 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); 3778 // If the ISDOpcode is undefined, it was undefined before the promotion. 3779 if (!ISDOpcode) 3780 return true; 3781 // Otherwise, check if the promoted instruction is legal or not. 3782 return TLI.isOperationLegalOrCustom( 3783 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); 3784 } 3785 3786 namespace { 3787 3788 /// Hepler class to perform type promotion. 3789 class TypePromotionHelper { 3790 /// Utility function to add a promoted instruction \p ExtOpnd to 3791 /// \p PromotedInsts and record the type of extension we have seen. 3792 static void addPromotedInst(InstrToOrigTy &PromotedInsts, 3793 Instruction *ExtOpnd, 3794 bool IsSExt) { 3795 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; 3796 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd); 3797 if (It != PromotedInsts.end()) { 3798 // If the new extension is same as original, the information in 3799 // PromotedInsts[ExtOpnd] is still correct. 3800 if (It->second.getInt() == ExtTy) 3801 return; 3802 3803 // Now the new extension is different from old extension, we make 3804 // the type information invalid by setting extension type to 3805 // BothExtension. 3806 ExtTy = BothExtension; 3807 } 3808 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy); 3809 } 3810 3811 /// Utility function to query the original type of instruction \p Opnd 3812 /// with a matched extension type. If the extension doesn't match, we 3813 /// cannot use the information we had on the original type. 3814 /// BothExtension doesn't match any extension type. 3815 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts, 3816 Instruction *Opnd, 3817 bool IsSExt) { 3818 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; 3819 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); 3820 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy) 3821 return It->second.getPointer(); 3822 return nullptr; 3823 } 3824 3825 /// Utility function to check whether or not a sign or zero extension 3826 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by 3827 /// either using the operands of \p Inst or promoting \p Inst. 3828 /// The type of the extension is defined by \p IsSExt. 3829 /// In other words, check if: 3830 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. 3831 /// #1 Promotion applies: 3832 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). 3833 /// #2 Operand reuses: 3834 /// ext opnd1 to ConsideredExtType. 3835 /// \p PromotedInsts maps the instructions to their type before promotion. 3836 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, 3837 const InstrToOrigTy &PromotedInsts, bool IsSExt); 3838 3839 /// Utility function to determine if \p OpIdx should be promoted when 3840 /// promoting \p Inst. 3841 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { 3842 return !(isa<SelectInst>(Inst) && OpIdx == 0); 3843 } 3844 3845 /// Utility function to promote the operand of \p Ext when this 3846 /// operand is a promotable trunc or sext or zext. 3847 /// \p PromotedInsts maps the instructions to their type before promotion. 3848 /// \p CreatedInstsCost[out] contains the cost of all instructions 3849 /// created to promote the operand of Ext. 3850 /// Newly added extensions are inserted in \p Exts. 3851 /// Newly added truncates are inserted in \p Truncs. 3852 /// Should never be called directly. 3853 /// \return The promoted value which is used instead of Ext. 3854 static Value *promoteOperandForTruncAndAnyExt( 3855 Instruction *Ext, TypePromotionTransaction &TPT, 3856 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 3857 SmallVectorImpl<Instruction *> *Exts, 3858 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); 3859 3860 /// Utility function to promote the operand of \p Ext when this 3861 /// operand is promotable and is not a supported trunc or sext. 3862 /// \p PromotedInsts maps the instructions to their type before promotion. 3863 /// \p CreatedInstsCost[out] contains the cost of all the instructions 3864 /// created to promote the operand of Ext. 3865 /// Newly added extensions are inserted in \p Exts. 3866 /// Newly added truncates are inserted in \p Truncs. 3867 /// Should never be called directly. 3868 /// \return The promoted value which is used instead of Ext. 3869 static Value *promoteOperandForOther(Instruction *Ext, 3870 TypePromotionTransaction &TPT, 3871 InstrToOrigTy &PromotedInsts, 3872 unsigned &CreatedInstsCost, 3873 SmallVectorImpl<Instruction *> *Exts, 3874 SmallVectorImpl<Instruction *> *Truncs, 3875 const TargetLowering &TLI, bool IsSExt); 3876 3877 /// \see promoteOperandForOther. 3878 static Value *signExtendOperandForOther( 3879 Instruction *Ext, TypePromotionTransaction &TPT, 3880 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 3881 SmallVectorImpl<Instruction *> *Exts, 3882 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { 3883 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, 3884 Exts, Truncs, TLI, true); 3885 } 3886 3887 /// \see promoteOperandForOther. 3888 static Value *zeroExtendOperandForOther( 3889 Instruction *Ext, TypePromotionTransaction &TPT, 3890 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 3891 SmallVectorImpl<Instruction *> *Exts, 3892 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { 3893 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, 3894 Exts, Truncs, TLI, false); 3895 } 3896 3897 public: 3898 /// Type for the utility function that promotes the operand of Ext. 3899 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT, 3900 InstrToOrigTy &PromotedInsts, 3901 unsigned &CreatedInstsCost, 3902 SmallVectorImpl<Instruction *> *Exts, 3903 SmallVectorImpl<Instruction *> *Truncs, 3904 const TargetLowering &TLI); 3905 3906 /// Given a sign/zero extend instruction \p Ext, return the appropriate 3907 /// action to promote the operand of \p Ext instead of using Ext. 3908 /// \return NULL if no promotable action is possible with the current 3909 /// sign extension. 3910 /// \p InsertedInsts keeps track of all the instructions inserted by the 3911 /// other CodeGenPrepare optimizations. This information is important 3912 /// because we do not want to promote these instructions as CodeGenPrepare 3913 /// will reinsert them later. Thus creating an infinite loop: create/remove. 3914 /// \p PromotedInsts maps the instructions to their type before promotion. 3915 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, 3916 const TargetLowering &TLI, 3917 const InstrToOrigTy &PromotedInsts); 3918 }; 3919 3920 } // end anonymous namespace 3921 3922 bool TypePromotionHelper::canGetThrough(const Instruction *Inst, 3923 Type *ConsideredExtType, 3924 const InstrToOrigTy &PromotedInsts, 3925 bool IsSExt) { 3926 // The promotion helper does not know how to deal with vector types yet. 3927 // To be able to fix that, we would need to fix the places where we 3928 // statically extend, e.g., constants and such. 3929 if (Inst->getType()->isVectorTy()) 3930 return false; 3931 3932 // We can always get through zext. 3933 if (isa<ZExtInst>(Inst)) 3934 return true; 3935 3936 // sext(sext) is ok too. 3937 if (IsSExt && isa<SExtInst>(Inst)) 3938 return true; 3939 3940 // We can get through binary operator, if it is legal. In other words, the 3941 // binary operator must have a nuw or nsw flag. 3942 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); 3943 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && 3944 ((!IsSExt && BinOp->hasNoUnsignedWrap()) || 3945 (IsSExt && BinOp->hasNoSignedWrap()))) 3946 return true; 3947 3948 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst)) 3949 if ((Inst->getOpcode() == Instruction::And || 3950 Inst->getOpcode() == Instruction::Or)) 3951 return true; 3952 3953 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst)) 3954 if (Inst->getOpcode() == Instruction::Xor) { 3955 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)); 3956 // Make sure it is not a NOT. 3957 if (Cst && !Cst->getValue().isAllOnesValue()) 3958 return true; 3959 } 3960 3961 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst)) 3962 // It may change a poisoned value into a regular value, like 3963 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12 3964 // poisoned value regular value 3965 // It should be OK since undef covers valid value. 3966 if (Inst->getOpcode() == Instruction::LShr && !IsSExt) 3967 return true; 3968 3969 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst) 3970 // It may change a poisoned value into a regular value, like 3971 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12 3972 // poisoned value regular value 3973 // It should be OK since undef covers valid value. 3974 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) { 3975 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin()); 3976 if (ExtInst->hasOneUse()) { 3977 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin()); 3978 if (AndInst && AndInst->getOpcode() == Instruction::And) { 3979 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1)); 3980 if (Cst && 3981 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth())) 3982 return true; 3983 } 3984 } 3985 } 3986 3987 // Check if we can do the following simplification. 3988 // ext(trunc(opnd)) --> ext(opnd) 3989 if (!isa<TruncInst>(Inst)) 3990 return false; 3991 3992 Value *OpndVal = Inst->getOperand(0); 3993 // Check if we can use this operand in the extension. 3994 // If the type is larger than the result type of the extension, we cannot. 3995 if (!OpndVal->getType()->isIntegerTy() || 3996 OpndVal->getType()->getIntegerBitWidth() > 3997 ConsideredExtType->getIntegerBitWidth()) 3998 return false; 3999 4000 // If the operand of the truncate is not an instruction, we will not have 4001 // any information on the dropped bits. 4002 // (Actually we could for constant but it is not worth the extra logic). 4003 Instruction *Opnd = dyn_cast<Instruction>(OpndVal); 4004 if (!Opnd) 4005 return false; 4006 4007 // Check if the source of the type is narrow enough. 4008 // I.e., check that trunc just drops extended bits of the same kind of 4009 // the extension. 4010 // #1 get the type of the operand and check the kind of the extended bits. 4011 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt); 4012 if (OpndType) 4013 ; 4014 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) 4015 OpndType = Opnd->getOperand(0)->getType(); 4016 else 4017 return false; 4018 4019 // #2 check that the truncate just drops extended bits. 4020 return Inst->getType()->getIntegerBitWidth() >= 4021 OpndType->getIntegerBitWidth(); 4022 } 4023 4024 TypePromotionHelper::Action TypePromotionHelper::getAction( 4025 Instruction *Ext, const SetOfInstrs &InsertedInsts, 4026 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { 4027 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 4028 "Unexpected instruction type"); 4029 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); 4030 Type *ExtTy = Ext->getType(); 4031 bool IsSExt = isa<SExtInst>(Ext); 4032 // If the operand of the extension is not an instruction, we cannot 4033 // get through. 4034 // If it, check we can get through. 4035 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) 4036 return nullptr; 4037 4038 // Do not promote if the operand has been added by codegenprepare. 4039 // Otherwise, it means we are undoing an optimization that is likely to be 4040 // redone, thus causing potential infinite loop. 4041 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) 4042 return nullptr; 4043 4044 // SExt or Trunc instructions. 4045 // Return the related handler. 4046 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || 4047 isa<ZExtInst>(ExtOpnd)) 4048 return promoteOperandForTruncAndAnyExt; 4049 4050 // Regular instruction. 4051 // Abort early if we will have to insert non-free instructions. 4052 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) 4053 return nullptr; 4054 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; 4055 } 4056 4057 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( 4058 Instruction *SExt, TypePromotionTransaction &TPT, 4059 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 4060 SmallVectorImpl<Instruction *> *Exts, 4061 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { 4062 // By construction, the operand of SExt is an instruction. Otherwise we cannot 4063 // get through it and this method should not be called. 4064 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); 4065 Value *ExtVal = SExt; 4066 bool HasMergedNonFreeExt = false; 4067 if (isa<ZExtInst>(SExtOpnd)) { 4068 // Replace s|zext(zext(opnd)) 4069 // => zext(opnd). 4070 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); 4071 Value *ZExt = 4072 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); 4073 TPT.replaceAllUsesWith(SExt, ZExt); 4074 TPT.eraseInstruction(SExt); 4075 ExtVal = ZExt; 4076 } else { 4077 // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) 4078 // => z|sext(opnd). 4079 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); 4080 } 4081 CreatedInstsCost = 0; 4082 4083 // Remove dead code. 4084 if (SExtOpnd->use_empty()) 4085 TPT.eraseInstruction(SExtOpnd); 4086 4087 // Check if the extension is still needed. 4088 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); 4089 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { 4090 if (ExtInst) { 4091 if (Exts) 4092 Exts->push_back(ExtInst); 4093 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; 4094 } 4095 return ExtVal; 4096 } 4097 4098 // At this point we have: ext ty opnd to ty. 4099 // Reassign the uses of ExtInst to the opnd and remove ExtInst. 4100 Value *NextVal = ExtInst->getOperand(0); 4101 TPT.eraseInstruction(ExtInst, NextVal); 4102 return NextVal; 4103 } 4104 4105 Value *TypePromotionHelper::promoteOperandForOther( 4106 Instruction *Ext, TypePromotionTransaction &TPT, 4107 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, 4108 SmallVectorImpl<Instruction *> *Exts, 4109 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, 4110 bool IsSExt) { 4111 // By construction, the operand of Ext is an instruction. Otherwise we cannot 4112 // get through it and this method should not be called. 4113 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); 4114 CreatedInstsCost = 0; 4115 if (!ExtOpnd->hasOneUse()) { 4116 // ExtOpnd will be promoted. 4117 // All its uses, but Ext, will need to use a truncated value of the 4118 // promoted version. 4119 // Create the truncate now. 4120 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); 4121 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { 4122 // Insert it just after the definition. 4123 ITrunc->moveAfter(ExtOpnd); 4124 if (Truncs) 4125 Truncs->push_back(ITrunc); 4126 } 4127 4128 TPT.replaceAllUsesWith(ExtOpnd, Trunc); 4129 // Restore the operand of Ext (which has been replaced by the previous call 4130 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. 4131 TPT.setOperand(Ext, 0, ExtOpnd); 4132 } 4133 4134 // Get through the Instruction: 4135 // 1. Update its type. 4136 // 2. Replace the uses of Ext by Inst. 4137 // 3. Extend each operand that needs to be extended. 4138 4139 // Remember the original type of the instruction before promotion. 4140 // This is useful to know that the high bits are sign extended bits. 4141 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt); 4142 // Step #1. 4143 TPT.mutateType(ExtOpnd, Ext->getType()); 4144 // Step #2. 4145 TPT.replaceAllUsesWith(Ext, ExtOpnd); 4146 // Step #3. 4147 Instruction *ExtForOpnd = Ext; 4148 4149 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n"); 4150 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; 4151 ++OpIdx) { 4152 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); 4153 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || 4154 !shouldExtOperand(ExtOpnd, OpIdx)) { 4155 LLVM_DEBUG(dbgs() << "No need to propagate\n"); 4156 continue; 4157 } 4158 // Check if we can statically extend the operand. 4159 Value *Opnd = ExtOpnd->getOperand(OpIdx); 4160 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { 4161 LLVM_DEBUG(dbgs() << "Statically extend\n"); 4162 unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); 4163 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) 4164 : Cst->getValue().zext(BitWidth); 4165 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); 4166 continue; 4167 } 4168 // UndefValue are typed, so we have to statically sign extend them. 4169 if (isa<UndefValue>(Opnd)) { 4170 LLVM_DEBUG(dbgs() << "Statically extend\n"); 4171 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); 4172 continue; 4173 } 4174 4175 // Otherwise we have to explicitly sign extend the operand. 4176 // Check if Ext was reused to extend an operand. 4177 if (!ExtForOpnd) { 4178 // If yes, create a new one. 4179 LLVM_DEBUG(dbgs() << "More operands to ext\n"); 4180 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) 4181 : TPT.createZExt(Ext, Opnd, Ext->getType()); 4182 if (!isa<Instruction>(ValForExtOpnd)) { 4183 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); 4184 continue; 4185 } 4186 ExtForOpnd = cast<Instruction>(ValForExtOpnd); 4187 } 4188 if (Exts) 4189 Exts->push_back(ExtForOpnd); 4190 TPT.setOperand(ExtForOpnd, 0, Opnd); 4191 4192 // Move the sign extension before the insertion point. 4193 TPT.moveBefore(ExtForOpnd, ExtOpnd); 4194 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); 4195 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); 4196 // If more sext are required, new instructions will have to be created. 4197 ExtForOpnd = nullptr; 4198 } 4199 if (ExtForOpnd == Ext) { 4200 LLVM_DEBUG(dbgs() << "Extension is useless now\n"); 4201 TPT.eraseInstruction(Ext); 4202 } 4203 return ExtOpnd; 4204 } 4205 4206 /// Check whether or not promoting an instruction to a wider type is profitable. 4207 /// \p NewCost gives the cost of extension instructions created by the 4208 /// promotion. 4209 /// \p OldCost gives the cost of extension instructions before the promotion 4210 /// plus the number of instructions that have been 4211 /// matched in the addressing mode the promotion. 4212 /// \p PromotedOperand is the value that has been promoted. 4213 /// \return True if the promotion is profitable, false otherwise. 4214 bool AddressingModeMatcher::isPromotionProfitable( 4215 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { 4216 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost 4217 << '\n'); 4218 // The cost of the new extensions is greater than the cost of the 4219 // old extension plus what we folded. 4220 // This is not profitable. 4221 if (NewCost > OldCost) 4222 return false; 4223 if (NewCost < OldCost) 4224 return true; 4225 // The promotion is neutral but it may help folding the sign extension in 4226 // loads for instance. 4227 // Check that we did not create an illegal instruction. 4228 return isPromotedInstructionLegal(TLI, DL, PromotedOperand); 4229 } 4230 4231 /// Given an instruction or constant expr, see if we can fold the operation 4232 /// into the addressing mode. If so, update the addressing mode and return 4233 /// true, otherwise return false without modifying AddrMode. 4234 /// If \p MovedAway is not NULL, it contains the information of whether or 4235 /// not AddrInst has to be folded into the addressing mode on success. 4236 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing 4237 /// because it has been moved away. 4238 /// Thus AddrInst must not be added in the matched instructions. 4239 /// This state can happen when AddrInst is a sext, since it may be moved away. 4240 /// Therefore, AddrInst may not be valid when MovedAway is true and it must 4241 /// not be referenced anymore. 4242 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, 4243 unsigned Depth, 4244 bool *MovedAway) { 4245 // Avoid exponential behavior on extremely deep expression trees. 4246 if (Depth >= 5) return false; 4247 4248 // By default, all matched instructions stay in place. 4249 if (MovedAway) 4250 *MovedAway = false; 4251 4252 switch (Opcode) { 4253 case Instruction::PtrToInt: 4254 // PtrToInt is always a noop, as we know that the int type is pointer sized. 4255 return matchAddr(AddrInst->getOperand(0), Depth); 4256 case Instruction::IntToPtr: { 4257 auto AS = AddrInst->getType()->getPointerAddressSpace(); 4258 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); 4259 // This inttoptr is a no-op if the integer type is pointer sized. 4260 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) 4261 return matchAddr(AddrInst->getOperand(0), Depth); 4262 return false; 4263 } 4264 case Instruction::BitCast: 4265 // BitCast is always a noop, and we can handle it as long as it is 4266 // int->int or pointer->pointer (we don't want int<->fp or something). 4267 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() && 4268 // Don't touch identity bitcasts. These were probably put here by LSR, 4269 // and we don't want to mess around with them. Assume it knows what it 4270 // is doing. 4271 AddrInst->getOperand(0)->getType() != AddrInst->getType()) 4272 return matchAddr(AddrInst->getOperand(0), Depth); 4273 return false; 4274 case Instruction::AddrSpaceCast: { 4275 unsigned SrcAS 4276 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); 4277 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); 4278 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 4279 return matchAddr(AddrInst->getOperand(0), Depth); 4280 return false; 4281 } 4282 case Instruction::Add: { 4283 // Check to see if we can merge in the RHS then the LHS. If so, we win. 4284 ExtAddrMode BackupAddrMode = AddrMode; 4285 unsigned OldSize = AddrModeInsts.size(); 4286 // Start a transaction at this point. 4287 // The LHS may match but not the RHS. 4288 // Therefore, we need a higher level restoration point to undo partially 4289 // matched operation. 4290 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4291 TPT.getRestorationPoint(); 4292 4293 AddrMode.InBounds = false; 4294 if (matchAddr(AddrInst->getOperand(1), Depth+1) && 4295 matchAddr(AddrInst->getOperand(0), Depth+1)) 4296 return true; 4297 4298 // Restore the old addr mode info. 4299 AddrMode = BackupAddrMode; 4300 AddrModeInsts.resize(OldSize); 4301 TPT.rollback(LastKnownGood); 4302 4303 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. 4304 if (matchAddr(AddrInst->getOperand(0), Depth+1) && 4305 matchAddr(AddrInst->getOperand(1), Depth+1)) 4306 return true; 4307 4308 // Otherwise we definitely can't merge the ADD in. 4309 AddrMode = BackupAddrMode; 4310 AddrModeInsts.resize(OldSize); 4311 TPT.rollback(LastKnownGood); 4312 break; 4313 } 4314 //case Instruction::Or: 4315 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. 4316 //break; 4317 case Instruction::Mul: 4318 case Instruction::Shl: { 4319 // Can only handle X*C and X << C. 4320 AddrMode.InBounds = false; 4321 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); 4322 if (!RHS || RHS->getBitWidth() > 64) 4323 return false; 4324 int64_t Scale = RHS->getSExtValue(); 4325 if (Opcode == Instruction::Shl) 4326 Scale = 1LL << Scale; 4327 4328 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); 4329 } 4330 case Instruction::GetElementPtr: { 4331 // Scan the GEP. We check it if it contains constant offsets and at most 4332 // one variable offset. 4333 int VariableOperand = -1; 4334 unsigned VariableScale = 0; 4335 4336 int64_t ConstantOffset = 0; 4337 gep_type_iterator GTI = gep_type_begin(AddrInst); 4338 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { 4339 if (StructType *STy = GTI.getStructTypeOrNull()) { 4340 const StructLayout *SL = DL.getStructLayout(STy); 4341 unsigned Idx = 4342 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); 4343 ConstantOffset += SL->getElementOffset(Idx); 4344 } else { 4345 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); 4346 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { 4347 const APInt &CVal = CI->getValue(); 4348 if (CVal.getMinSignedBits() <= 64) { 4349 ConstantOffset += CVal.getSExtValue() * TypeSize; 4350 continue; 4351 } 4352 } 4353 if (TypeSize) { // Scales of zero don't do anything. 4354 // We only allow one variable index at the moment. 4355 if (VariableOperand != -1) 4356 return false; 4357 4358 // Remember the variable index. 4359 VariableOperand = i; 4360 VariableScale = TypeSize; 4361 } 4362 } 4363 } 4364 4365 // A common case is for the GEP to only do a constant offset. In this case, 4366 // just add it to the disp field and check validity. 4367 if (VariableOperand == -1) { 4368 AddrMode.BaseOffs += ConstantOffset; 4369 if (ConstantOffset == 0 || 4370 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { 4371 // Check to see if we can fold the base pointer in too. 4372 if (matchAddr(AddrInst->getOperand(0), Depth+1)) { 4373 if (!cast<GEPOperator>(AddrInst)->isInBounds()) 4374 AddrMode.InBounds = false; 4375 return true; 4376 } 4377 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) && 4378 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 && 4379 ConstantOffset > 0) { 4380 // Record GEPs with non-zero offsets as candidates for splitting in the 4381 // event that the offset cannot fit into the r+i addressing mode. 4382 // Simple and common case that only one GEP is used in calculating the 4383 // address for the memory access. 4384 Value *Base = AddrInst->getOperand(0); 4385 auto *BaseI = dyn_cast<Instruction>(Base); 4386 auto *GEP = cast<GetElementPtrInst>(AddrInst); 4387 if (isa<Argument>(Base) || isa<GlobalValue>(Base) || 4388 (BaseI && !isa<CastInst>(BaseI) && 4389 !isa<GetElementPtrInst>(BaseI))) { 4390 // Make sure the parent block allows inserting non-PHI instructions 4391 // before the terminator. 4392 BasicBlock *Parent = 4393 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock(); 4394 if (!Parent->getTerminator()->isEHPad()) 4395 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset); 4396 } 4397 } 4398 AddrMode.BaseOffs -= ConstantOffset; 4399 return false; 4400 } 4401 4402 // Save the valid addressing mode in case we can't match. 4403 ExtAddrMode BackupAddrMode = AddrMode; 4404 unsigned OldSize = AddrModeInsts.size(); 4405 4406 // See if the scale and offset amount is valid for this target. 4407 AddrMode.BaseOffs += ConstantOffset; 4408 if (!cast<GEPOperator>(AddrInst)->isInBounds()) 4409 AddrMode.InBounds = false; 4410 4411 // Match the base operand of the GEP. 4412 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { 4413 // If it couldn't be matched, just stuff the value in a register. 4414 if (AddrMode.HasBaseReg) { 4415 AddrMode = BackupAddrMode; 4416 AddrModeInsts.resize(OldSize); 4417 return false; 4418 } 4419 AddrMode.HasBaseReg = true; 4420 AddrMode.BaseReg = AddrInst->getOperand(0); 4421 } 4422 4423 // Match the remaining variable portion of the GEP. 4424 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, 4425 Depth)) { 4426 // If it couldn't be matched, try stuffing the base into a register 4427 // instead of matching it, and retrying the match of the scale. 4428 AddrMode = BackupAddrMode; 4429 AddrModeInsts.resize(OldSize); 4430 if (AddrMode.HasBaseReg) 4431 return false; 4432 AddrMode.HasBaseReg = true; 4433 AddrMode.BaseReg = AddrInst->getOperand(0); 4434 AddrMode.BaseOffs += ConstantOffset; 4435 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), 4436 VariableScale, Depth)) { 4437 // If even that didn't work, bail. 4438 AddrMode = BackupAddrMode; 4439 AddrModeInsts.resize(OldSize); 4440 return false; 4441 } 4442 } 4443 4444 return true; 4445 } 4446 case Instruction::SExt: 4447 case Instruction::ZExt: { 4448 Instruction *Ext = dyn_cast<Instruction>(AddrInst); 4449 if (!Ext) 4450 return false; 4451 4452 // Try to move this ext out of the way of the addressing mode. 4453 // Ask for a method for doing so. 4454 TypePromotionHelper::Action TPH = 4455 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); 4456 if (!TPH) 4457 return false; 4458 4459 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4460 TPT.getRestorationPoint(); 4461 unsigned CreatedInstsCost = 0; 4462 unsigned ExtCost = !TLI.isExtFree(Ext); 4463 Value *PromotedOperand = 4464 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); 4465 // SExt has been moved away. 4466 // Thus either it will be rematched later in the recursive calls or it is 4467 // gone. Anyway, we must not fold it into the addressing mode at this point. 4468 // E.g., 4469 // op = add opnd, 1 4470 // idx = ext op 4471 // addr = gep base, idx 4472 // is now: 4473 // promotedOpnd = ext opnd <- no match here 4474 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) 4475 // addr = gep base, op <- match 4476 if (MovedAway) 4477 *MovedAway = true; 4478 4479 assert(PromotedOperand && 4480 "TypePromotionHelper should have filtered out those cases"); 4481 4482 ExtAddrMode BackupAddrMode = AddrMode; 4483 unsigned OldSize = AddrModeInsts.size(); 4484 4485 if (!matchAddr(PromotedOperand, Depth) || 4486 // The total of the new cost is equal to the cost of the created 4487 // instructions. 4488 // The total of the old cost is equal to the cost of the extension plus 4489 // what we have saved in the addressing mode. 4490 !isPromotionProfitable(CreatedInstsCost, 4491 ExtCost + (AddrModeInsts.size() - OldSize), 4492 PromotedOperand)) { 4493 AddrMode = BackupAddrMode; 4494 AddrModeInsts.resize(OldSize); 4495 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); 4496 TPT.rollback(LastKnownGood); 4497 return false; 4498 } 4499 return true; 4500 } 4501 } 4502 return false; 4503 } 4504 4505 /// If we can, try to add the value of 'Addr' into the current addressing mode. 4506 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode 4507 /// unmodified. This assumes that Addr is either a pointer type or intptr_t 4508 /// for the target. 4509 /// 4510 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { 4511 // Start a transaction at this point that we will rollback if the matching 4512 // fails. 4513 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4514 TPT.getRestorationPoint(); 4515 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { 4516 if (CI->getValue().isSignedIntN(64)) { 4517 // Fold in immediates if legal for the target. 4518 AddrMode.BaseOffs += CI->getSExtValue(); 4519 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) 4520 return true; 4521 AddrMode.BaseOffs -= CI->getSExtValue(); 4522 } 4523 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { 4524 // If this is a global variable, try to fold it into the addressing mode. 4525 if (!AddrMode.BaseGV) { 4526 AddrMode.BaseGV = GV; 4527 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) 4528 return true; 4529 AddrMode.BaseGV = nullptr; 4530 } 4531 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { 4532 ExtAddrMode BackupAddrMode = AddrMode; 4533 unsigned OldSize = AddrModeInsts.size(); 4534 4535 // Check to see if it is possible to fold this operation. 4536 bool MovedAway = false; 4537 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { 4538 // This instruction may have been moved away. If so, there is nothing 4539 // to check here. 4540 if (MovedAway) 4541 return true; 4542 // Okay, it's possible to fold this. Check to see if it is actually 4543 // *profitable* to do so. We use a simple cost model to avoid increasing 4544 // register pressure too much. 4545 if (I->hasOneUse() || 4546 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { 4547 AddrModeInsts.push_back(I); 4548 return true; 4549 } 4550 4551 // It isn't profitable to do this, roll back. 4552 //cerr << "NOT FOLDING: " << *I; 4553 AddrMode = BackupAddrMode; 4554 AddrModeInsts.resize(OldSize); 4555 TPT.rollback(LastKnownGood); 4556 } 4557 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { 4558 if (matchOperationAddr(CE, CE->getOpcode(), Depth)) 4559 return true; 4560 TPT.rollback(LastKnownGood); 4561 } else if (isa<ConstantPointerNull>(Addr)) { 4562 // Null pointer gets folded without affecting the addressing mode. 4563 return true; 4564 } 4565 4566 // Worse case, the target should support [reg] addressing modes. :) 4567 if (!AddrMode.HasBaseReg) { 4568 AddrMode.HasBaseReg = true; 4569 AddrMode.BaseReg = Addr; 4570 // Still check for legality in case the target supports [imm] but not [i+r]. 4571 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) 4572 return true; 4573 AddrMode.HasBaseReg = false; 4574 AddrMode.BaseReg = nullptr; 4575 } 4576 4577 // If the base register is already taken, see if we can do [r+r]. 4578 if (AddrMode.Scale == 0) { 4579 AddrMode.Scale = 1; 4580 AddrMode.ScaledReg = Addr; 4581 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) 4582 return true; 4583 AddrMode.Scale = 0; 4584 AddrMode.ScaledReg = nullptr; 4585 } 4586 // Couldn't match. 4587 TPT.rollback(LastKnownGood); 4588 return false; 4589 } 4590 4591 /// Check to see if all uses of OpVal by the specified inline asm call are due 4592 /// to memory operands. If so, return true, otherwise return false. 4593 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, 4594 const TargetLowering &TLI, 4595 const TargetRegisterInfo &TRI) { 4596 const Function *F = CI->getFunction(); 4597 TargetLowering::AsmOperandInfoVector TargetConstraints = 4598 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI); 4599 4600 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 4601 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; 4602 4603 // Compute the constraint code and ConstraintType to use. 4604 TLI.ComputeConstraintToUse(OpInfo, SDValue()); 4605 4606 // If this asm operand is our Value*, and if it isn't an indirect memory 4607 // operand, we can't fold it! 4608 if (OpInfo.CallOperandVal == OpVal && 4609 (OpInfo.ConstraintType != TargetLowering::C_Memory || 4610 !OpInfo.isIndirect)) 4611 return false; 4612 } 4613 4614 return true; 4615 } 4616 4617 // Max number of memory uses to look at before aborting the search to conserve 4618 // compile time. 4619 static constexpr int MaxMemoryUsesToScan = 20; 4620 4621 /// Recursively walk all the uses of I until we find a memory use. 4622 /// If we find an obviously non-foldable instruction, return true. 4623 /// Add the ultimately found memory instructions to MemoryUses. 4624 static bool FindAllMemoryUses( 4625 Instruction *I, 4626 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, 4627 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI, 4628 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, 4629 BlockFrequencyInfo *BFI, int SeenInsts = 0) { 4630 // If we already considered this instruction, we're done. 4631 if (!ConsideredInsts.insert(I).second) 4632 return false; 4633 4634 // If this is an obviously unfoldable instruction, bail out. 4635 if (!MightBeFoldableInst(I)) 4636 return true; 4637 4638 // Loop over all the uses, recursively processing them. 4639 for (Use &U : I->uses()) { 4640 // Conservatively return true if we're seeing a large number or a deep chain 4641 // of users. This avoids excessive compilation times in pathological cases. 4642 if (SeenInsts++ >= MaxMemoryUsesToScan) 4643 return true; 4644 4645 Instruction *UserI = cast<Instruction>(U.getUser()); 4646 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { 4647 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); 4648 continue; 4649 } 4650 4651 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { 4652 unsigned opNo = U.getOperandNo(); 4653 if (opNo != StoreInst::getPointerOperandIndex()) 4654 return true; // Storing addr, not into addr. 4655 MemoryUses.push_back(std::make_pair(SI, opNo)); 4656 continue; 4657 } 4658 4659 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) { 4660 unsigned opNo = U.getOperandNo(); 4661 if (opNo != AtomicRMWInst::getPointerOperandIndex()) 4662 return true; // Storing addr, not into addr. 4663 MemoryUses.push_back(std::make_pair(RMW, opNo)); 4664 continue; 4665 } 4666 4667 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) { 4668 unsigned opNo = U.getOperandNo(); 4669 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex()) 4670 return true; // Storing addr, not into addr. 4671 MemoryUses.push_back(std::make_pair(CmpX, opNo)); 4672 continue; 4673 } 4674 4675 if (CallInst *CI = dyn_cast<CallInst>(UserI)) { 4676 if (CI->hasFnAttr(Attribute::Cold)) { 4677 // If this is a cold call, we can sink the addressing calculation into 4678 // the cold path. See optimizeCallInst 4679 bool OptForSize = OptSize || 4680 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI); 4681 if (!OptForSize) 4682 continue; 4683 } 4684 4685 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand()); 4686 if (!IA) return true; 4687 4688 // If this is a memory operand, we're cool, otherwise bail out. 4689 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI)) 4690 return true; 4691 continue; 4692 } 4693 4694 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, 4695 PSI, BFI, SeenInsts)) 4696 return true; 4697 } 4698 4699 return false; 4700 } 4701 4702 /// Return true if Val is already known to be live at the use site that we're 4703 /// folding it into. If so, there is no cost to include it in the addressing 4704 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the 4705 /// instruction already. 4706 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, 4707 Value *KnownLive2) { 4708 // If Val is either of the known-live values, we know it is live! 4709 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) 4710 return true; 4711 4712 // All values other than instructions and arguments (e.g. constants) are live. 4713 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; 4714 4715 // If Val is a constant sized alloca in the entry block, it is live, this is 4716 // true because it is just a reference to the stack/frame pointer, which is 4717 // live for the whole function. 4718 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) 4719 if (AI->isStaticAlloca()) 4720 return true; 4721 4722 // Check to see if this value is already used in the memory instruction's 4723 // block. If so, it's already live into the block at the very least, so we 4724 // can reasonably fold it. 4725 return Val->isUsedInBasicBlock(MemoryInst->getParent()); 4726 } 4727 4728 /// It is possible for the addressing mode of the machine to fold the specified 4729 /// instruction into a load or store that ultimately uses it. 4730 /// However, the specified instruction has multiple uses. 4731 /// Given this, it may actually increase register pressure to fold it 4732 /// into the load. For example, consider this code: 4733 /// 4734 /// X = ... 4735 /// Y = X+1 4736 /// use(Y) -> nonload/store 4737 /// Z = Y+1 4738 /// load Z 4739 /// 4740 /// In this case, Y has multiple uses, and can be folded into the load of Z 4741 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to 4742 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one 4743 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the 4744 /// number of computations either. 4745 /// 4746 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If 4747 /// X was live across 'load Z' for other reasons, we actually *would* want to 4748 /// fold the addressing mode in the Z case. This would make Y die earlier. 4749 bool AddressingModeMatcher:: 4750 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, 4751 ExtAddrMode &AMAfter) { 4752 if (IgnoreProfitability) return true; 4753 4754 // AMBefore is the addressing mode before this instruction was folded into it, 4755 // and AMAfter is the addressing mode after the instruction was folded. Get 4756 // the set of registers referenced by AMAfter and subtract out those 4757 // referenced by AMBefore: this is the set of values which folding in this 4758 // address extends the lifetime of. 4759 // 4760 // Note that there are only two potential values being referenced here, 4761 // BaseReg and ScaleReg (global addresses are always available, as are any 4762 // folded immediates). 4763 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; 4764 4765 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their 4766 // lifetime wasn't extended by adding this instruction. 4767 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) 4768 BaseReg = nullptr; 4769 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) 4770 ScaledReg = nullptr; 4771 4772 // If folding this instruction (and it's subexprs) didn't extend any live 4773 // ranges, we're ok with it. 4774 if (!BaseReg && !ScaledReg) 4775 return true; 4776 4777 // If all uses of this instruction can have the address mode sunk into them, 4778 // we can remove the addressing mode and effectively trade one live register 4779 // for another (at worst.) In this context, folding an addressing mode into 4780 // the use is just a particularly nice way of sinking it. 4781 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; 4782 SmallPtrSet<Instruction*, 16> ConsideredInsts; 4783 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, 4784 PSI, BFI)) 4785 return false; // Has a non-memory, non-foldable use! 4786 4787 // Now that we know that all uses of this instruction are part of a chain of 4788 // computation involving only operations that could theoretically be folded 4789 // into a memory use, loop over each of these memory operation uses and see 4790 // if they could *actually* fold the instruction. The assumption is that 4791 // addressing modes are cheap and that duplicating the computation involved 4792 // many times is worthwhile, even on a fastpath. For sinking candidates 4793 // (i.e. cold call sites), this serves as a way to prevent excessive code 4794 // growth since most architectures have some reasonable small and fast way to 4795 // compute an effective address. (i.e LEA on x86) 4796 SmallVector<Instruction*, 32> MatchedAddrModeInsts; 4797 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { 4798 Instruction *User = MemoryUses[i].first; 4799 unsigned OpNo = MemoryUses[i].second; 4800 4801 // Get the access type of this use. If the use isn't a pointer, we don't 4802 // know what it accesses. 4803 Value *Address = User->getOperand(OpNo); 4804 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); 4805 if (!AddrTy) 4806 return false; 4807 Type *AddressAccessTy = AddrTy->getElementType(); 4808 unsigned AS = AddrTy->getAddressSpace(); 4809 4810 // Do a match against the root of this address, ignoring profitability. This 4811 // will tell us if the addressing mode for the memory operation will 4812 // *actually* cover the shared instruction. 4813 ExtAddrMode Result; 4814 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, 4815 0); 4816 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4817 TPT.getRestorationPoint(); 4818 AddressingModeMatcher Matcher( 4819 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result, 4820 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI, BFI); 4821 Matcher.IgnoreProfitability = true; 4822 bool Success = Matcher.matchAddr(Address, 0); 4823 (void)Success; assert(Success && "Couldn't select *anything*?"); 4824 4825 // The match was to check the profitability, the changes made are not 4826 // part of the original matcher. Therefore, they should be dropped 4827 // otherwise the original matcher will not present the right state. 4828 TPT.rollback(LastKnownGood); 4829 4830 // If the match didn't cover I, then it won't be shared by it. 4831 if (!is_contained(MatchedAddrModeInsts, I)) 4832 return false; 4833 4834 MatchedAddrModeInsts.clear(); 4835 } 4836 4837 return true; 4838 } 4839 4840 /// Return true if the specified values are defined in a 4841 /// different basic block than BB. 4842 static bool IsNonLocalValue(Value *V, BasicBlock *BB) { 4843 if (Instruction *I = dyn_cast<Instruction>(V)) 4844 return I->getParent() != BB; 4845 return false; 4846 } 4847 4848 /// Sink addressing mode computation immediate before MemoryInst if doing so 4849 /// can be done without increasing register pressure. The need for the 4850 /// register pressure constraint means this can end up being an all or nothing 4851 /// decision for all uses of the same addressing computation. 4852 /// 4853 /// Load and Store Instructions often have addressing modes that can do 4854 /// significant amounts of computation. As such, instruction selection will try 4855 /// to get the load or store to do as much computation as possible for the 4856 /// program. The problem is that isel can only see within a single block. As 4857 /// such, we sink as much legal addressing mode work into the block as possible. 4858 /// 4859 /// This method is used to optimize both load/store and inline asms with memory 4860 /// operands. It's also used to sink addressing computations feeding into cold 4861 /// call sites into their (cold) basic block. 4862 /// 4863 /// The motivation for handling sinking into cold blocks is that doing so can 4864 /// both enable other address mode sinking (by satisfying the register pressure 4865 /// constraint above), and reduce register pressure globally (by removing the 4866 /// addressing mode computation from the fast path entirely.). 4867 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, 4868 Type *AccessTy, unsigned AddrSpace) { 4869 Value *Repl = Addr; 4870 4871 // Try to collapse single-value PHI nodes. This is necessary to undo 4872 // unprofitable PRE transformations. 4873 SmallVector<Value*, 8> worklist; 4874 SmallPtrSet<Value*, 16> Visited; 4875 worklist.push_back(Addr); 4876 4877 // Use a worklist to iteratively look through PHI and select nodes, and 4878 // ensure that the addressing mode obtained from the non-PHI/select roots of 4879 // the graph are compatible. 4880 bool PhiOrSelectSeen = false; 4881 SmallVector<Instruction*, 16> AddrModeInsts; 4882 const SimplifyQuery SQ(*DL, TLInfo); 4883 AddressingModeCombiner AddrModes(SQ, Addr); 4884 TypePromotionTransaction TPT(RemovedInsts); 4885 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 4886 TPT.getRestorationPoint(); 4887 while (!worklist.empty()) { 4888 Value *V = worklist.back(); 4889 worklist.pop_back(); 4890 4891 // We allow traversing cyclic Phi nodes. 4892 // In case of success after this loop we ensure that traversing through 4893 // Phi nodes ends up with all cases to compute address of the form 4894 // BaseGV + Base + Scale * Index + Offset 4895 // where Scale and Offset are constans and BaseGV, Base and Index 4896 // are exactly the same Values in all cases. 4897 // It means that BaseGV, Scale and Offset dominate our memory instruction 4898 // and have the same value as they had in address computation represented 4899 // as Phi. So we can safely sink address computation to memory instruction. 4900 if (!Visited.insert(V).second) 4901 continue; 4902 4903 // For a PHI node, push all of its incoming values. 4904 if (PHINode *P = dyn_cast<PHINode>(V)) { 4905 for (Value *IncValue : P->incoming_values()) 4906 worklist.push_back(IncValue); 4907 PhiOrSelectSeen = true; 4908 continue; 4909 } 4910 // Similar for select. 4911 if (SelectInst *SI = dyn_cast<SelectInst>(V)) { 4912 worklist.push_back(SI->getFalseValue()); 4913 worklist.push_back(SI->getTrueValue()); 4914 PhiOrSelectSeen = true; 4915 continue; 4916 } 4917 4918 // For non-PHIs, determine the addressing mode being computed. Note that 4919 // the result may differ depending on what other uses our candidate 4920 // addressing instructions might have. 4921 AddrModeInsts.clear(); 4922 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, 4923 0); 4924 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( 4925 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI, 4926 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI, 4927 BFI.get()); 4928 4929 GetElementPtrInst *GEP = LargeOffsetGEP.first; 4930 if (GEP && !NewGEPBases.count(GEP)) { 4931 // If splitting the underlying data structure can reduce the offset of a 4932 // GEP, collect the GEP. Skip the GEPs that are the new bases of 4933 // previously split data structures. 4934 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP); 4935 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end()) 4936 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size(); 4937 } 4938 4939 NewAddrMode.OriginalValue = V; 4940 if (!AddrModes.addNewAddrMode(NewAddrMode)) 4941 break; 4942 } 4943 4944 // Try to combine the AddrModes we've collected. If we couldn't collect any, 4945 // or we have multiple but either couldn't combine them or combining them 4946 // wouldn't do anything useful, bail out now. 4947 if (!AddrModes.combineAddrModes()) { 4948 TPT.rollback(LastKnownGood); 4949 return false; 4950 } 4951 TPT.commit(); 4952 4953 // Get the combined AddrMode (or the only AddrMode, if we only had one). 4954 ExtAddrMode AddrMode = AddrModes.getAddrMode(); 4955 4956 // If all the instructions matched are already in this BB, don't do anything. 4957 // If we saw a Phi node then it is not local definitely, and if we saw a select 4958 // then we want to push the address calculation past it even if it's already 4959 // in this BB. 4960 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) { 4961 return IsNonLocalValue(V, MemoryInst->getParent()); 4962 })) { 4963 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode 4964 << "\n"); 4965 return false; 4966 } 4967 4968 // Insert this computation right after this user. Since our caller is 4969 // scanning from the top of the BB to the bottom, reuse of the expr are 4970 // guaranteed to happen later. 4971 IRBuilder<> Builder(MemoryInst); 4972 4973 // Now that we determined the addressing expression we want to use and know 4974 // that we have to sink it into this block. Check to see if we have already 4975 // done this for some other load/store instr in this block. If so, reuse 4976 // the computation. Before attempting reuse, check if the address is valid 4977 // as it may have been erased. 4978 4979 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr]; 4980 4981 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; 4982 if (SunkAddr) { 4983 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode 4984 << " for " << *MemoryInst << "\n"); 4985 if (SunkAddr->getType() != Addr->getType()) 4986 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); 4987 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() && 4988 SubtargetInfo->addrSinkUsingGEPs())) { 4989 // By default, we use the GEP-based method when AA is used later. This 4990 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. 4991 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode 4992 << " for " << *MemoryInst << "\n"); 4993 Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); 4994 Value *ResultPtr = nullptr, *ResultIndex = nullptr; 4995 4996 // First, find the pointer. 4997 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { 4998 ResultPtr = AddrMode.BaseReg; 4999 AddrMode.BaseReg = nullptr; 5000 } 5001 5002 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { 5003 // We can't add more than one pointer together, nor can we scale a 5004 // pointer (both of which seem meaningless). 5005 if (ResultPtr || AddrMode.Scale != 1) 5006 return false; 5007 5008 ResultPtr = AddrMode.ScaledReg; 5009 AddrMode.Scale = 0; 5010 } 5011 5012 // It is only safe to sign extend the BaseReg if we know that the math 5013 // required to create it did not overflow before we extend it. Since 5014 // the original IR value was tossed in favor of a constant back when 5015 // the AddrMode was created we need to bail out gracefully if widths 5016 // do not match instead of extending it. 5017 // 5018 // (See below for code to add the scale.) 5019 if (AddrMode.Scale) { 5020 Type *ScaledRegTy = AddrMode.ScaledReg->getType(); 5021 if (cast<IntegerType>(IntPtrTy)->getBitWidth() > 5022 cast<IntegerType>(ScaledRegTy)->getBitWidth()) 5023 return false; 5024 } 5025 5026 if (AddrMode.BaseGV) { 5027 if (ResultPtr) 5028 return false; 5029 5030 ResultPtr = AddrMode.BaseGV; 5031 } 5032 5033 // If the real base value actually came from an inttoptr, then the matcher 5034 // will look through it and provide only the integer value. In that case, 5035 // use it here. 5036 if (!DL->isNonIntegralPointerType(Addr->getType())) { 5037 if (!ResultPtr && AddrMode.BaseReg) { 5038 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), 5039 "sunkaddr"); 5040 AddrMode.BaseReg = nullptr; 5041 } else if (!ResultPtr && AddrMode.Scale == 1) { 5042 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), 5043 "sunkaddr"); 5044 AddrMode.Scale = 0; 5045 } 5046 } 5047 5048 if (!ResultPtr && 5049 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { 5050 SunkAddr = Constant::getNullValue(Addr->getType()); 5051 } else if (!ResultPtr) { 5052 return false; 5053 } else { 5054 Type *I8PtrTy = 5055 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); 5056 Type *I8Ty = Builder.getInt8Ty(); 5057 5058 // Start with the base register. Do this first so that subsequent address 5059 // matching finds it last, which will prevent it from trying to match it 5060 // as the scaled value in case it happens to be a mul. That would be 5061 // problematic if we've sunk a different mul for the scale, because then 5062 // we'd end up sinking both muls. 5063 if (AddrMode.BaseReg) { 5064 Value *V = AddrMode.BaseReg; 5065 if (V->getType() != IntPtrTy) 5066 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); 5067 5068 ResultIndex = V; 5069 } 5070 5071 // Add the scale value. 5072 if (AddrMode.Scale) { 5073 Value *V = AddrMode.ScaledReg; 5074 if (V->getType() == IntPtrTy) { 5075 // done. 5076 } else { 5077 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() < 5078 cast<IntegerType>(V->getType())->getBitWidth() && 5079 "We can't transform if ScaledReg is too narrow"); 5080 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); 5081 } 5082 5083 if (AddrMode.Scale != 1) 5084 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), 5085 "sunkaddr"); 5086 if (ResultIndex) 5087 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); 5088 else 5089 ResultIndex = V; 5090 } 5091 5092 // Add in the Base Offset if present. 5093 if (AddrMode.BaseOffs) { 5094 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); 5095 if (ResultIndex) { 5096 // We need to add this separately from the scale above to help with 5097 // SDAG consecutive load/store merging. 5098 if (ResultPtr->getType() != I8PtrTy) 5099 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); 5100 ResultPtr = 5101 AddrMode.InBounds 5102 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex, 5103 "sunkaddr") 5104 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); 5105 } 5106 5107 ResultIndex = V; 5108 } 5109 5110 if (!ResultIndex) { 5111 SunkAddr = ResultPtr; 5112 } else { 5113 if (ResultPtr->getType() != I8PtrTy) 5114 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); 5115 SunkAddr = 5116 AddrMode.InBounds 5117 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex, 5118 "sunkaddr") 5119 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); 5120 } 5121 5122 if (SunkAddr->getType() != Addr->getType()) 5123 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); 5124 } 5125 } else { 5126 // We'd require a ptrtoint/inttoptr down the line, which we can't do for 5127 // non-integral pointers, so in that case bail out now. 5128 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr; 5129 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr; 5130 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy); 5131 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy); 5132 if (DL->isNonIntegralPointerType(Addr->getType()) || 5133 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) || 5134 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) || 5135 (AddrMode.BaseGV && 5136 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType()))) 5137 return false; 5138 5139 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode 5140 << " for " << *MemoryInst << "\n"); 5141 Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); 5142 Value *Result = nullptr; 5143 5144 // Start with the base register. Do this first so that subsequent address 5145 // matching finds it last, which will prevent it from trying to match it 5146 // as the scaled value in case it happens to be a mul. That would be 5147 // problematic if we've sunk a different mul for the scale, because then 5148 // we'd end up sinking both muls. 5149 if (AddrMode.BaseReg) { 5150 Value *V = AddrMode.BaseReg; 5151 if (V->getType()->isPointerTy()) 5152 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); 5153 if (V->getType() != IntPtrTy) 5154 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); 5155 Result = V; 5156 } 5157 5158 // Add the scale value. 5159 if (AddrMode.Scale) { 5160 Value *V = AddrMode.ScaledReg; 5161 if (V->getType() == IntPtrTy) { 5162 // done. 5163 } else if (V->getType()->isPointerTy()) { 5164 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); 5165 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < 5166 cast<IntegerType>(V->getType())->getBitWidth()) { 5167 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); 5168 } else { 5169 // It is only safe to sign extend the BaseReg if we know that the math 5170 // required to create it did not overflow before we extend it. Since 5171 // the original IR value was tossed in favor of a constant back when 5172 // the AddrMode was created we need to bail out gracefully if widths 5173 // do not match instead of extending it. 5174 Instruction *I = dyn_cast_or_null<Instruction>(Result); 5175 if (I && (Result != AddrMode.BaseReg)) 5176 I->eraseFromParent(); 5177 return false; 5178 } 5179 if (AddrMode.Scale != 1) 5180 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), 5181 "sunkaddr"); 5182 if (Result) 5183 Result = Builder.CreateAdd(Result, V, "sunkaddr"); 5184 else 5185 Result = V; 5186 } 5187 5188 // Add in the BaseGV if present. 5189 if (AddrMode.BaseGV) { 5190 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); 5191 if (Result) 5192 Result = Builder.CreateAdd(Result, V, "sunkaddr"); 5193 else 5194 Result = V; 5195 } 5196 5197 // Add in the Base Offset if present. 5198 if (AddrMode.BaseOffs) { 5199 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); 5200 if (Result) 5201 Result = Builder.CreateAdd(Result, V, "sunkaddr"); 5202 else 5203 Result = V; 5204 } 5205 5206 if (!Result) 5207 SunkAddr = Constant::getNullValue(Addr->getType()); 5208 else 5209 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); 5210 } 5211 5212 MemoryInst->replaceUsesOfWith(Repl, SunkAddr); 5213 // Store the newly computed address into the cache. In the case we reused a 5214 // value, this should be idempotent. 5215 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr); 5216 5217 // If we have no uses, recursively delete the value and all dead instructions 5218 // using it. 5219 if (Repl->use_empty()) { 5220 // This can cause recursive deletion, which can invalidate our iterator. 5221 // Use a WeakTrackingVH to hold onto it in case this happens. 5222 Value *CurValue = &*CurInstIterator; 5223 WeakTrackingVH IterHandle(CurValue); 5224 BasicBlock *BB = CurInstIterator->getParent(); 5225 5226 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); 5227 5228 if (IterHandle != CurValue) { 5229 // If the iterator instruction was recursively deleted, start over at the 5230 // start of the block. 5231 CurInstIterator = BB->begin(); 5232 SunkAddrs.clear(); 5233 } 5234 } 5235 ++NumMemoryInsts; 5236 return true; 5237 } 5238 5239 /// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find 5240 /// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can 5241 /// only handle a 2 operand GEP in the same basic block or a splat constant 5242 /// vector. The 2 operands to the GEP must have a scalar pointer and a vector 5243 /// index. 5244 /// 5245 /// If the existing GEP has a vector base pointer that is splat, we can look 5246 /// through the splat to find the scalar pointer. If we can't find a scalar 5247 /// pointer there's nothing we can do. 5248 /// 5249 /// If we have a GEP with more than 2 indices where the middle indices are all 5250 /// zeroes, we can replace it with 2 GEPs where the second has 2 operands. 5251 /// 5252 /// If the final index isn't a vector or is a splat, we can emit a scalar GEP 5253 /// followed by a GEP with an all zeroes vector index. This will enable 5254 /// SelectionDAGBuilder to use a the scalar GEP as the uniform base and have a 5255 /// zero index. 5256 bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst, 5257 Value *Ptr) { 5258 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 5259 if (!GEP || !GEP->hasIndices()) 5260 return false; 5261 5262 // If the GEP and the gather/scatter aren't in the same BB, don't optimize. 5263 // FIXME: We should support this by sinking the GEP. 5264 if (MemoryInst->getParent() != GEP->getParent()) 5265 return false; 5266 5267 SmallVector<Value *, 2> Ops(GEP->op_begin(), GEP->op_end()); 5268 5269 bool RewriteGEP = false; 5270 5271 if (Ops[0]->getType()->isVectorTy()) { 5272 Ops[0] = const_cast<Value *>(getSplatValue(Ops[0])); 5273 if (!Ops[0]) 5274 return false; 5275 RewriteGEP = true; 5276 } 5277 5278 unsigned FinalIndex = Ops.size() - 1; 5279 5280 // Ensure all but the last index is 0. 5281 // FIXME: This isn't strictly required. All that's required is that they are 5282 // all scalars or splats. 5283 for (unsigned i = 1; i < FinalIndex; ++i) { 5284 auto *C = dyn_cast<Constant>(Ops[i]); 5285 if (!C) 5286 return false; 5287 if (isa<VectorType>(C->getType())) 5288 C = C->getSplatValue(); 5289 auto *CI = dyn_cast_or_null<ConstantInt>(C); 5290 if (!CI || !CI->isZero()) 5291 return false; 5292 // Scalarize the index if needed. 5293 Ops[i] = CI; 5294 } 5295 5296 // Try to scalarize the final index. 5297 if (Ops[FinalIndex]->getType()->isVectorTy()) { 5298 if (Value *V = const_cast<Value *>(getSplatValue(Ops[FinalIndex]))) { 5299 auto *C = dyn_cast<ConstantInt>(V); 5300 // Don't scalarize all zeros vector. 5301 if (!C || !C->isZero()) { 5302 Ops[FinalIndex] = V; 5303 RewriteGEP = true; 5304 } 5305 } 5306 } 5307 5308 // If we made any changes or the we have extra operands, we need to generate 5309 // new instructions. 5310 if (!RewriteGEP && Ops.size() == 2) 5311 return false; 5312 5313 unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements(); 5314 5315 IRBuilder<> Builder(MemoryInst); 5316 5317 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType()); 5318 5319 Value *NewAddr; 5320 5321 // If the final index isn't a vector, emit a scalar GEP containing all ops 5322 // and a vector GEP with all zeroes final index. 5323 if (!Ops[FinalIndex]->getType()->isVectorTy()) { 5324 NewAddr = Builder.CreateGEP(Ops[0], makeArrayRef(Ops).drop_front()); 5325 Type *IndexTy = VectorType::get(ScalarIndexTy, NumElts); 5326 NewAddr = Builder.CreateGEP(NewAddr, Constant::getNullValue(IndexTy)); 5327 } else { 5328 Value *Base = Ops[0]; 5329 Value *Index = Ops[FinalIndex]; 5330 5331 // Create a scalar GEP if there are more than 2 operands. 5332 if (Ops.size() != 2) { 5333 // Replace the last index with 0. 5334 Ops[FinalIndex] = Constant::getNullValue(ScalarIndexTy); 5335 Base = Builder.CreateGEP(Base, makeArrayRef(Ops).drop_front()); 5336 } 5337 5338 // Now create the GEP with scalar pointer and vector index. 5339 NewAddr = Builder.CreateGEP(Base, Index); 5340 } 5341 5342 MemoryInst->replaceUsesOfWith(Ptr, NewAddr); 5343 5344 // If we have no uses, recursively delete the value and all dead instructions 5345 // using it. 5346 if (Ptr->use_empty()) 5347 RecursivelyDeleteTriviallyDeadInstructions(Ptr, TLInfo); 5348 5349 return true; 5350 } 5351 5352 /// If there are any memory operands, use OptimizeMemoryInst to sink their 5353 /// address computing into the block when possible / profitable. 5354 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { 5355 bool MadeChange = false; 5356 5357 const TargetRegisterInfo *TRI = 5358 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo(); 5359 TargetLowering::AsmOperandInfoVector TargetConstraints = 5360 TLI->ParseConstraints(*DL, TRI, *CS); 5361 unsigned ArgNo = 0; 5362 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 5363 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; 5364 5365 // Compute the constraint code and ConstraintType to use. 5366 TLI->ComputeConstraintToUse(OpInfo, SDValue()); 5367 5368 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 5369 OpInfo.isIndirect) { 5370 Value *OpVal = CS->getArgOperand(ArgNo++); 5371 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); 5372 } else if (OpInfo.Type == InlineAsm::isInput) 5373 ArgNo++; 5374 } 5375 5376 return MadeChange; 5377 } 5378 5379 /// Check if all the uses of \p Val are equivalent (or free) zero or 5380 /// sign extensions. 5381 static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) { 5382 assert(!Val->use_empty() && "Input must have at least one use"); 5383 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin()); 5384 bool IsSExt = isa<SExtInst>(FirstUser); 5385 Type *ExtTy = FirstUser->getType(); 5386 for (const User *U : Val->users()) { 5387 const Instruction *UI = cast<Instruction>(U); 5388 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) 5389 return false; 5390 Type *CurTy = UI->getType(); 5391 // Same input and output types: Same instruction after CSE. 5392 if (CurTy == ExtTy) 5393 continue; 5394 5395 // If IsSExt is true, we are in this situation: 5396 // a = Val 5397 // b = sext ty1 a to ty2 5398 // c = sext ty1 a to ty3 5399 // Assuming ty2 is shorter than ty3, this could be turned into: 5400 // a = Val 5401 // b = sext ty1 a to ty2 5402 // c = sext ty2 b to ty3 5403 // However, the last sext is not free. 5404 if (IsSExt) 5405 return false; 5406 5407 // This is a ZExt, maybe this is free to extend from one type to another. 5408 // In that case, we would not account for a different use. 5409 Type *NarrowTy; 5410 Type *LargeTy; 5411 if (ExtTy->getScalarType()->getIntegerBitWidth() > 5412 CurTy->getScalarType()->getIntegerBitWidth()) { 5413 NarrowTy = CurTy; 5414 LargeTy = ExtTy; 5415 } else { 5416 NarrowTy = ExtTy; 5417 LargeTy = CurTy; 5418 } 5419 5420 if (!TLI.isZExtFree(NarrowTy, LargeTy)) 5421 return false; 5422 } 5423 // All uses are the same or can be derived from one another for free. 5424 return true; 5425 } 5426 5427 /// Try to speculatively promote extensions in \p Exts and continue 5428 /// promoting through newly promoted operands recursively as far as doing so is 5429 /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts. 5430 /// When some promotion happened, \p TPT contains the proper state to revert 5431 /// them. 5432 /// 5433 /// \return true if some promotion happened, false otherwise. 5434 bool CodeGenPrepare::tryToPromoteExts( 5435 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts, 5436 SmallVectorImpl<Instruction *> &ProfitablyMovedExts, 5437 unsigned CreatedInstsCost) { 5438 bool Promoted = false; 5439 5440 // Iterate over all the extensions to try to promote them. 5441 for (auto I : Exts) { 5442 // Early check if we directly have ext(load). 5443 if (isa<LoadInst>(I->getOperand(0))) { 5444 ProfitablyMovedExts.push_back(I); 5445 continue; 5446 } 5447 5448 // Check whether or not we want to do any promotion. The reason we have 5449 // this check inside the for loop is to catch the case where an extension 5450 // is directly fed by a load because in such case the extension can be moved 5451 // up without any promotion on its operands. 5452 if (!TLI->enableExtLdPromotion() || DisableExtLdPromotion) 5453 return false; 5454 5455 // Get the action to perform the promotion. 5456 TypePromotionHelper::Action TPH = 5457 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts); 5458 // Check if we can promote. 5459 if (!TPH) { 5460 // Save the current extension as we cannot move up through its operand. 5461 ProfitablyMovedExts.push_back(I); 5462 continue; 5463 } 5464 5465 // Save the current state. 5466 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 5467 TPT.getRestorationPoint(); 5468 SmallVector<Instruction *, 4> NewExts; 5469 unsigned NewCreatedInstsCost = 0; 5470 unsigned ExtCost = !TLI->isExtFree(I); 5471 // Promote. 5472 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, 5473 &NewExts, nullptr, *TLI); 5474 assert(PromotedVal && 5475 "TypePromotionHelper should have filtered out those cases"); 5476 5477 // We would be able to merge only one extension in a load. 5478 // Therefore, if we have more than 1 new extension we heuristically 5479 // cut this search path, because it means we degrade the code quality. 5480 // With exactly 2, the transformation is neutral, because we will merge 5481 // one extension but leave one. However, we optimistically keep going, 5482 // because the new extension may be removed too. 5483 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; 5484 // FIXME: It would be possible to propagate a negative value instead of 5485 // conservatively ceiling it to 0. 5486 TotalCreatedInstsCost = 5487 std::max((long long)0, (TotalCreatedInstsCost - ExtCost)); 5488 if (!StressExtLdPromotion && 5489 (TotalCreatedInstsCost > 1 || 5490 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { 5491 // This promotion is not profitable, rollback to the previous state, and 5492 // save the current extension in ProfitablyMovedExts as the latest 5493 // speculative promotion turned out to be unprofitable. 5494 TPT.rollback(LastKnownGood); 5495 ProfitablyMovedExts.push_back(I); 5496 continue; 5497 } 5498 // Continue promoting NewExts as far as doing so is profitable. 5499 SmallVector<Instruction *, 2> NewlyMovedExts; 5500 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost); 5501 bool NewPromoted = false; 5502 for (auto ExtInst : NewlyMovedExts) { 5503 Instruction *MovedExt = cast<Instruction>(ExtInst); 5504 Value *ExtOperand = MovedExt->getOperand(0); 5505 // If we have reached to a load, we need this extra profitability check 5506 // as it could potentially be merged into an ext(load). 5507 if (isa<LoadInst>(ExtOperand) && 5508 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || 5509 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI)))) 5510 continue; 5511 5512 ProfitablyMovedExts.push_back(MovedExt); 5513 NewPromoted = true; 5514 } 5515 5516 // If none of speculative promotions for NewExts is profitable, rollback 5517 // and save the current extension (I) as the last profitable extension. 5518 if (!NewPromoted) { 5519 TPT.rollback(LastKnownGood); 5520 ProfitablyMovedExts.push_back(I); 5521 continue; 5522 } 5523 // The promotion is profitable. 5524 Promoted = true; 5525 } 5526 return Promoted; 5527 } 5528 5529 /// Merging redundant sexts when one is dominating the other. 5530 bool CodeGenPrepare::mergeSExts(Function &F) { 5531 bool Changed = false; 5532 for (auto &Entry : ValToSExtendedUses) { 5533 SExts &Insts = Entry.second; 5534 SExts CurPts; 5535 for (Instruction *Inst : Insts) { 5536 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) || 5537 Inst->getOperand(0) != Entry.first) 5538 continue; 5539 bool inserted = false; 5540 for (auto &Pt : CurPts) { 5541 if (getDT(F).dominates(Inst, Pt)) { 5542 Pt->replaceAllUsesWith(Inst); 5543 RemovedInsts.insert(Pt); 5544 Pt->removeFromParent(); 5545 Pt = Inst; 5546 inserted = true; 5547 Changed = true; 5548 break; 5549 } 5550 if (!getDT(F).dominates(Pt, Inst)) 5551 // Give up if we need to merge in a common dominator as the 5552 // experiments show it is not profitable. 5553 continue; 5554 Inst->replaceAllUsesWith(Pt); 5555 RemovedInsts.insert(Inst); 5556 Inst->removeFromParent(); 5557 inserted = true; 5558 Changed = true; 5559 break; 5560 } 5561 if (!inserted) 5562 CurPts.push_back(Inst); 5563 } 5564 } 5565 return Changed; 5566 } 5567 5568 // Spliting large data structures so that the GEPs accessing them can have 5569 // smaller offsets so that they can be sunk to the same blocks as their users. 5570 // For example, a large struct starting from %base is splitted into two parts 5571 // where the second part starts from %new_base. 5572 // 5573 // Before: 5574 // BB0: 5575 // %base = 5576 // 5577 // BB1: 5578 // %gep0 = gep %base, off0 5579 // %gep1 = gep %base, off1 5580 // %gep2 = gep %base, off2 5581 // 5582 // BB2: 5583 // %load1 = load %gep0 5584 // %load2 = load %gep1 5585 // %load3 = load %gep2 5586 // 5587 // After: 5588 // BB0: 5589 // %base = 5590 // %new_base = gep %base, off0 5591 // 5592 // BB1: 5593 // %new_gep0 = %new_base 5594 // %new_gep1 = gep %new_base, off1 - off0 5595 // %new_gep2 = gep %new_base, off2 - off0 5596 // 5597 // BB2: 5598 // %load1 = load i32, i32* %new_gep0 5599 // %load2 = load i32, i32* %new_gep1 5600 // %load3 = load i32, i32* %new_gep2 5601 // 5602 // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because 5603 // their offsets are smaller enough to fit into the addressing mode. 5604 bool CodeGenPrepare::splitLargeGEPOffsets() { 5605 bool Changed = false; 5606 for (auto &Entry : LargeOffsetGEPMap) { 5607 Value *OldBase = Entry.first; 5608 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>> 5609 &LargeOffsetGEPs = Entry.second; 5610 auto compareGEPOffset = 5611 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS, 5612 const std::pair<GetElementPtrInst *, int64_t> &RHS) { 5613 if (LHS.first == RHS.first) 5614 return false; 5615 if (LHS.second != RHS.second) 5616 return LHS.second < RHS.second; 5617 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first]; 5618 }; 5619 // Sorting all the GEPs of the same data structures based on the offsets. 5620 llvm::sort(LargeOffsetGEPs, compareGEPOffset); 5621 LargeOffsetGEPs.erase( 5622 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()), 5623 LargeOffsetGEPs.end()); 5624 // Skip if all the GEPs have the same offsets. 5625 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second) 5626 continue; 5627 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first; 5628 int64_t BaseOffset = LargeOffsetGEPs.begin()->second; 5629 Value *NewBaseGEP = nullptr; 5630 5631 auto LargeOffsetGEP = LargeOffsetGEPs.begin(); 5632 while (LargeOffsetGEP != LargeOffsetGEPs.end()) { 5633 GetElementPtrInst *GEP = LargeOffsetGEP->first; 5634 int64_t Offset = LargeOffsetGEP->second; 5635 if (Offset != BaseOffset) { 5636 TargetLowering::AddrMode AddrMode; 5637 AddrMode.BaseOffs = Offset - BaseOffset; 5638 // The result type of the GEP might not be the type of the memory 5639 // access. 5640 if (!TLI->isLegalAddressingMode(*DL, AddrMode, 5641 GEP->getResultElementType(), 5642 GEP->getAddressSpace())) { 5643 // We need to create a new base if the offset to the current base is 5644 // too large to fit into the addressing mode. So, a very large struct 5645 // may be splitted into several parts. 5646 BaseGEP = GEP; 5647 BaseOffset = Offset; 5648 NewBaseGEP = nullptr; 5649 } 5650 } 5651 5652 // Generate a new GEP to replace the current one. 5653 LLVMContext &Ctx = GEP->getContext(); 5654 Type *IntPtrTy = DL->getIntPtrType(GEP->getType()); 5655 Type *I8PtrTy = 5656 Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace()); 5657 Type *I8Ty = Type::getInt8Ty(Ctx); 5658 5659 if (!NewBaseGEP) { 5660 // Create a new base if we don't have one yet. Find the insertion 5661 // pointer for the new base first. 5662 BasicBlock::iterator NewBaseInsertPt; 5663 BasicBlock *NewBaseInsertBB; 5664 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) { 5665 // If the base of the struct is an instruction, the new base will be 5666 // inserted close to it. 5667 NewBaseInsertBB = BaseI->getParent(); 5668 if (isa<PHINode>(BaseI)) 5669 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); 5670 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) { 5671 NewBaseInsertBB = 5672 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest()); 5673 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); 5674 } else 5675 NewBaseInsertPt = std::next(BaseI->getIterator()); 5676 } else { 5677 // If the current base is an argument or global value, the new base 5678 // will be inserted to the entry block. 5679 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock(); 5680 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); 5681 } 5682 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt); 5683 // Create a new base. 5684 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset); 5685 NewBaseGEP = OldBase; 5686 if (NewBaseGEP->getType() != I8PtrTy) 5687 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy); 5688 NewBaseGEP = 5689 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep"); 5690 NewGEPBases.insert(NewBaseGEP); 5691 } 5692 5693 IRBuilder<> Builder(GEP); 5694 Value *NewGEP = NewBaseGEP; 5695 if (Offset == BaseOffset) { 5696 if (GEP->getType() != I8PtrTy) 5697 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); 5698 } else { 5699 // Calculate the new offset for the new GEP. 5700 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset); 5701 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index); 5702 5703 if (GEP->getType() != I8PtrTy) 5704 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); 5705 } 5706 GEP->replaceAllUsesWith(NewGEP); 5707 LargeOffsetGEPID.erase(GEP); 5708 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP); 5709 GEP->eraseFromParent(); 5710 Changed = true; 5711 } 5712 } 5713 return Changed; 5714 } 5715 5716 /// Return true, if an ext(load) can be formed from an extension in 5717 /// \p MovedExts. 5718 bool CodeGenPrepare::canFormExtLd( 5719 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI, 5720 Instruction *&Inst, bool HasPromoted) { 5721 for (auto *MovedExtInst : MovedExts) { 5722 if (isa<LoadInst>(MovedExtInst->getOperand(0))) { 5723 LI = cast<LoadInst>(MovedExtInst->getOperand(0)); 5724 Inst = MovedExtInst; 5725 break; 5726 } 5727 } 5728 if (!LI) 5729 return false; 5730 5731 // If they're already in the same block, there's nothing to do. 5732 // Make the cheap checks first if we did not promote. 5733 // If we promoted, we need to check if it is indeed profitable. 5734 if (!HasPromoted && LI->getParent() == Inst->getParent()) 5735 return false; 5736 5737 return TLI->isExtLoad(LI, Inst, *DL); 5738 } 5739 5740 /// Move a zext or sext fed by a load into the same basic block as the load, 5741 /// unless conditions are unfavorable. This allows SelectionDAG to fold the 5742 /// extend into the load. 5743 /// 5744 /// E.g., 5745 /// \code 5746 /// %ld = load i32* %addr 5747 /// %add = add nuw i32 %ld, 4 5748 /// %zext = zext i32 %add to i64 5749 // \endcode 5750 /// => 5751 /// \code 5752 /// %ld = load i32* %addr 5753 /// %zext = zext i32 %ld to i64 5754 /// %add = add nuw i64 %zext, 4 5755 /// \encode 5756 /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which 5757 /// allow us to match zext(load i32*) to i64. 5758 /// 5759 /// Also, try to promote the computations used to obtain a sign extended 5760 /// value used into memory accesses. 5761 /// E.g., 5762 /// \code 5763 /// a = add nsw i32 b, 3 5764 /// d = sext i32 a to i64 5765 /// e = getelementptr ..., i64 d 5766 /// \endcode 5767 /// => 5768 /// \code 5769 /// f = sext i32 b to i64 5770 /// a = add nsw i64 f, 3 5771 /// e = getelementptr ..., i64 a 5772 /// \endcode 5773 /// 5774 /// \p Inst[in/out] the extension may be modified during the process if some 5775 /// promotions apply. 5776 bool CodeGenPrepare::optimizeExt(Instruction *&Inst) { 5777 bool AllowPromotionWithoutCommonHeader = false; 5778 /// See if it is an interesting sext operations for the address type 5779 /// promotion before trying to promote it, e.g., the ones with the right 5780 /// type and used in memory accesses. 5781 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion( 5782 *Inst, AllowPromotionWithoutCommonHeader); 5783 TypePromotionTransaction TPT(RemovedInsts); 5784 TypePromotionTransaction::ConstRestorationPt LastKnownGood = 5785 TPT.getRestorationPoint(); 5786 SmallVector<Instruction *, 1> Exts; 5787 SmallVector<Instruction *, 2> SpeculativelyMovedExts; 5788 Exts.push_back(Inst); 5789 5790 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts); 5791 5792 // Look for a load being extended. 5793 LoadInst *LI = nullptr; 5794 Instruction *ExtFedByLoad; 5795 5796 // Try to promote a chain of computation if it allows to form an extended 5797 // load. 5798 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) { 5799 assert(LI && ExtFedByLoad && "Expect a valid load and extension"); 5800 TPT.commit(); 5801 // Move the extend into the same block as the load 5802 ExtFedByLoad->moveAfter(LI); 5803 // CGP does not check if the zext would be speculatively executed when moved 5804 // to the same basic block as the load. Preserving its original location 5805 // would pessimize the debugging experience, as well as negatively impact 5806 // the quality of sample pgo. We don't want to use "line 0" as that has a 5807 // size cost in the line-table section and logically the zext can be seen as 5808 // part of the load. Therefore we conservatively reuse the same debug 5809 // location for the load and the zext. 5810 ExtFedByLoad->setDebugLoc(LI->getDebugLoc()); 5811 ++NumExtsMoved; 5812 Inst = ExtFedByLoad; 5813 return true; 5814 } 5815 5816 // Continue promoting SExts if known as considerable depending on targets. 5817 if (ATPConsiderable && 5818 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader, 5819 HasPromoted, TPT, SpeculativelyMovedExts)) 5820 return true; 5821 5822 TPT.rollback(LastKnownGood); 5823 return false; 5824 } 5825 5826 // Perform address type promotion if doing so is profitable. 5827 // If AllowPromotionWithoutCommonHeader == false, we should find other sext 5828 // instructions that sign extended the same initial value. However, if 5829 // AllowPromotionWithoutCommonHeader == true, we expect promoting the 5830 // extension is just profitable. 5831 bool CodeGenPrepare::performAddressTypePromotion( 5832 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader, 5833 bool HasPromoted, TypePromotionTransaction &TPT, 5834 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) { 5835 bool Promoted = false; 5836 SmallPtrSet<Instruction *, 1> UnhandledExts; 5837 bool AllSeenFirst = true; 5838 for (auto I : SpeculativelyMovedExts) { 5839 Value *HeadOfChain = I->getOperand(0); 5840 DenseMap<Value *, Instruction *>::iterator AlreadySeen = 5841 SeenChainsForSExt.find(HeadOfChain); 5842 // If there is an unhandled SExt which has the same header, try to promote 5843 // it as well. 5844 if (AlreadySeen != SeenChainsForSExt.end()) { 5845 if (AlreadySeen->second != nullptr) 5846 UnhandledExts.insert(AlreadySeen->second); 5847 AllSeenFirst = false; 5848 } 5849 } 5850 5851 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader && 5852 SpeculativelyMovedExts.size() == 1)) { 5853 TPT.commit(); 5854 if (HasPromoted) 5855 Promoted = true; 5856 for (auto I : SpeculativelyMovedExts) { 5857 Value *HeadOfChain = I->getOperand(0); 5858 SeenChainsForSExt[HeadOfChain] = nullptr; 5859 ValToSExtendedUses[HeadOfChain].push_back(I); 5860 } 5861 // Update Inst as promotion happen. 5862 Inst = SpeculativelyMovedExts.pop_back_val(); 5863 } else { 5864 // This is the first chain visited from the header, keep the current chain 5865 // as unhandled. Defer to promote this until we encounter another SExt 5866 // chain derived from the same header. 5867 for (auto I : SpeculativelyMovedExts) { 5868 Value *HeadOfChain = I->getOperand(0); 5869 SeenChainsForSExt[HeadOfChain] = Inst; 5870 } 5871 return false; 5872 } 5873 5874 if (!AllSeenFirst && !UnhandledExts.empty()) 5875 for (auto VisitedSExt : UnhandledExts) { 5876 if (RemovedInsts.count(VisitedSExt)) 5877 continue; 5878 TypePromotionTransaction TPT(RemovedInsts); 5879 SmallVector<Instruction *, 1> Exts; 5880 SmallVector<Instruction *, 2> Chains; 5881 Exts.push_back(VisitedSExt); 5882 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains); 5883 TPT.commit(); 5884 if (HasPromoted) 5885 Promoted = true; 5886 for (auto I : Chains) { 5887 Value *HeadOfChain = I->getOperand(0); 5888 // Mark this as handled. 5889 SeenChainsForSExt[HeadOfChain] = nullptr; 5890 ValToSExtendedUses[HeadOfChain].push_back(I); 5891 } 5892 } 5893 return Promoted; 5894 } 5895 5896 bool CodeGenPrepare::optimizeExtUses(Instruction *I) { 5897 BasicBlock *DefBB = I->getParent(); 5898 5899 // If the result of a {s|z}ext and its source are both live out, rewrite all 5900 // other uses of the source with result of extension. 5901 Value *Src = I->getOperand(0); 5902 if (Src->hasOneUse()) 5903 return false; 5904 5905 // Only do this xform if truncating is free. 5906 if (!TLI->isTruncateFree(I->getType(), Src->getType())) 5907 return false; 5908 5909 // Only safe to perform the optimization if the source is also defined in 5910 // this block. 5911 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) 5912 return false; 5913 5914 bool DefIsLiveOut = false; 5915 for (User *U : I->users()) { 5916 Instruction *UI = cast<Instruction>(U); 5917 5918 // Figure out which BB this ext is used in. 5919 BasicBlock *UserBB = UI->getParent(); 5920 if (UserBB == DefBB) continue; 5921 DefIsLiveOut = true; 5922 break; 5923 } 5924 if (!DefIsLiveOut) 5925 return false; 5926 5927 // Make sure none of the uses are PHI nodes. 5928 for (User *U : Src->users()) { 5929 Instruction *UI = cast<Instruction>(U); 5930 BasicBlock *UserBB = UI->getParent(); 5931 if (UserBB == DefBB) continue; 5932 // Be conservative. We don't want this xform to end up introducing 5933 // reloads just before load / store instructions. 5934 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) 5935 return false; 5936 } 5937 5938 // InsertedTruncs - Only insert one trunc in each block once. 5939 DenseMap<BasicBlock*, Instruction*> InsertedTruncs; 5940 5941 bool MadeChange = false; 5942 for (Use &U : Src->uses()) { 5943 Instruction *User = cast<Instruction>(U.getUser()); 5944 5945 // Figure out which BB this ext is used in. 5946 BasicBlock *UserBB = User->getParent(); 5947 if (UserBB == DefBB) continue; 5948 5949 // Both src and def are live in this block. Rewrite the use. 5950 Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; 5951 5952 if (!InsertedTrunc) { 5953 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); 5954 assert(InsertPt != UserBB->end()); 5955 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); 5956 InsertedInsts.insert(InsertedTrunc); 5957 } 5958 5959 // Replace a use of the {s|z}ext source with a use of the result. 5960 U = InsertedTrunc; 5961 ++NumExtUses; 5962 MadeChange = true; 5963 } 5964 5965 return MadeChange; 5966 } 5967 5968 // Find loads whose uses only use some of the loaded value's bits. Add an "and" 5969 // just after the load if the target can fold this into one extload instruction, 5970 // with the hope of eliminating some of the other later "and" instructions using 5971 // the loaded value. "and"s that are made trivially redundant by the insertion 5972 // of the new "and" are removed by this function, while others (e.g. those whose 5973 // path from the load goes through a phi) are left for isel to potentially 5974 // remove. 5975 // 5976 // For example: 5977 // 5978 // b0: 5979 // x = load i32 5980 // ... 5981 // b1: 5982 // y = and x, 0xff 5983 // z = use y 5984 // 5985 // becomes: 5986 // 5987 // b0: 5988 // x = load i32 5989 // x' = and x, 0xff 5990 // ... 5991 // b1: 5992 // z = use x' 5993 // 5994 // whereas: 5995 // 5996 // b0: 5997 // x1 = load i32 5998 // ... 5999 // b1: 6000 // x2 = load i32 6001 // ... 6002 // b2: 6003 // x = phi x1, x2 6004 // y = and x, 0xff 6005 // 6006 // becomes (after a call to optimizeLoadExt for each load): 6007 // 6008 // b0: 6009 // x1 = load i32 6010 // x1' = and x1, 0xff 6011 // ... 6012 // b1: 6013 // x2 = load i32 6014 // x2' = and x2, 0xff 6015 // ... 6016 // b2: 6017 // x = phi x1', x2' 6018 // y = and x, 0xff 6019 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { 6020 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy()) 6021 return false; 6022 6023 // Skip loads we've already transformed. 6024 if (Load->hasOneUse() && 6025 InsertedInsts.count(cast<Instruction>(*Load->user_begin()))) 6026 return false; 6027 6028 // Look at all uses of Load, looking through phis, to determine how many bits 6029 // of the loaded value are needed. 6030 SmallVector<Instruction *, 8> WorkList; 6031 SmallPtrSet<Instruction *, 16> Visited; 6032 SmallVector<Instruction *, 8> AndsToMaybeRemove; 6033 for (auto *U : Load->users()) 6034 WorkList.push_back(cast<Instruction>(U)); 6035 6036 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); 6037 unsigned BitWidth = LoadResultVT.getSizeInBits(); 6038 APInt DemandBits(BitWidth, 0); 6039 APInt WidestAndBits(BitWidth, 0); 6040 6041 while (!WorkList.empty()) { 6042 Instruction *I = WorkList.back(); 6043 WorkList.pop_back(); 6044 6045 // Break use-def graph loops. 6046 if (!Visited.insert(I).second) 6047 continue; 6048 6049 // For a PHI node, push all of its users. 6050 if (auto *Phi = dyn_cast<PHINode>(I)) { 6051 for (auto *U : Phi->users()) 6052 WorkList.push_back(cast<Instruction>(U)); 6053 continue; 6054 } 6055 6056 switch (I->getOpcode()) { 6057 case Instruction::And: { 6058 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); 6059 if (!AndC) 6060 return false; 6061 APInt AndBits = AndC->getValue(); 6062 DemandBits |= AndBits; 6063 // Keep track of the widest and mask we see. 6064 if (AndBits.ugt(WidestAndBits)) 6065 WidestAndBits = AndBits; 6066 if (AndBits == WidestAndBits && I->getOperand(0) == Load) 6067 AndsToMaybeRemove.push_back(I); 6068 break; 6069 } 6070 6071 case Instruction::Shl: { 6072 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); 6073 if (!ShlC) 6074 return false; 6075 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); 6076 DemandBits.setLowBits(BitWidth - ShiftAmt); 6077 break; 6078 } 6079 6080 case Instruction::Trunc: { 6081 EVT TruncVT = TLI->getValueType(*DL, I->getType()); 6082 unsigned TruncBitWidth = TruncVT.getSizeInBits(); 6083 DemandBits.setLowBits(TruncBitWidth); 6084 break; 6085 } 6086 6087 default: 6088 return false; 6089 } 6090 } 6091 6092 uint32_t ActiveBits = DemandBits.getActiveBits(); 6093 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the 6094 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, 6095 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but 6096 // (and (load x) 1) is not matched as a single instruction, rather as a LDR 6097 // followed by an AND. 6098 // TODO: Look into removing this restriction by fixing backends to either 6099 // return false for isLoadExtLegal for i1 or have them select this pattern to 6100 // a single instruction. 6101 // 6102 // Also avoid hoisting if we didn't see any ands with the exact DemandBits 6103 // mask, since these are the only ands that will be removed by isel. 6104 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) || 6105 WidestAndBits != DemandBits) 6106 return false; 6107 6108 LLVMContext &Ctx = Load->getType()->getContext(); 6109 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); 6110 EVT TruncVT = TLI->getValueType(*DL, TruncTy); 6111 6112 // Reject cases that won't be matched as extloads. 6113 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || 6114 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) 6115 return false; 6116 6117 IRBuilder<> Builder(Load->getNextNode()); 6118 auto *NewAnd = cast<Instruction>( 6119 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); 6120 // Mark this instruction as "inserted by CGP", so that other 6121 // optimizations don't touch it. 6122 InsertedInsts.insert(NewAnd); 6123 6124 // Replace all uses of load with new and (except for the use of load in the 6125 // new and itself). 6126 Load->replaceAllUsesWith(NewAnd); 6127 NewAnd->setOperand(0, Load); 6128 6129 // Remove any and instructions that are now redundant. 6130 for (auto *And : AndsToMaybeRemove) 6131 // Check that the and mask is the same as the one we decided to put on the 6132 // new and. 6133 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { 6134 And->replaceAllUsesWith(NewAnd); 6135 if (&*CurInstIterator == And) 6136 CurInstIterator = std::next(And->getIterator()); 6137 And->eraseFromParent(); 6138 ++NumAndUses; 6139 } 6140 6141 ++NumAndsAdded; 6142 return true; 6143 } 6144 6145 /// Check if V (an operand of a select instruction) is an expensive instruction 6146 /// that is only used once. 6147 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { 6148 auto *I = dyn_cast<Instruction>(V); 6149 // If it's safe to speculatively execute, then it should not have side 6150 // effects; therefore, it's safe to sink and possibly *not* execute. 6151 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && 6152 TTI->getUserCost(I, TargetTransformInfo::TCK_SizeAndLatency) >= 6153 TargetTransformInfo::TCC_Expensive; 6154 } 6155 6156 /// Returns true if a SelectInst should be turned into an explicit branch. 6157 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, 6158 const TargetLowering *TLI, 6159 SelectInst *SI) { 6160 // If even a predictable select is cheap, then a branch can't be cheaper. 6161 if (!TLI->isPredictableSelectExpensive()) 6162 return false; 6163 6164 // FIXME: This should use the same heuristics as IfConversion to determine 6165 // whether a select is better represented as a branch. 6166 6167 // If metadata tells us that the select condition is obviously predictable, 6168 // then we want to replace the select with a branch. 6169 uint64_t TrueWeight, FalseWeight; 6170 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { 6171 uint64_t Max = std::max(TrueWeight, FalseWeight); 6172 uint64_t Sum = TrueWeight + FalseWeight; 6173 if (Sum != 0) { 6174 auto Probability = BranchProbability::getBranchProbability(Max, Sum); 6175 if (Probability > TLI->getPredictableBranchThreshold()) 6176 return true; 6177 } 6178 } 6179 6180 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); 6181 6182 // If a branch is predictable, an out-of-order CPU can avoid blocking on its 6183 // comparison condition. If the compare has more than one use, there's 6184 // probably another cmov or setcc around, so it's not worth emitting a branch. 6185 if (!Cmp || !Cmp->hasOneUse()) 6186 return false; 6187 6188 // If either operand of the select is expensive and only needed on one side 6189 // of the select, we should form a branch. 6190 if (sinkSelectOperand(TTI, SI->getTrueValue()) || 6191 sinkSelectOperand(TTI, SI->getFalseValue())) 6192 return true; 6193 6194 return false; 6195 } 6196 6197 /// If \p isTrue is true, return the true value of \p SI, otherwise return 6198 /// false value of \p SI. If the true/false value of \p SI is defined by any 6199 /// select instructions in \p Selects, look through the defining select 6200 /// instruction until the true/false value is not defined in \p Selects. 6201 static Value *getTrueOrFalseValue( 6202 SelectInst *SI, bool isTrue, 6203 const SmallPtrSet<const Instruction *, 2> &Selects) { 6204 Value *V = nullptr; 6205 6206 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); 6207 DefSI = dyn_cast<SelectInst>(V)) { 6208 assert(DefSI->getCondition() == SI->getCondition() && 6209 "The condition of DefSI does not match with SI"); 6210 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); 6211 } 6212 6213 assert(V && "Failed to get select true/false value"); 6214 return V; 6215 } 6216 6217 bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) { 6218 assert(Shift->isShift() && "Expected a shift"); 6219 6220 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than 6221 // general vector shifts, and (3) the shift amount is a select-of-splatted 6222 // values, hoist the shifts before the select: 6223 // shift Op0, (select Cond, TVal, FVal) --> 6224 // select Cond, (shift Op0, TVal), (shift Op0, FVal) 6225 // 6226 // This is inverting a generic IR transform when we know that the cost of a 6227 // general vector shift is more than the cost of 2 shift-by-scalars. 6228 // We can't do this effectively in SDAG because we may not be able to 6229 // determine if the select operands are splats from within a basic block. 6230 Type *Ty = Shift->getType(); 6231 if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty)) 6232 return false; 6233 Value *Cond, *TVal, *FVal; 6234 if (!match(Shift->getOperand(1), 6235 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) 6236 return false; 6237 if (!isSplatValue(TVal) || !isSplatValue(FVal)) 6238 return false; 6239 6240 IRBuilder<> Builder(Shift); 6241 BinaryOperator::BinaryOps Opcode = Shift->getOpcode(); 6242 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal); 6243 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal); 6244 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal); 6245 Shift->replaceAllUsesWith(NewSel); 6246 Shift->eraseFromParent(); 6247 return true; 6248 } 6249 6250 bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) { 6251 Intrinsic::ID Opcode = Fsh->getIntrinsicID(); 6252 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) && 6253 "Expected a funnel shift"); 6254 6255 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper 6256 // than general vector shifts, and (3) the shift amount is select-of-splatted 6257 // values, hoist the funnel shifts before the select: 6258 // fsh Op0, Op1, (select Cond, TVal, FVal) --> 6259 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal) 6260 // 6261 // This is inverting a generic IR transform when we know that the cost of a 6262 // general vector shift is more than the cost of 2 shift-by-scalars. 6263 // We can't do this effectively in SDAG because we may not be able to 6264 // determine if the select operands are splats from within a basic block. 6265 Type *Ty = Fsh->getType(); 6266 if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty)) 6267 return false; 6268 Value *Cond, *TVal, *FVal; 6269 if (!match(Fsh->getOperand(2), 6270 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) 6271 return false; 6272 if (!isSplatValue(TVal) || !isSplatValue(FVal)) 6273 return false; 6274 6275 IRBuilder<> Builder(Fsh); 6276 Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1); 6277 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, TVal }); 6278 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, { X, Y, FVal }); 6279 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal); 6280 Fsh->replaceAllUsesWith(NewSel); 6281 Fsh->eraseFromParent(); 6282 return true; 6283 } 6284 6285 /// If we have a SelectInst that will likely profit from branch prediction, 6286 /// turn it into a branch. 6287 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { 6288 // If branch conversion isn't desirable, exit early. 6289 if (DisableSelectToBranch || OptSize || 6290 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI.get())) 6291 return false; 6292 6293 // Find all consecutive select instructions that share the same condition. 6294 SmallVector<SelectInst *, 2> ASI; 6295 ASI.push_back(SI); 6296 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); 6297 It != SI->getParent()->end(); ++It) { 6298 SelectInst *I = dyn_cast<SelectInst>(&*It); 6299 if (I && SI->getCondition() == I->getCondition()) { 6300 ASI.push_back(I); 6301 } else { 6302 break; 6303 } 6304 } 6305 6306 SelectInst *LastSI = ASI.back(); 6307 // Increment the current iterator to skip all the rest of select instructions 6308 // because they will be either "not lowered" or "all lowered" to branch. 6309 CurInstIterator = std::next(LastSI->getIterator()); 6310 6311 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); 6312 6313 // Can we convert the 'select' to CF ? 6314 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable)) 6315 return false; 6316 6317 TargetLowering::SelectSupportKind SelectKind; 6318 if (VectorCond) 6319 SelectKind = TargetLowering::VectorMaskSelect; 6320 else if (SI->getType()->isVectorTy()) 6321 SelectKind = TargetLowering::ScalarCondVectorVal; 6322 else 6323 SelectKind = TargetLowering::ScalarValSelect; 6324 6325 if (TLI->isSelectSupported(SelectKind) && 6326 !isFormingBranchFromSelectProfitable(TTI, TLI, SI)) 6327 return false; 6328 6329 // The DominatorTree needs to be rebuilt by any consumers after this 6330 // transformation. We simply reset here rather than setting the ModifiedDT 6331 // flag to avoid restarting the function walk in runOnFunction for each 6332 // select optimized. 6333 DT.reset(); 6334 6335 // Transform a sequence like this: 6336 // start: 6337 // %cmp = cmp uge i32 %a, %b 6338 // %sel = select i1 %cmp, i32 %c, i32 %d 6339 // 6340 // Into: 6341 // start: 6342 // %cmp = cmp uge i32 %a, %b 6343 // %cmp.frozen = freeze %cmp 6344 // br i1 %cmp.frozen, label %select.true, label %select.false 6345 // select.true: 6346 // br label %select.end 6347 // select.false: 6348 // br label %select.end 6349 // select.end: 6350 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] 6351 // 6352 // %cmp should be frozen, otherwise it may introduce undefined behavior. 6353 // In addition, we may sink instructions that produce %c or %d from 6354 // the entry block into the destination(s) of the new branch. 6355 // If the true or false blocks do not contain a sunken instruction, that 6356 // block and its branch may be optimized away. In that case, one side of the 6357 // first branch will point directly to select.end, and the corresponding PHI 6358 // predecessor block will be the start block. 6359 6360 // First, we split the block containing the select into 2 blocks. 6361 BasicBlock *StartBlock = SI->getParent(); 6362 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); 6363 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); 6364 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock).getFrequency()); 6365 6366 // Delete the unconditional branch that was just created by the split. 6367 StartBlock->getTerminator()->eraseFromParent(); 6368 6369 // These are the new basic blocks for the conditional branch. 6370 // At least one will become an actual new basic block. 6371 BasicBlock *TrueBlock = nullptr; 6372 BasicBlock *FalseBlock = nullptr; 6373 BranchInst *TrueBranch = nullptr; 6374 BranchInst *FalseBranch = nullptr; 6375 6376 // Sink expensive instructions into the conditional blocks to avoid executing 6377 // them speculatively. 6378 for (SelectInst *SI : ASI) { 6379 if (sinkSelectOperand(TTI, SI->getTrueValue())) { 6380 if (TrueBlock == nullptr) { 6381 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", 6382 EndBlock->getParent(), EndBlock); 6383 TrueBranch = BranchInst::Create(EndBlock, TrueBlock); 6384 TrueBranch->setDebugLoc(SI->getDebugLoc()); 6385 } 6386 auto *TrueInst = cast<Instruction>(SI->getTrueValue()); 6387 TrueInst->moveBefore(TrueBranch); 6388 } 6389 if (sinkSelectOperand(TTI, SI->getFalseValue())) { 6390 if (FalseBlock == nullptr) { 6391 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", 6392 EndBlock->getParent(), EndBlock); 6393 FalseBranch = BranchInst::Create(EndBlock, FalseBlock); 6394 FalseBranch->setDebugLoc(SI->getDebugLoc()); 6395 } 6396 auto *FalseInst = cast<Instruction>(SI->getFalseValue()); 6397 FalseInst->moveBefore(FalseBranch); 6398 } 6399 } 6400 6401 // If there was nothing to sink, then arbitrarily choose the 'false' side 6402 // for a new input value to the PHI. 6403 if (TrueBlock == FalseBlock) { 6404 assert(TrueBlock == nullptr && 6405 "Unexpected basic block transform while optimizing select"); 6406 6407 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", 6408 EndBlock->getParent(), EndBlock); 6409 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock); 6410 FalseBranch->setDebugLoc(SI->getDebugLoc()); 6411 } 6412 6413 // Insert the real conditional branch based on the original condition. 6414 // If we did not create a new block for one of the 'true' or 'false' paths 6415 // of the condition, it means that side of the branch goes to the end block 6416 // directly and the path originates from the start block from the point of 6417 // view of the new PHI. 6418 BasicBlock *TT, *FT; 6419 if (TrueBlock == nullptr) { 6420 TT = EndBlock; 6421 FT = FalseBlock; 6422 TrueBlock = StartBlock; 6423 } else if (FalseBlock == nullptr) { 6424 TT = TrueBlock; 6425 FT = EndBlock; 6426 FalseBlock = StartBlock; 6427 } else { 6428 TT = TrueBlock; 6429 FT = FalseBlock; 6430 } 6431 IRBuilder<> IB(SI); 6432 auto CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen"); 6433 IB.CreateCondBr(CondFr, TT, FT, SI); 6434 6435 SmallPtrSet<const Instruction *, 2> INS; 6436 INS.insert(ASI.begin(), ASI.end()); 6437 // Use reverse iterator because later select may use the value of the 6438 // earlier select, and we need to propagate value through earlier select 6439 // to get the PHI operand. 6440 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { 6441 SelectInst *SI = *It; 6442 // The select itself is replaced with a PHI Node. 6443 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); 6444 PN->takeName(SI); 6445 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); 6446 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); 6447 PN->setDebugLoc(SI->getDebugLoc()); 6448 6449 SI->replaceAllUsesWith(PN); 6450 SI->eraseFromParent(); 6451 INS.erase(SI); 6452 ++NumSelectsExpanded; 6453 } 6454 6455 // Instruct OptimizeBlock to skip to the next block. 6456 CurInstIterator = StartBlock->end(); 6457 return true; 6458 } 6459 6460 /// Some targets only accept certain types for splat inputs. For example a VDUP 6461 /// in MVE takes a GPR (integer) register, and the instruction that incorporate 6462 /// a VDUP (such as a VADD qd, qm, rm) also require a gpr register. 6463 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { 6464 if (!match(SVI, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 6465 m_Undef(), m_ZeroMask()))) 6466 return false; 6467 Type *NewType = TLI->shouldConvertSplatType(SVI); 6468 if (!NewType) 6469 return false; 6470 6471 VectorType *SVIVecType = cast<VectorType>(SVI->getType()); 6472 assert(!NewType->isVectorTy() && "Expected a scalar type!"); 6473 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() && 6474 "Expected a type of the same size!"); 6475 Type *NewVecType = VectorType::get(NewType, SVIVecType->getNumElements()); 6476 6477 // Create a bitcast (shuffle (insert (bitcast(..)))) 6478 IRBuilder<> Builder(SVI->getContext()); 6479 Builder.SetInsertPoint(SVI); 6480 Value *BC1 = Builder.CreateBitCast( 6481 cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType); 6482 Value *Insert = Builder.CreateInsertElement(UndefValue::get(NewVecType), BC1, 6483 (uint64_t)0); 6484 Value *Shuffle = Builder.CreateShuffleVector( 6485 Insert, UndefValue::get(NewVecType), SVI->getShuffleMask()); 6486 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType); 6487 6488 SVI->replaceAllUsesWith(BC2); 6489 RecursivelyDeleteTriviallyDeadInstructions(SVI); 6490 6491 // Also hoist the bitcast up to its operand if it they are not in the same 6492 // block. 6493 if (auto *BCI = dyn_cast<Instruction>(BC1)) 6494 if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0))) 6495 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) && 6496 !Op->isTerminator() && !Op->isEHPad()) 6497 BCI->moveAfter(Op); 6498 6499 return true; 6500 } 6501 6502 bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) { 6503 // If the operands of I can be folded into a target instruction together with 6504 // I, duplicate and sink them. 6505 SmallVector<Use *, 4> OpsToSink; 6506 if (!TLI->shouldSinkOperands(I, OpsToSink)) 6507 return false; 6508 6509 // OpsToSink can contain multiple uses in a use chain (e.g. 6510 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating 6511 // uses must come first, so we process the ops in reverse order so as to not 6512 // create invalid IR. 6513 BasicBlock *TargetBB = I->getParent(); 6514 bool Changed = false; 6515 SmallVector<Use *, 4> ToReplace; 6516 for (Use *U : reverse(OpsToSink)) { 6517 auto *UI = cast<Instruction>(U->get()); 6518 if (UI->getParent() == TargetBB || isa<PHINode>(UI)) 6519 continue; 6520 ToReplace.push_back(U); 6521 } 6522 6523 SetVector<Instruction *> MaybeDead; 6524 DenseMap<Instruction *, Instruction *> NewInstructions; 6525 Instruction *InsertPoint = I; 6526 for (Use *U : ToReplace) { 6527 auto *UI = cast<Instruction>(U->get()); 6528 Instruction *NI = UI->clone(); 6529 NewInstructions[UI] = NI; 6530 MaybeDead.insert(UI); 6531 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n"); 6532 NI->insertBefore(InsertPoint); 6533 InsertPoint = NI; 6534 InsertedInsts.insert(NI); 6535 6536 // Update the use for the new instruction, making sure that we update the 6537 // sunk instruction uses, if it is part of a chain that has already been 6538 // sunk. 6539 Instruction *OldI = cast<Instruction>(U->getUser()); 6540 if (NewInstructions.count(OldI)) 6541 NewInstructions[OldI]->setOperand(U->getOperandNo(), NI); 6542 else 6543 U->set(NI); 6544 Changed = true; 6545 } 6546 6547 // Remove instructions that are dead after sinking. 6548 for (auto *I : MaybeDead) { 6549 if (!I->hasNUsesOrMore(1)) { 6550 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n"); 6551 I->eraseFromParent(); 6552 } 6553 } 6554 6555 return Changed; 6556 } 6557 6558 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { 6559 Value *Cond = SI->getCondition(); 6560 Type *OldType = Cond->getType(); 6561 LLVMContext &Context = Cond->getContext(); 6562 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); 6563 unsigned RegWidth = RegType.getSizeInBits(); 6564 6565 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) 6566 return false; 6567 6568 // If the register width is greater than the type width, expand the condition 6569 // of the switch instruction and each case constant to the width of the 6570 // register. By widening the type of the switch condition, subsequent 6571 // comparisons (for case comparisons) will not need to be extended to the 6572 // preferred register width, so we will potentially eliminate N-1 extends, 6573 // where N is the number of cases in the switch. 6574 auto *NewType = Type::getIntNTy(Context, RegWidth); 6575 6576 // Zero-extend the switch condition and case constants unless the switch 6577 // condition is a function argument that is already being sign-extended. 6578 // In that case, we can avoid an unnecessary mask/extension by sign-extending 6579 // everything instead. 6580 Instruction::CastOps ExtType = Instruction::ZExt; 6581 if (auto *Arg = dyn_cast<Argument>(Cond)) 6582 if (Arg->hasSExtAttr()) 6583 ExtType = Instruction::SExt; 6584 6585 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); 6586 ExtInst->insertBefore(SI); 6587 ExtInst->setDebugLoc(SI->getDebugLoc()); 6588 SI->setCondition(ExtInst); 6589 for (auto Case : SI->cases()) { 6590 APInt NarrowConst = Case.getCaseValue()->getValue(); 6591 APInt WideConst = (ExtType == Instruction::ZExt) ? 6592 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); 6593 Case.setValue(ConstantInt::get(Context, WideConst)); 6594 } 6595 6596 return true; 6597 } 6598 6599 6600 namespace { 6601 6602 /// Helper class to promote a scalar operation to a vector one. 6603 /// This class is used to move downward extractelement transition. 6604 /// E.g., 6605 /// a = vector_op <2 x i32> 6606 /// b = extractelement <2 x i32> a, i32 0 6607 /// c = scalar_op b 6608 /// store c 6609 /// 6610 /// => 6611 /// a = vector_op <2 x i32> 6612 /// c = vector_op a (equivalent to scalar_op on the related lane) 6613 /// * d = extractelement <2 x i32> c, i32 0 6614 /// * store d 6615 /// Assuming both extractelement and store can be combine, we get rid of the 6616 /// transition. 6617 class VectorPromoteHelper { 6618 /// DataLayout associated with the current module. 6619 const DataLayout &DL; 6620 6621 /// Used to perform some checks on the legality of vector operations. 6622 const TargetLowering &TLI; 6623 6624 /// Used to estimated the cost of the promoted chain. 6625 const TargetTransformInfo &TTI; 6626 6627 /// The transition being moved downwards. 6628 Instruction *Transition; 6629 6630 /// The sequence of instructions to be promoted. 6631 SmallVector<Instruction *, 4> InstsToBePromoted; 6632 6633 /// Cost of combining a store and an extract. 6634 unsigned StoreExtractCombineCost; 6635 6636 /// Instruction that will be combined with the transition. 6637 Instruction *CombineInst = nullptr; 6638 6639 /// The instruction that represents the current end of the transition. 6640 /// Since we are faking the promotion until we reach the end of the chain 6641 /// of computation, we need a way to get the current end of the transition. 6642 Instruction *getEndOfTransition() const { 6643 if (InstsToBePromoted.empty()) 6644 return Transition; 6645 return InstsToBePromoted.back(); 6646 } 6647 6648 /// Return the index of the original value in the transition. 6649 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, 6650 /// c, is at index 0. 6651 unsigned getTransitionOriginalValueIdx() const { 6652 assert(isa<ExtractElementInst>(Transition) && 6653 "Other kind of transitions are not supported yet"); 6654 return 0; 6655 } 6656 6657 /// Return the index of the index in the transition. 6658 /// E.g., for "extractelement <2 x i32> c, i32 0" the index 6659 /// is at index 1. 6660 unsigned getTransitionIdx() const { 6661 assert(isa<ExtractElementInst>(Transition) && 6662 "Other kind of transitions are not supported yet"); 6663 return 1; 6664 } 6665 6666 /// Get the type of the transition. 6667 /// This is the type of the original value. 6668 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the 6669 /// transition is <2 x i32>. 6670 Type *getTransitionType() const { 6671 return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); 6672 } 6673 6674 /// Promote \p ToBePromoted by moving \p Def downward through. 6675 /// I.e., we have the following sequence: 6676 /// Def = Transition <ty1> a to <ty2> 6677 /// b = ToBePromoted <ty2> Def, ... 6678 /// => 6679 /// b = ToBePromoted <ty1> a, ... 6680 /// Def = Transition <ty1> ToBePromoted to <ty2> 6681 void promoteImpl(Instruction *ToBePromoted); 6682 6683 /// Check whether or not it is profitable to promote all the 6684 /// instructions enqueued to be promoted. 6685 bool isProfitableToPromote() { 6686 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); 6687 unsigned Index = isa<ConstantInt>(ValIdx) 6688 ? cast<ConstantInt>(ValIdx)->getZExtValue() 6689 : -1; 6690 Type *PromotedType = getTransitionType(); 6691 6692 StoreInst *ST = cast<StoreInst>(CombineInst); 6693 unsigned AS = ST->getPointerAddressSpace(); 6694 unsigned Align = ST->getAlignment(); 6695 // Check if this store is supported. 6696 if (!TLI.allowsMisalignedMemoryAccesses( 6697 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, 6698 Align)) { 6699 // If this is not supported, there is no way we can combine 6700 // the extract with the store. 6701 return false; 6702 } 6703 6704 // The scalar chain of computation has to pay for the transition 6705 // scalar to vector. 6706 // The vector chain has to account for the combining cost. 6707 uint64_t ScalarCost = 6708 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); 6709 uint64_t VectorCost = StoreExtractCombineCost; 6710 enum TargetTransformInfo::TargetCostKind CostKind = 6711 TargetTransformInfo::TCK_RecipThroughput; 6712 for (const auto &Inst : InstsToBePromoted) { 6713 // Compute the cost. 6714 // By construction, all instructions being promoted are arithmetic ones. 6715 // Moreover, one argument is a constant that can be viewed as a splat 6716 // constant. 6717 Value *Arg0 = Inst->getOperand(0); 6718 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || 6719 isa<ConstantFP>(Arg0); 6720 TargetTransformInfo::OperandValueKind Arg0OVK = 6721 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue 6722 : TargetTransformInfo::OK_AnyValue; 6723 TargetTransformInfo::OperandValueKind Arg1OVK = 6724 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue 6725 : TargetTransformInfo::OK_AnyValue; 6726 ScalarCost += TTI.getArithmeticInstrCost( 6727 Inst->getOpcode(), Inst->getType(), CostKind, Arg0OVK, Arg1OVK); 6728 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, 6729 CostKind, 6730 Arg0OVK, Arg1OVK); 6731 } 6732 LLVM_DEBUG( 6733 dbgs() << "Estimated cost of computation to be promoted:\nScalar: " 6734 << ScalarCost << "\nVector: " << VectorCost << '\n'); 6735 return ScalarCost > VectorCost; 6736 } 6737 6738 /// Generate a constant vector with \p Val with the same 6739 /// number of elements as the transition. 6740 /// \p UseSplat defines whether or not \p Val should be replicated 6741 /// across the whole vector. 6742 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, 6743 /// otherwise we generate a vector with as many undef as possible: 6744 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only 6745 /// used at the index of the extract. 6746 Value *getConstantVector(Constant *Val, bool UseSplat) const { 6747 unsigned ExtractIdx = std::numeric_limits<unsigned>::max(); 6748 if (!UseSplat) { 6749 // If we cannot determine where the constant must be, we have to 6750 // use a splat constant. 6751 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); 6752 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) 6753 ExtractIdx = CstVal->getSExtValue(); 6754 else 6755 UseSplat = true; 6756 } 6757 6758 ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount(); 6759 if (UseSplat) 6760 return ConstantVector::getSplat(EC, Val); 6761 6762 if (!EC.Scalable) { 6763 SmallVector<Constant *, 4> ConstVec; 6764 UndefValue *UndefVal = UndefValue::get(Val->getType()); 6765 for (unsigned Idx = 0; Idx != EC.Min; ++Idx) { 6766 if (Idx == ExtractIdx) 6767 ConstVec.push_back(Val); 6768 else 6769 ConstVec.push_back(UndefVal); 6770 } 6771 return ConstantVector::get(ConstVec); 6772 } else 6773 llvm_unreachable( 6774 "Generate scalable vector for non-splat is unimplemented"); 6775 } 6776 6777 /// Check if promoting to a vector type an operand at \p OperandIdx 6778 /// in \p Use can trigger undefined behavior. 6779 static bool canCauseUndefinedBehavior(const Instruction *Use, 6780 unsigned OperandIdx) { 6781 // This is not safe to introduce undef when the operand is on 6782 // the right hand side of a division-like instruction. 6783 if (OperandIdx != 1) 6784 return false; 6785 switch (Use->getOpcode()) { 6786 default: 6787 return false; 6788 case Instruction::SDiv: 6789 case Instruction::UDiv: 6790 case Instruction::SRem: 6791 case Instruction::URem: 6792 return true; 6793 case Instruction::FDiv: 6794 case Instruction::FRem: 6795 return !Use->hasNoNaNs(); 6796 } 6797 llvm_unreachable(nullptr); 6798 } 6799 6800 public: 6801 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, 6802 const TargetTransformInfo &TTI, Instruction *Transition, 6803 unsigned CombineCost) 6804 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), 6805 StoreExtractCombineCost(CombineCost) { 6806 assert(Transition && "Do not know how to promote null"); 6807 } 6808 6809 /// Check if we can promote \p ToBePromoted to \p Type. 6810 bool canPromote(const Instruction *ToBePromoted) const { 6811 // We could support CastInst too. 6812 return isa<BinaryOperator>(ToBePromoted); 6813 } 6814 6815 /// Check if it is profitable to promote \p ToBePromoted 6816 /// by moving downward the transition through. 6817 bool shouldPromote(const Instruction *ToBePromoted) const { 6818 // Promote only if all the operands can be statically expanded. 6819 // Indeed, we do not want to introduce any new kind of transitions. 6820 for (const Use &U : ToBePromoted->operands()) { 6821 const Value *Val = U.get(); 6822 if (Val == getEndOfTransition()) { 6823 // If the use is a division and the transition is on the rhs, 6824 // we cannot promote the operation, otherwise we may create a 6825 // division by zero. 6826 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) 6827 return false; 6828 continue; 6829 } 6830 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && 6831 !isa<ConstantFP>(Val)) 6832 return false; 6833 } 6834 // Check that the resulting operation is legal. 6835 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); 6836 if (!ISDOpcode) 6837 return false; 6838 return StressStoreExtract || 6839 TLI.isOperationLegalOrCustom( 6840 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); 6841 } 6842 6843 /// Check whether or not \p Use can be combined 6844 /// with the transition. 6845 /// I.e., is it possible to do Use(Transition) => AnotherUse? 6846 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } 6847 6848 /// Record \p ToBePromoted as part of the chain to be promoted. 6849 void enqueueForPromotion(Instruction *ToBePromoted) { 6850 InstsToBePromoted.push_back(ToBePromoted); 6851 } 6852 6853 /// Set the instruction that will be combined with the transition. 6854 void recordCombineInstruction(Instruction *ToBeCombined) { 6855 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); 6856 CombineInst = ToBeCombined; 6857 } 6858 6859 /// Promote all the instructions enqueued for promotion if it is 6860 /// is profitable. 6861 /// \return True if the promotion happened, false otherwise. 6862 bool promote() { 6863 // Check if there is something to promote. 6864 // Right now, if we do not have anything to combine with, 6865 // we assume the promotion is not profitable. 6866 if (InstsToBePromoted.empty() || !CombineInst) 6867 return false; 6868 6869 // Check cost. 6870 if (!StressStoreExtract && !isProfitableToPromote()) 6871 return false; 6872 6873 // Promote. 6874 for (auto &ToBePromoted : InstsToBePromoted) 6875 promoteImpl(ToBePromoted); 6876 InstsToBePromoted.clear(); 6877 return true; 6878 } 6879 }; 6880 6881 } // end anonymous namespace 6882 6883 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { 6884 // At this point, we know that all the operands of ToBePromoted but Def 6885 // can be statically promoted. 6886 // For Def, we need to use its parameter in ToBePromoted: 6887 // b = ToBePromoted ty1 a 6888 // Def = Transition ty1 b to ty2 6889 // Move the transition down. 6890 // 1. Replace all uses of the promoted operation by the transition. 6891 // = ... b => = ... Def. 6892 assert(ToBePromoted->getType() == Transition->getType() && 6893 "The type of the result of the transition does not match " 6894 "the final type"); 6895 ToBePromoted->replaceAllUsesWith(Transition); 6896 // 2. Update the type of the uses. 6897 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. 6898 Type *TransitionTy = getTransitionType(); 6899 ToBePromoted->mutateType(TransitionTy); 6900 // 3. Update all the operands of the promoted operation with promoted 6901 // operands. 6902 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. 6903 for (Use &U : ToBePromoted->operands()) { 6904 Value *Val = U.get(); 6905 Value *NewVal = nullptr; 6906 if (Val == Transition) 6907 NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); 6908 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || 6909 isa<ConstantFP>(Val)) { 6910 // Use a splat constant if it is not safe to use undef. 6911 NewVal = getConstantVector( 6912 cast<Constant>(Val), 6913 isa<UndefValue>(Val) || 6914 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); 6915 } else 6916 llvm_unreachable("Did you modified shouldPromote and forgot to update " 6917 "this?"); 6918 ToBePromoted->setOperand(U.getOperandNo(), NewVal); 6919 } 6920 Transition->moveAfter(ToBePromoted); 6921 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); 6922 } 6923 6924 /// Some targets can do store(extractelement) with one instruction. 6925 /// Try to push the extractelement towards the stores when the target 6926 /// has this feature and this is profitable. 6927 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { 6928 unsigned CombineCost = std::numeric_limits<unsigned>::max(); 6929 if (DisableStoreExtract || 6930 (!StressStoreExtract && 6931 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), 6932 Inst->getOperand(1), CombineCost))) 6933 return false; 6934 6935 // At this point we know that Inst is a vector to scalar transition. 6936 // Try to move it down the def-use chain, until: 6937 // - We can combine the transition with its single use 6938 // => we got rid of the transition. 6939 // - We escape the current basic block 6940 // => we would need to check that we are moving it at a cheaper place and 6941 // we do not do that for now. 6942 BasicBlock *Parent = Inst->getParent(); 6943 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); 6944 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); 6945 // If the transition has more than one use, assume this is not going to be 6946 // beneficial. 6947 while (Inst->hasOneUse()) { 6948 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); 6949 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); 6950 6951 if (ToBePromoted->getParent() != Parent) { 6952 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block (" 6953 << ToBePromoted->getParent()->getName() 6954 << ") than the transition (" << Parent->getName() 6955 << ").\n"); 6956 return false; 6957 } 6958 6959 if (VPH.canCombine(ToBePromoted)) { 6960 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n' 6961 << "will be combined with: " << *ToBePromoted << '\n'); 6962 VPH.recordCombineInstruction(ToBePromoted); 6963 bool Changed = VPH.promote(); 6964 NumStoreExtractExposed += Changed; 6965 return Changed; 6966 } 6967 6968 LLVM_DEBUG(dbgs() << "Try promoting.\n"); 6969 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) 6970 return false; 6971 6972 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); 6973 6974 VPH.enqueueForPromotion(ToBePromoted); 6975 Inst = ToBePromoted; 6976 } 6977 return false; 6978 } 6979 6980 /// For the instruction sequence of store below, F and I values 6981 /// are bundled together as an i64 value before being stored into memory. 6982 /// Sometimes it is more efficient to generate separate stores for F and I, 6983 /// which can remove the bitwise instructions or sink them to colder places. 6984 /// 6985 /// (store (or (zext (bitcast F to i32) to i64), 6986 /// (shl (zext I to i64), 32)), addr) --> 6987 /// (store F, addr) and (store I, addr+4) 6988 /// 6989 /// Similarly, splitting for other merged store can also be beneficial, like: 6990 /// For pair of {i32, i32}, i64 store --> two i32 stores. 6991 /// For pair of {i32, i16}, i64 store --> two i32 stores. 6992 /// For pair of {i16, i16}, i32 store --> two i16 stores. 6993 /// For pair of {i16, i8}, i32 store --> two i16 stores. 6994 /// For pair of {i8, i8}, i16 store --> two i8 stores. 6995 /// 6996 /// We allow each target to determine specifically which kind of splitting is 6997 /// supported. 6998 /// 6999 /// The store patterns are commonly seen from the simple code snippet below 7000 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 7001 /// void goo(const std::pair<int, float> &); 7002 /// hoo() { 7003 /// ... 7004 /// goo(std::make_pair(tmp, ftmp)); 7005 /// ... 7006 /// } 7007 /// 7008 /// Although we already have similar splitting in DAG Combine, we duplicate 7009 /// it in CodeGenPrepare to catch the case in which pattern is across 7010 /// multiple BBs. The logic in DAG Combine is kept to catch case generated 7011 /// during code expansion. 7012 static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, 7013 const TargetLowering &TLI) { 7014 // Handle simple but common cases only. 7015 Type *StoreType = SI.getValueOperand()->getType(); 7016 7017 // The code below assumes shifting a value by <number of bits>, 7018 // whereas scalable vectors would have to be shifted by 7019 // <2log(vscale) + number of bits> in order to store the 7020 // low/high parts. Bailing out for now. 7021 if (isa<ScalableVectorType>(StoreType)) 7022 return false; 7023 7024 if (!DL.typeSizeEqualsStoreSize(StoreType) || 7025 DL.getTypeSizeInBits(StoreType) == 0) 7026 return false; 7027 7028 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2; 7029 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize); 7030 if (!DL.typeSizeEqualsStoreSize(SplitStoreType)) 7031 return false; 7032 7033 // Don't split the store if it is volatile. 7034 if (SI.isVolatile()) 7035 return false; 7036 7037 // Match the following patterns: 7038 // (store (or (zext LValue to i64), 7039 // (shl (zext HValue to i64), 32)), HalfValBitSize) 7040 // or 7041 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize) 7042 // (zext LValue to i64), 7043 // Expect both operands of OR and the first operand of SHL have only 7044 // one use. 7045 Value *LValue, *HValue; 7046 if (!match(SI.getValueOperand(), 7047 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))), 7048 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))), 7049 m_SpecificInt(HalfValBitSize)))))) 7050 return false; 7051 7052 // Check LValue and HValue are int with size less or equal than 32. 7053 if (!LValue->getType()->isIntegerTy() || 7054 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize || 7055 !HValue->getType()->isIntegerTy() || 7056 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize) 7057 return false; 7058 7059 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast 7060 // as the input of target query. 7061 auto *LBC = dyn_cast<BitCastInst>(LValue); 7062 auto *HBC = dyn_cast<BitCastInst>(HValue); 7063 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType()) 7064 : EVT::getEVT(LValue->getType()); 7065 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType()) 7066 : EVT::getEVT(HValue->getType()); 7067 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 7068 return false; 7069 7070 // Start to split store. 7071 IRBuilder<> Builder(SI.getContext()); 7072 Builder.SetInsertPoint(&SI); 7073 7074 // If LValue/HValue is a bitcast in another BB, create a new one in current 7075 // BB so it may be merged with the splitted stores by dag combiner. 7076 if (LBC && LBC->getParent() != SI.getParent()) 7077 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType()); 7078 if (HBC && HBC->getParent() != SI.getParent()) 7079 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType()); 7080 7081 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian(); 7082 auto CreateSplitStore = [&](Value *V, bool Upper) { 7083 V = Builder.CreateZExtOrBitCast(V, SplitStoreType); 7084 Value *Addr = Builder.CreateBitCast( 7085 SI.getOperand(1), 7086 SplitStoreType->getPointerTo(SI.getPointerAddressSpace())); 7087 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper); 7088 if (IsOffsetStore) 7089 Addr = Builder.CreateGEP( 7090 SplitStoreType, Addr, 7091 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1)); 7092 MaybeAlign Alignment = SI.getAlign(); 7093 if (IsOffsetStore && Alignment) { 7094 // When splitting the store in half, naturally one half will retain the 7095 // alignment of the original wider store, regardless of whether it was 7096 // over-aligned or not, while the other will require adjustment. 7097 Alignment = commonAlignment(Alignment, HalfValBitSize / 8); 7098 } 7099 Builder.CreateAlignedStore(V, Addr, Alignment); 7100 }; 7101 7102 CreateSplitStore(LValue, false); 7103 CreateSplitStore(HValue, true); 7104 7105 // Delete the old store. 7106 SI.eraseFromParent(); 7107 return true; 7108 } 7109 7110 // Return true if the GEP has two operands, the first operand is of a sequential 7111 // type, and the second operand is a constant. 7112 static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) { 7113 gep_type_iterator I = gep_type_begin(*GEP); 7114 return GEP->getNumOperands() == 2 && 7115 I.isSequential() && 7116 isa<ConstantInt>(GEP->getOperand(1)); 7117 } 7118 7119 // Try unmerging GEPs to reduce liveness interference (register pressure) across 7120 // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks, 7121 // reducing liveness interference across those edges benefits global register 7122 // allocation. Currently handles only certain cases. 7123 // 7124 // For example, unmerge %GEPI and %UGEPI as below. 7125 // 7126 // ---------- BEFORE ---------- 7127 // SrcBlock: 7128 // ... 7129 // %GEPIOp = ... 7130 // ... 7131 // %GEPI = gep %GEPIOp, Idx 7132 // ... 7133 // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ] 7134 // (* %GEPI is alive on the indirectbr edges due to other uses ahead) 7135 // (* %GEPIOp is alive on the indirectbr edges only because of it's used by 7136 // %UGEPI) 7137 // 7138 // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged) 7139 // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged) 7140 // ... 7141 // 7142 // DstBi: 7143 // ... 7144 // %UGEPI = gep %GEPIOp, UIdx 7145 // ... 7146 // --------------------------- 7147 // 7148 // ---------- AFTER ---------- 7149 // SrcBlock: 7150 // ... (same as above) 7151 // (* %GEPI is still alive on the indirectbr edges) 7152 // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the 7153 // unmerging) 7154 // ... 7155 // 7156 // DstBi: 7157 // ... 7158 // %UGEPI = gep %GEPI, (UIdx-Idx) 7159 // ... 7160 // --------------------------- 7161 // 7162 // The register pressure on the IndirectBr edges is reduced because %GEPIOp is 7163 // no longer alive on them. 7164 // 7165 // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging 7166 // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as 7167 // not to disable further simplications and optimizations as a result of GEP 7168 // merging. 7169 // 7170 // Note this unmerging may increase the length of the data flow critical path 7171 // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff 7172 // between the register pressure and the length of data-flow critical 7173 // path. Restricting this to the uncommon IndirectBr case would minimize the 7174 // impact of potentially longer critical path, if any, and the impact on compile 7175 // time. 7176 static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, 7177 const TargetTransformInfo *TTI) { 7178 BasicBlock *SrcBlock = GEPI->getParent(); 7179 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common 7180 // (non-IndirectBr) cases exit early here. 7181 if (!isa<IndirectBrInst>(SrcBlock->getTerminator())) 7182 return false; 7183 // Check that GEPI is a simple gep with a single constant index. 7184 if (!GEPSequentialConstIndexed(GEPI)) 7185 return false; 7186 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1)); 7187 // Check that GEPI is a cheap one. 7188 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(), 7189 TargetTransformInfo::TCK_SizeAndLatency) 7190 > TargetTransformInfo::TCC_Basic) 7191 return false; 7192 Value *GEPIOp = GEPI->getOperand(0); 7193 // Check that GEPIOp is an instruction that's also defined in SrcBlock. 7194 if (!isa<Instruction>(GEPIOp)) 7195 return false; 7196 auto *GEPIOpI = cast<Instruction>(GEPIOp); 7197 if (GEPIOpI->getParent() != SrcBlock) 7198 return false; 7199 // Check that GEP is used outside the block, meaning it's alive on the 7200 // IndirectBr edge(s). 7201 if (find_if(GEPI->users(), [&](User *Usr) { 7202 if (auto *I = dyn_cast<Instruction>(Usr)) { 7203 if (I->getParent() != SrcBlock) { 7204 return true; 7205 } 7206 } 7207 return false; 7208 }) == GEPI->users().end()) 7209 return false; 7210 // The second elements of the GEP chains to be unmerged. 7211 std::vector<GetElementPtrInst *> UGEPIs; 7212 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive 7213 // on IndirectBr edges. 7214 for (User *Usr : GEPIOp->users()) { 7215 if (Usr == GEPI) continue; 7216 // Check if Usr is an Instruction. If not, give up. 7217 if (!isa<Instruction>(Usr)) 7218 return false; 7219 auto *UI = cast<Instruction>(Usr); 7220 // Check if Usr in the same block as GEPIOp, which is fine, skip. 7221 if (UI->getParent() == SrcBlock) 7222 continue; 7223 // Check if Usr is a GEP. If not, give up. 7224 if (!isa<GetElementPtrInst>(Usr)) 7225 return false; 7226 auto *UGEPI = cast<GetElementPtrInst>(Usr); 7227 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is 7228 // the pointer operand to it. If so, record it in the vector. If not, give 7229 // up. 7230 if (!GEPSequentialConstIndexed(UGEPI)) 7231 return false; 7232 if (UGEPI->getOperand(0) != GEPIOp) 7233 return false; 7234 if (GEPIIdx->getType() != 7235 cast<ConstantInt>(UGEPI->getOperand(1))->getType()) 7236 return false; 7237 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); 7238 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(), 7239 TargetTransformInfo::TCK_SizeAndLatency) 7240 > TargetTransformInfo::TCC_Basic) 7241 return false; 7242 UGEPIs.push_back(UGEPI); 7243 } 7244 if (UGEPIs.size() == 0) 7245 return false; 7246 // Check the materializing cost of (Uidx-Idx). 7247 for (GetElementPtrInst *UGEPI : UGEPIs) { 7248 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); 7249 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue(); 7250 unsigned ImmCost = 7251 TTI->getIntImmCost(NewIdx, GEPIIdx->getType(), 7252 TargetTransformInfo::TCK_SizeAndLatency); 7253 if (ImmCost > TargetTransformInfo::TCC_Basic) 7254 return false; 7255 } 7256 // Now unmerge between GEPI and UGEPIs. 7257 for (GetElementPtrInst *UGEPI : UGEPIs) { 7258 UGEPI->setOperand(0, GEPI); 7259 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); 7260 Constant *NewUGEPIIdx = 7261 ConstantInt::get(GEPIIdx->getType(), 7262 UGEPIIdx->getValue() - GEPIIdx->getValue()); 7263 UGEPI->setOperand(1, NewUGEPIIdx); 7264 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not 7265 // inbounds to avoid UB. 7266 if (!GEPI->isInBounds()) { 7267 UGEPI->setIsInBounds(false); 7268 } 7269 } 7270 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not 7271 // alive on IndirectBr edges). 7272 assert(find_if(GEPIOp->users(), [&](User *Usr) { 7273 return cast<Instruction>(Usr)->getParent() != SrcBlock; 7274 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock"); 7275 return true; 7276 } 7277 7278 bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) { 7279 // Bail out if we inserted the instruction to prevent optimizations from 7280 // stepping on each other's toes. 7281 if (InsertedInsts.count(I)) 7282 return false; 7283 7284 // TODO: Move into the switch on opcode below here. 7285 if (PHINode *P = dyn_cast<PHINode>(I)) { 7286 // It is possible for very late stage optimizations (such as SimplifyCFG) 7287 // to introduce PHI nodes too late to be cleaned up. If we detect such a 7288 // trivial PHI, go ahead and zap it here. 7289 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) { 7290 LargeOffsetGEPMap.erase(P); 7291 P->replaceAllUsesWith(V); 7292 P->eraseFromParent(); 7293 ++NumPHIsElim; 7294 return true; 7295 } 7296 return false; 7297 } 7298 7299 if (CastInst *CI = dyn_cast<CastInst>(I)) { 7300 // If the source of the cast is a constant, then this should have 7301 // already been constant folded. The only reason NOT to constant fold 7302 // it is if something (e.g. LSR) was careful to place the constant 7303 // evaluation in a block other than then one that uses it (e.g. to hoist 7304 // the address of globals out of a loop). If this is the case, we don't 7305 // want to forward-subst the cast. 7306 if (isa<Constant>(CI->getOperand(0))) 7307 return false; 7308 7309 if (OptimizeNoopCopyExpression(CI, *TLI, *DL)) 7310 return true; 7311 7312 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { 7313 /// Sink a zext or sext into its user blocks if the target type doesn't 7314 /// fit in one register 7315 if (TLI->getTypeAction(CI->getContext(), 7316 TLI->getValueType(*DL, CI->getType())) == 7317 TargetLowering::TypeExpandInteger) { 7318 return SinkCast(CI); 7319 } else { 7320 bool MadeChange = optimizeExt(I); 7321 return MadeChange | optimizeExtUses(I); 7322 } 7323 } 7324 return false; 7325 } 7326 7327 if (auto *Cmp = dyn_cast<CmpInst>(I)) 7328 if (optimizeCmp(Cmp, ModifiedDT)) 7329 return true; 7330 7331 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7332 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); 7333 bool Modified = optimizeLoadExt(LI); 7334 unsigned AS = LI->getPointerAddressSpace(); 7335 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); 7336 return Modified; 7337 } 7338 7339 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 7340 if (splitMergedValStore(*SI, *DL, *TLI)) 7341 return true; 7342 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); 7343 unsigned AS = SI->getPointerAddressSpace(); 7344 return optimizeMemoryInst(I, SI->getOperand(1), 7345 SI->getOperand(0)->getType(), AS); 7346 } 7347 7348 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { 7349 unsigned AS = RMW->getPointerAddressSpace(); 7350 return optimizeMemoryInst(I, RMW->getPointerOperand(), 7351 RMW->getType(), AS); 7352 } 7353 7354 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) { 7355 unsigned AS = CmpX->getPointerAddressSpace(); 7356 return optimizeMemoryInst(I, CmpX->getPointerOperand(), 7357 CmpX->getCompareOperand()->getType(), AS); 7358 } 7359 7360 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); 7361 7362 if (BinOp && (BinOp->getOpcode() == Instruction::And) && EnableAndCmpSinking) 7363 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts); 7364 7365 // TODO: Move this into the switch on opcode - it handles shifts already. 7366 if (BinOp && (BinOp->getOpcode() == Instruction::AShr || 7367 BinOp->getOpcode() == Instruction::LShr)) { 7368 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); 7369 if (CI && TLI->hasExtractBitsInsn()) 7370 if (OptimizeExtractBits(BinOp, CI, *TLI, *DL)) 7371 return true; 7372 } 7373 7374 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { 7375 if (GEPI->hasAllZeroIndices()) { 7376 /// The GEP operand must be a pointer, so must its result -> BitCast 7377 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), 7378 GEPI->getName(), GEPI); 7379 NC->setDebugLoc(GEPI->getDebugLoc()); 7380 GEPI->replaceAllUsesWith(NC); 7381 GEPI->eraseFromParent(); 7382 ++NumGEPsElim; 7383 optimizeInst(NC, ModifiedDT); 7384 return true; 7385 } 7386 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) { 7387 return true; 7388 } 7389 return false; 7390 } 7391 7392 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) { 7393 // freeze(icmp a, const)) -> icmp (freeze a), const 7394 // This helps generate efficient conditional jumps. 7395 Instruction *CmpI = nullptr; 7396 if (ICmpInst *II = dyn_cast<ICmpInst>(FI->getOperand(0))) 7397 CmpI = II; 7398 else if (FCmpInst *F = dyn_cast<FCmpInst>(FI->getOperand(0))) 7399 CmpI = F->getFastMathFlags().none() ? F : nullptr; 7400 7401 if (CmpI && CmpI->hasOneUse()) { 7402 auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1); 7403 bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) || 7404 isa<ConstantPointerNull>(Op0); 7405 bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) || 7406 isa<ConstantPointerNull>(Op1); 7407 if (Const0 || Const1) { 7408 if (!Const0 || !Const1) { 7409 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI); 7410 F->takeName(FI); 7411 CmpI->setOperand(Const0 ? 1 : 0, F); 7412 } 7413 FI->replaceAllUsesWith(CmpI); 7414 FI->eraseFromParent(); 7415 return true; 7416 } 7417 } 7418 return false; 7419 } 7420 7421 if (tryToSinkFreeOperands(I)) 7422 return true; 7423 7424 switch (I->getOpcode()) { 7425 case Instruction::Shl: 7426 case Instruction::LShr: 7427 case Instruction::AShr: 7428 return optimizeShiftInst(cast<BinaryOperator>(I)); 7429 case Instruction::Call: 7430 return optimizeCallInst(cast<CallInst>(I), ModifiedDT); 7431 case Instruction::Select: 7432 return optimizeSelectInst(cast<SelectInst>(I)); 7433 case Instruction::ShuffleVector: 7434 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I)); 7435 case Instruction::Switch: 7436 return optimizeSwitchInst(cast<SwitchInst>(I)); 7437 case Instruction::ExtractElement: 7438 return optimizeExtractElementInst(cast<ExtractElementInst>(I)); 7439 } 7440 7441 return false; 7442 } 7443 7444 /// Given an OR instruction, check to see if this is a bitreverse 7445 /// idiom. If so, insert the new intrinsic and return true. 7446 static bool makeBitReverse(Instruction &I, const DataLayout &DL, 7447 const TargetLowering &TLI) { 7448 if (!I.getType()->isIntegerTy() || 7449 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE, 7450 TLI.getValueType(DL, I.getType(), true))) 7451 return false; 7452 7453 SmallVector<Instruction*, 4> Insts; 7454 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) 7455 return false; 7456 Instruction *LastInst = Insts.back(); 7457 I.replaceAllUsesWith(LastInst); 7458 RecursivelyDeleteTriviallyDeadInstructions(&I); 7459 return true; 7460 } 7461 7462 // In this pass we look for GEP and cast instructions that are used 7463 // across basic blocks and rewrite them to improve basic-block-at-a-time 7464 // selection. 7465 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) { 7466 SunkAddrs.clear(); 7467 bool MadeChange = false; 7468 7469 CurInstIterator = BB.begin(); 7470 while (CurInstIterator != BB.end()) { 7471 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); 7472 if (ModifiedDT) 7473 return true; 7474 } 7475 7476 bool MadeBitReverse = true; 7477 while (MadeBitReverse) { 7478 MadeBitReverse = false; 7479 for (auto &I : reverse(BB)) { 7480 if (makeBitReverse(I, *DL, *TLI)) { 7481 MadeBitReverse = MadeChange = true; 7482 break; 7483 } 7484 } 7485 } 7486 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT); 7487 7488 return MadeChange; 7489 } 7490 7491 // Some CGP optimizations may move or alter what's computed in a block. Check 7492 // whether a dbg.value intrinsic could be pointed at a more appropriate operand. 7493 bool CodeGenPrepare::fixupDbgValue(Instruction *I) { 7494 assert(isa<DbgValueInst>(I)); 7495 DbgValueInst &DVI = *cast<DbgValueInst>(I); 7496 7497 // Does this dbg.value refer to a sunk address calculation? 7498 Value *Location = DVI.getVariableLocation(); 7499 WeakTrackingVH SunkAddrVH = SunkAddrs[Location]; 7500 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; 7501 if (SunkAddr) { 7502 // Point dbg.value at locally computed address, which should give the best 7503 // opportunity to be accurately lowered. This update may change the type of 7504 // pointer being referred to; however this makes no difference to debugging 7505 // information, and we can't generate bitcasts that may affect codegen. 7506 DVI.setOperand(0, MetadataAsValue::get(DVI.getContext(), 7507 ValueAsMetadata::get(SunkAddr))); 7508 return true; 7509 } 7510 return false; 7511 } 7512 7513 // A llvm.dbg.value may be using a value before its definition, due to 7514 // optimizations in this pass and others. Scan for such dbg.values, and rescue 7515 // them by moving the dbg.value to immediately after the value definition. 7516 // FIXME: Ideally this should never be necessary, and this has the potential 7517 // to re-order dbg.value intrinsics. 7518 bool CodeGenPrepare::placeDbgValues(Function &F) { 7519 bool MadeChange = false; 7520 DominatorTree DT(F); 7521 7522 for (BasicBlock &BB : F) { 7523 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { 7524 Instruction *Insn = &*BI++; 7525 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); 7526 if (!DVI) 7527 continue; 7528 7529 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); 7530 7531 if (!VI || VI->isTerminator()) 7532 continue; 7533 7534 // If VI is a phi in a block with an EHPad terminator, we can't insert 7535 // after it. 7536 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) 7537 continue; 7538 7539 // If the defining instruction dominates the dbg.value, we do not need 7540 // to move the dbg.value. 7541 if (DT.dominates(VI, DVI)) 7542 continue; 7543 7544 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n" 7545 << *DVI << ' ' << *VI); 7546 DVI->removeFromParent(); 7547 if (isa<PHINode>(VI)) 7548 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); 7549 else 7550 DVI->insertAfter(VI); 7551 MadeChange = true; 7552 ++NumDbgValueMoved; 7553 } 7554 } 7555 return MadeChange; 7556 } 7557 7558 /// Scale down both weights to fit into uint32_t. 7559 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { 7560 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; 7561 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1; 7562 NewTrue = NewTrue / Scale; 7563 NewFalse = NewFalse / Scale; 7564 } 7565 7566 /// Some targets prefer to split a conditional branch like: 7567 /// \code 7568 /// %0 = icmp ne i32 %a, 0 7569 /// %1 = icmp ne i32 %b, 0 7570 /// %or.cond = or i1 %0, %1 7571 /// br i1 %or.cond, label %TrueBB, label %FalseBB 7572 /// \endcode 7573 /// into multiple branch instructions like: 7574 /// \code 7575 /// bb1: 7576 /// %0 = icmp ne i32 %a, 0 7577 /// br i1 %0, label %TrueBB, label %bb2 7578 /// bb2: 7579 /// %1 = icmp ne i32 %b, 0 7580 /// br i1 %1, label %TrueBB, label %FalseBB 7581 /// \endcode 7582 /// This usually allows instruction selection to do even further optimizations 7583 /// and combine the compare with the branch instruction. Currently this is 7584 /// applied for targets which have "cheap" jump instructions. 7585 /// 7586 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. 7587 /// 7588 bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) { 7589 if (!TM->Options.EnableFastISel || TLI->isJumpExpensive()) 7590 return false; 7591 7592 bool MadeChange = false; 7593 for (auto &BB : F) { 7594 // Does this BB end with the following? 7595 // %cond1 = icmp|fcmp|binary instruction ... 7596 // %cond2 = icmp|fcmp|binary instruction ... 7597 // %cond.or = or|and i1 %cond1, cond2 7598 // br i1 %cond.or label %dest1, label %dest2" 7599 BinaryOperator *LogicOp; 7600 BasicBlock *TBB, *FBB; 7601 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) 7602 continue; 7603 7604 auto *Br1 = cast<BranchInst>(BB.getTerminator()); 7605 if (Br1->getMetadata(LLVMContext::MD_unpredictable)) 7606 continue; 7607 7608 // The merging of mostly empty BB can cause a degenerate branch. 7609 if (TBB == FBB) 7610 continue; 7611 7612 unsigned Opc; 7613 Value *Cond1, *Cond2; 7614 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), 7615 m_OneUse(m_Value(Cond2))))) 7616 Opc = Instruction::And; 7617 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), 7618 m_OneUse(m_Value(Cond2))))) 7619 Opc = Instruction::Or; 7620 else 7621 continue; 7622 7623 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || 7624 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) 7625 continue; 7626 7627 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); 7628 7629 // Create a new BB. 7630 auto TmpBB = 7631 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", 7632 BB.getParent(), BB.getNextNode()); 7633 7634 // Update original basic block by using the first condition directly by the 7635 // branch instruction and removing the no longer needed and/or instruction. 7636 Br1->setCondition(Cond1); 7637 LogicOp->eraseFromParent(); 7638 7639 // Depending on the condition we have to either replace the true or the 7640 // false successor of the original branch instruction. 7641 if (Opc == Instruction::And) 7642 Br1->setSuccessor(0, TmpBB); 7643 else 7644 Br1->setSuccessor(1, TmpBB); 7645 7646 // Fill in the new basic block. 7647 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); 7648 if (auto *I = dyn_cast<Instruction>(Cond2)) { 7649 I->removeFromParent(); 7650 I->insertBefore(Br2); 7651 } 7652 7653 // Update PHI nodes in both successors. The original BB needs to be 7654 // replaced in one successor's PHI nodes, because the branch comes now from 7655 // the newly generated BB (NewBB). In the other successor we need to add one 7656 // incoming edge to the PHI nodes, because both branch instructions target 7657 // now the same successor. Depending on the original branch condition 7658 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that 7659 // we perform the correct update for the PHI nodes. 7660 // This doesn't change the successor order of the just created branch 7661 // instruction (or any other instruction). 7662 if (Opc == Instruction::Or) 7663 std::swap(TBB, FBB); 7664 7665 // Replace the old BB with the new BB. 7666 TBB->replacePhiUsesWith(&BB, TmpBB); 7667 7668 // Add another incoming edge form the new BB. 7669 for (PHINode &PN : FBB->phis()) { 7670 auto *Val = PN.getIncomingValueForBlock(&BB); 7671 PN.addIncoming(Val, TmpBB); 7672 } 7673 7674 // Update the branch weights (from SelectionDAGBuilder:: 7675 // FindMergedConditions). 7676 if (Opc == Instruction::Or) { 7677 // Codegen X | Y as: 7678 // BB1: 7679 // jmp_if_X TBB 7680 // jmp TmpBB 7681 // TmpBB: 7682 // jmp_if_Y TBB 7683 // jmp FBB 7684 // 7685 7686 // We have flexibility in setting Prob for BB1 and Prob for NewBB. 7687 // The requirement is that 7688 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 7689 // = TrueProb for original BB. 7690 // Assuming the original weights are A and B, one choice is to set BB1's 7691 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice 7692 // assumes that 7693 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 7694 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 7695 // TmpBB, but the math is more complicated. 7696 uint64_t TrueWeight, FalseWeight; 7697 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { 7698 uint64_t NewTrueWeight = TrueWeight; 7699 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; 7700 scaleWeights(NewTrueWeight, NewFalseWeight); 7701 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) 7702 .createBranchWeights(TrueWeight, FalseWeight)); 7703 7704 NewTrueWeight = TrueWeight; 7705 NewFalseWeight = 2 * FalseWeight; 7706 scaleWeights(NewTrueWeight, NewFalseWeight); 7707 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) 7708 .createBranchWeights(TrueWeight, FalseWeight)); 7709 } 7710 } else { 7711 // Codegen X & Y as: 7712 // BB1: 7713 // jmp_if_X TmpBB 7714 // jmp FBB 7715 // TmpBB: 7716 // jmp_if_Y TBB 7717 // jmp FBB 7718 // 7719 // This requires creation of TmpBB after CurBB. 7720 7721 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 7722 // The requirement is that 7723 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 7724 // = FalseProb for original BB. 7725 // Assuming the original weights are A and B, one choice is to set BB1's 7726 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice 7727 // assumes that 7728 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. 7729 uint64_t TrueWeight, FalseWeight; 7730 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { 7731 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; 7732 uint64_t NewFalseWeight = FalseWeight; 7733 scaleWeights(NewTrueWeight, NewFalseWeight); 7734 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) 7735 .createBranchWeights(TrueWeight, FalseWeight)); 7736 7737 NewTrueWeight = 2 * TrueWeight; 7738 NewFalseWeight = FalseWeight; 7739 scaleWeights(NewTrueWeight, NewFalseWeight); 7740 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) 7741 .createBranchWeights(TrueWeight, FalseWeight)); 7742 } 7743 } 7744 7745 ModifiedDT = true; 7746 MadeChange = true; 7747 7748 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); 7749 TmpBB->dump()); 7750 } 7751 return MadeChange; 7752 } 7753