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