191bc56edSDimitry Andric //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
291bc56edSDimitry Andric //
391bc56edSDimitry Andric //                     The LLVM Compiler Infrastructure
491bc56edSDimitry Andric //
591bc56edSDimitry Andric // This file is distributed under the University of Illinois Open Source
691bc56edSDimitry Andric // License. See LICENSE.TXT for details.
791bc56edSDimitry Andric //
891bc56edSDimitry Andric //===----------------------------------------------------------------------===//
991bc56edSDimitry Andric //
1091bc56edSDimitry Andric // This pass munges the code in the input function to better prepare it for
1191bc56edSDimitry Andric // SelectionDAG-based code generation. This works around limitations in it's
1291bc56edSDimitry Andric // basic-block-at-a-time approach. It should eventually be removed.
1391bc56edSDimitry Andric //
1491bc56edSDimitry Andric //===----------------------------------------------------------------------===//
1591bc56edSDimitry Andric 
1691bc56edSDimitry Andric #include "llvm/ADT/DenseMap.h"
177a7e6055SDimitry Andric #include "llvm/ADT/SetVector.h"
1891bc56edSDimitry Andric #include "llvm/ADT/SmallSet.h"
1991bc56edSDimitry Andric #include "llvm/ADT/Statistic.h"
20d88c1a5aSDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
21d88c1a5aSDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
227a7e6055SDimitry Andric #include "llvm/Analysis/CFG.h"
2391bc56edSDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
243ca95b02SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
25f9448bf3SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
26d88c1a5aSDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
27ff0cc061SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
2839d628a0SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
297d523365SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
30d88c1a5aSDimitry Andric #include "llvm/CodeGen/Analysis.h"
31f9448bf3SDimitry Andric #include "llvm/CodeGen/Passes.h"
32db17bf38SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
3391bc56edSDimitry Andric #include "llvm/IR/CallSite.h"
3491bc56edSDimitry Andric #include "llvm/IR/Constants.h"
3591bc56edSDimitry Andric #include "llvm/IR/DataLayout.h"
3691bc56edSDimitry Andric #include "llvm/IR/DerivedTypes.h"
3791bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
3891bc56edSDimitry Andric #include "llvm/IR/Function.h"
3991bc56edSDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
4091bc56edSDimitry Andric #include "llvm/IR/IRBuilder.h"
4191bc56edSDimitry Andric #include "llvm/IR/InlineAsm.h"
4291bc56edSDimitry Andric #include "llvm/IR/Instructions.h"
4391bc56edSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
4439d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h"
4591bc56edSDimitry Andric #include "llvm/IR/PatternMatch.h"
46ff0cc061SDimitry Andric #include "llvm/IR/Statepoint.h"
4791bc56edSDimitry Andric #include "llvm/IR/ValueHandle.h"
4891bc56edSDimitry Andric #include "llvm/IR/ValueMap.h"
4991bc56edSDimitry Andric #include "llvm/Pass.h"
503ca95b02SDimitry Andric #include "llvm/Support/BranchProbability.h"
5191bc56edSDimitry Andric #include "llvm/Support/CommandLine.h"
5291bc56edSDimitry Andric #include "llvm/Support/Debug.h"
5391bc56edSDimitry Andric #include "llvm/Support/raw_ostream.h"
5491bc56edSDimitry Andric #include "llvm/Target/TargetLowering.h"
5591bc56edSDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
5691bc56edSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
5791bc56edSDimitry Andric #include "llvm/Transforms/Utils/BuildLibCalls.h"
5891bc56edSDimitry Andric #include "llvm/Transforms/Utils/BypassSlowDivision.h"
597a7e6055SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
6091bc56edSDimitry Andric #include "llvm/Transforms/Utils/Local.h"
6139d628a0SDimitry Andric #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
627a7e6055SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
63f9448bf3SDimitry Andric 
6491bc56edSDimitry Andric using namespace llvm;
6591bc56edSDimitry Andric using namespace llvm::PatternMatch;
6691bc56edSDimitry Andric 
6791bc56edSDimitry Andric #define DEBUG_TYPE "codegenprepare"
6891bc56edSDimitry Andric 
6991bc56edSDimitry Andric STATISTIC(NumBlocksElim, "Number of blocks eliminated");
7091bc56edSDimitry Andric STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
7191bc56edSDimitry Andric STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
7291bc56edSDimitry Andric STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
7391bc56edSDimitry Andric                       "sunken Cmps");
7491bc56edSDimitry Andric STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
7591bc56edSDimitry Andric                        "of sunken Casts");
7691bc56edSDimitry Andric STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
7791bc56edSDimitry Andric                           "computations were sunk");
7891bc56edSDimitry Andric STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
7991bc56edSDimitry Andric STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
807d523365SDimitry Andric STATISTIC(NumAndsAdded,
817d523365SDimitry Andric           "Number of and mask instructions added to form ext loads");
827d523365SDimitry Andric STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
8391bc56edSDimitry Andric STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
8491bc56edSDimitry Andric STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
8591bc56edSDimitry Andric STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
8639d628a0SDimitry Andric STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
8791bc56edSDimitry Andric 
88f9448bf3SDimitry Andric STATISTIC(NumMemCmpCalls, "Number of memcmp calls");
89f9448bf3SDimitry Andric STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size");
90f9448bf3SDimitry Andric STATISTIC(NumMemCmpGreaterThanMax,
91f9448bf3SDimitry Andric           "Number of memcmp calls with size greater than max size");
92f9448bf3SDimitry Andric STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls");
93f9448bf3SDimitry Andric 
9491bc56edSDimitry Andric static cl::opt<bool> DisableBranchOpts(
9591bc56edSDimitry Andric   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
9691bc56edSDimitry Andric   cl::desc("Disable branch optimizations in CodeGenPrepare"));
9791bc56edSDimitry Andric 
98ff0cc061SDimitry Andric static cl::opt<bool>
99ff0cc061SDimitry Andric     DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
100ff0cc061SDimitry Andric                   cl::desc("Disable GC optimizations in CodeGenPrepare"));
101ff0cc061SDimitry Andric 
10291bc56edSDimitry Andric static cl::opt<bool> DisableSelectToBranch(
10391bc56edSDimitry Andric   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
10491bc56edSDimitry Andric   cl::desc("Disable select to branch conversion."));
10591bc56edSDimitry Andric 
10691bc56edSDimitry Andric static cl::opt<bool> AddrSinkUsingGEPs(
1077a7e6055SDimitry Andric   "addr-sink-using-gep", cl::Hidden, cl::init(true),
10891bc56edSDimitry Andric   cl::desc("Address sinking in CGP using GEPs."));
10991bc56edSDimitry Andric 
11091bc56edSDimitry Andric static cl::opt<bool> EnableAndCmpSinking(
11191bc56edSDimitry Andric    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
11291bc56edSDimitry Andric    cl::desc("Enable sinkinig and/cmp into branches."));
11391bc56edSDimitry Andric 
11439d628a0SDimitry Andric static cl::opt<bool> DisableStoreExtract(
11539d628a0SDimitry Andric     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
11639d628a0SDimitry Andric     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
11739d628a0SDimitry Andric 
11839d628a0SDimitry Andric static cl::opt<bool> StressStoreExtract(
11939d628a0SDimitry Andric     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
12039d628a0SDimitry Andric     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
12139d628a0SDimitry Andric 
12239d628a0SDimitry Andric static cl::opt<bool> DisableExtLdPromotion(
12339d628a0SDimitry Andric     "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
12439d628a0SDimitry Andric     cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
12539d628a0SDimitry Andric              "CodeGenPrepare"));
12639d628a0SDimitry Andric 
12739d628a0SDimitry Andric static cl::opt<bool> StressExtLdPromotion(
12839d628a0SDimitry Andric     "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
12939d628a0SDimitry Andric     cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
13039d628a0SDimitry Andric              "optimization in CodeGenPrepare"));
13139d628a0SDimitry Andric 
1323ca95b02SDimitry Andric static cl::opt<bool> DisablePreheaderProtect(
1333ca95b02SDimitry Andric     "disable-preheader-prot", cl::Hidden, cl::init(false),
1343ca95b02SDimitry Andric     cl::desc("Disable protection against removing loop preheaders"));
1353ca95b02SDimitry Andric 
136d88c1a5aSDimitry Andric static cl::opt<bool> ProfileGuidedSectionPrefix(
13724d58133SDimitry Andric     "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
138d88c1a5aSDimitry Andric     cl::desc("Use profile info to add section prefix for hot/cold functions"));
139d88c1a5aSDimitry Andric 
140d88c1a5aSDimitry Andric static cl::opt<unsigned> FreqRatioToSkipMerge(
141d88c1a5aSDimitry Andric     "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
142d88c1a5aSDimitry Andric     cl::desc("Skip merging empty blocks if (frequency of empty block) / "
143d88c1a5aSDimitry Andric              "(frequency of destination block) is greater than this ratio"));
144d88c1a5aSDimitry Andric 
145d88c1a5aSDimitry Andric static cl::opt<bool> ForceSplitStore(
146d88c1a5aSDimitry Andric     "force-split-store", cl::Hidden, cl::init(false),
147d88c1a5aSDimitry Andric     cl::desc("Force store splitting no matter what the target query says."));
148d88c1a5aSDimitry Andric 
1497a7e6055SDimitry Andric static cl::opt<bool>
1507a7e6055SDimitry Andric EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
1517a7e6055SDimitry Andric     cl::desc("Enable merging of redundant sexts when one is dominating"
1527a7e6055SDimitry Andric     " the other."), cl::init(true));
1537a7e6055SDimitry Andric 
154f9448bf3SDimitry Andric static cl::opt<unsigned> MemCmpNumLoadsPerBlock(
155f9448bf3SDimitry Andric     "memcmp-num-loads-per-block", cl::Hidden, cl::init(1),
156f9448bf3SDimitry Andric     cl::desc("The number of loads per basic block for inline expansion of "
157f9448bf3SDimitry Andric              "memcmp that is only being compared against zero."));
158f9448bf3SDimitry Andric 
15991bc56edSDimitry Andric namespace {
16091bc56edSDimitry Andric typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
1617d523365SDimitry Andric typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
16239d628a0SDimitry Andric typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
1637a7e6055SDimitry Andric typedef SmallVector<Instruction *, 16> SExts;
1647a7e6055SDimitry Andric typedef DenseMap<Value *, SExts> ValueToSExts;
16539d628a0SDimitry Andric class TypePromotionTransaction;
16691bc56edSDimitry Andric 
16791bc56edSDimitry Andric   class CodeGenPrepare : public FunctionPass {
16891bc56edSDimitry Andric     const TargetMachine *TM;
1697a7e6055SDimitry Andric     const TargetSubtargetInfo *SubtargetInfo;
17091bc56edSDimitry Andric     const TargetLowering *TLI;
1717a7e6055SDimitry Andric     const TargetRegisterInfo *TRI;
17239d628a0SDimitry Andric     const TargetTransformInfo *TTI;
17391bc56edSDimitry Andric     const TargetLibraryInfo *TLInfo;
1743ca95b02SDimitry Andric     const LoopInfo *LI;
175d88c1a5aSDimitry Andric     std::unique_ptr<BlockFrequencyInfo> BFI;
176d88c1a5aSDimitry Andric     std::unique_ptr<BranchProbabilityInfo> BPI;
17791bc56edSDimitry Andric 
1787d523365SDimitry Andric     /// As we scan instructions optimizing them, this is the next instruction
1797d523365SDimitry Andric     /// to optimize. Transforms that can invalidate this should update it.
18091bc56edSDimitry Andric     BasicBlock::iterator CurInstIterator;
18191bc56edSDimitry Andric 
18291bc56edSDimitry Andric     /// Keeps track of non-local addresses that have been sunk into a block.
18391bc56edSDimitry Andric     /// This allows us to avoid inserting duplicate code for blocks with
18491bc56edSDimitry Andric     /// multiple load/stores of the same address.
18591bc56edSDimitry Andric     ValueMap<Value*, Value*> SunkAddrs;
18691bc56edSDimitry Andric 
1878f0fd8f6SDimitry Andric     /// Keeps track of all instructions inserted for the current function.
1888f0fd8f6SDimitry Andric     SetOfInstrs InsertedInsts;
18991bc56edSDimitry Andric     /// Keeps track of the type of the related instruction before their
19091bc56edSDimitry Andric     /// promotion for the current function.
19191bc56edSDimitry Andric     InstrToOrigTy PromotedInsts;
19291bc56edSDimitry Andric 
1937a7e6055SDimitry Andric     /// Keep track of instructions removed during promotion.
1947a7e6055SDimitry Andric     SetOfInstrs RemovedInsts;
1957a7e6055SDimitry Andric 
1967a7e6055SDimitry Andric     /// Keep track of sext chains based on their initial value.
1977a7e6055SDimitry Andric     DenseMap<Value *, Instruction *> SeenChainsForSExt;
1987a7e6055SDimitry Andric 
1997a7e6055SDimitry Andric     /// Keep track of SExt promoted.
2007a7e6055SDimitry Andric     ValueToSExts ValToSExtendedUses;
2017a7e6055SDimitry Andric 
2027d523365SDimitry Andric     /// True if CFG is modified in any way.
20391bc56edSDimitry Andric     bool ModifiedDT;
20491bc56edSDimitry Andric 
2057d523365SDimitry Andric     /// True if optimizing for size.
20691bc56edSDimitry Andric     bool OptSize;
20791bc56edSDimitry Andric 
208875ed548SDimitry Andric     /// DataLayout for the Function being processed.
209875ed548SDimitry Andric     const DataLayout *DL;
210875ed548SDimitry Andric 
21191bc56edSDimitry Andric   public:
21291bc56edSDimitry Andric     static char ID; // Pass identification, replacement for typeid
213d8866befSDimitry Andric     CodeGenPrepare()
214d8866befSDimitry Andric         : FunctionPass(ID), TM(nullptr), TLI(nullptr), TTI(nullptr),
215d8866befSDimitry Andric           DL(nullptr) {
21691bc56edSDimitry Andric       initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
21791bc56edSDimitry Andric     }
21891bc56edSDimitry Andric     bool runOnFunction(Function &F) override;
21991bc56edSDimitry Andric 
220d88c1a5aSDimitry Andric     StringRef getPassName() const override { return "CodeGen Prepare"; }
22191bc56edSDimitry Andric 
22291bc56edSDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
2233ca95b02SDimitry Andric       // FIXME: When we can selectively preserve passes, preserve the domtree.
224d88c1a5aSDimitry Andric       AU.addRequired<ProfileSummaryInfoWrapperPass>();
225ff0cc061SDimitry Andric       AU.addRequired<TargetLibraryInfoWrapperPass>();
226ff0cc061SDimitry Andric       AU.addRequired<TargetTransformInfoWrapperPass>();
2273ca95b02SDimitry Andric       AU.addRequired<LoopInfoWrapperPass>();
22891bc56edSDimitry Andric     }
22991bc56edSDimitry Andric 
23091bc56edSDimitry Andric   private:
2317d523365SDimitry Andric     bool eliminateFallThrough(Function &F);
2327d523365SDimitry Andric     bool eliminateMostlyEmptyBlocks(Function &F);
233d88c1a5aSDimitry Andric     BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
2347d523365SDimitry Andric     bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
2357d523365SDimitry Andric     void eliminateMostlyEmptyBlock(BasicBlock *BB);
236d88c1a5aSDimitry Andric     bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
237d88c1a5aSDimitry Andric                                        bool isPreheader);
2387d523365SDimitry Andric     bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
2397d523365SDimitry Andric     bool optimizeInst(Instruction *I, bool &ModifiedDT);
2407d523365SDimitry Andric     bool optimizeMemoryInst(Instruction *I, Value *Addr,
24197bc6c73SDimitry Andric                             Type *AccessTy, unsigned AS);
2427d523365SDimitry Andric     bool optimizeInlineAsmInst(CallInst *CS);
2437d523365SDimitry Andric     bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
2447a7e6055SDimitry Andric     bool optimizeExt(Instruction *&I);
2457d523365SDimitry Andric     bool optimizeExtUses(Instruction *I);
2467d523365SDimitry Andric     bool optimizeLoadExt(LoadInst *I);
2477d523365SDimitry Andric     bool optimizeSelectInst(SelectInst *SI);
2487d523365SDimitry Andric     bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
2497d523365SDimitry Andric     bool optimizeSwitchInst(SwitchInst *CI);
2507d523365SDimitry Andric     bool optimizeExtractElementInst(Instruction *Inst);
2517d523365SDimitry Andric     bool dupRetToEnableTailCallOpts(BasicBlock *BB);
2527d523365SDimitry Andric     bool placeDbgValues(Function &F);
2537a7e6055SDimitry Andric     bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
2547a7e6055SDimitry Andric                       LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
2557a7e6055SDimitry Andric     bool tryToPromoteExts(TypePromotionTransaction &TPT,
25639d628a0SDimitry Andric                           const SmallVectorImpl<Instruction *> &Exts,
2577a7e6055SDimitry Andric                           SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
2587a7e6055SDimitry Andric                           unsigned CreatedInstsCost = 0);
2597a7e6055SDimitry Andric     bool mergeSExts(Function &F);
2607a7e6055SDimitry Andric     bool performAddressTypePromotion(
2617a7e6055SDimitry Andric         Instruction *&Inst,
2627a7e6055SDimitry Andric         bool AllowPromotionWithoutCommonHeader,
2637a7e6055SDimitry Andric         bool HasPromoted, TypePromotionTransaction &TPT,
2647a7e6055SDimitry Andric         SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
26539d628a0SDimitry Andric     bool splitBranchCondition(Function &F);
266ff0cc061SDimitry Andric     bool simplifyOffsetableRelocate(Instruction &I);
2677a7e6055SDimitry Andric     bool splitIndirectCriticalEdges(Function &F);
26891bc56edSDimitry Andric   };
2693dac3a9bSDimitry Andric }
27091bc56edSDimitry Andric 
27191bc56edSDimitry Andric char CodeGenPrepare::ID = 0;
272302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
273d88c1a5aSDimitry Andric                       "Optimize for code generation", false, false)
274d88c1a5aSDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
275302affcbSDimitry Andric INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
27691bc56edSDimitry Andric                     "Optimize for code generation", false, false)
27791bc56edSDimitry Andric 
278d8866befSDimitry Andric FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
27991bc56edSDimitry Andric 
28091bc56edSDimitry Andric bool CodeGenPrepare::runOnFunction(Function &F) {
2813ca95b02SDimitry Andric   if (skipFunction(F))
28291bc56edSDimitry Andric     return false;
28391bc56edSDimitry Andric 
284875ed548SDimitry Andric   DL = &F.getParent()->getDataLayout();
285875ed548SDimitry Andric 
28691bc56edSDimitry Andric   bool EverMadeChange = false;
28791bc56edSDimitry Andric   // Clear per function information.
2888f0fd8f6SDimitry Andric   InsertedInsts.clear();
28991bc56edSDimitry Andric   PromotedInsts.clear();
290d88c1a5aSDimitry Andric   BFI.reset();
291d88c1a5aSDimitry Andric   BPI.reset();
29291bc56edSDimitry Andric 
29391bc56edSDimitry Andric   ModifiedDT = false;
294d8866befSDimitry Andric   if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
295d8866befSDimitry Andric     TM = &TPC->getTM<TargetMachine>();
2967a7e6055SDimitry Andric     SubtargetInfo = TM->getSubtargetImpl(F);
2977a7e6055SDimitry Andric     TLI = SubtargetInfo->getTargetLowering();
2987a7e6055SDimitry Andric     TRI = SubtargetInfo->getRegisterInfo();
2997a7e6055SDimitry Andric   }
300ff0cc061SDimitry Andric   TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
301ff0cc061SDimitry Andric   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3023ca95b02SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3037d523365SDimitry Andric   OptSize = F.optForSize();
30491bc56edSDimitry Andric 
305d88c1a5aSDimitry Andric   if (ProfileGuidedSectionPrefix) {
306d88c1a5aSDimitry Andric     ProfileSummaryInfo *PSI =
307d88c1a5aSDimitry Andric         getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3087a7e6055SDimitry Andric     if (PSI->isFunctionHotInCallGraph(&F))
309d88c1a5aSDimitry Andric       F.setSectionPrefix(".hot");
3107a7e6055SDimitry Andric     else if (PSI->isFunctionColdInCallGraph(&F))
3115517e702SDimitry Andric       F.setSectionPrefix(".unlikely");
312d88c1a5aSDimitry Andric   }
313d88c1a5aSDimitry Andric 
31491bc56edSDimitry Andric   /// This optimization identifies DIV instructions that can be
31591bc56edSDimitry Andric   /// profitably bypassed and carried out with a shorter, faster divide.
31691bc56edSDimitry Andric   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
31791bc56edSDimitry Andric     const DenseMap<unsigned int, unsigned int> &BypassWidths =
31891bc56edSDimitry Andric        TLI->getBypassSlowDivWidths();
3194d0b32cdSDimitry Andric     BasicBlock* BB = &*F.begin();
3204d0b32cdSDimitry Andric     while (BB != nullptr) {
3214d0b32cdSDimitry Andric       // bypassSlowDivision may create new BBs, but we don't want to reapply the
3224d0b32cdSDimitry Andric       // optimization to those blocks.
3234d0b32cdSDimitry Andric       BasicBlock* Next = BB->getNextNode();
3244d0b32cdSDimitry Andric       EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
3254d0b32cdSDimitry Andric       BB = Next;
3264d0b32cdSDimitry Andric     }
32791bc56edSDimitry Andric   }
32891bc56edSDimitry Andric 
32991bc56edSDimitry Andric   // Eliminate blocks that contain only PHI nodes and an
33091bc56edSDimitry Andric   // unconditional branch.
3317d523365SDimitry Andric   EverMadeChange |= eliminateMostlyEmptyBlocks(F);
33291bc56edSDimitry Andric 
33391bc56edSDimitry Andric   // llvm.dbg.value is far away from the value then iSel may not be able
33491bc56edSDimitry Andric   // handle it properly. iSel will drop llvm.dbg.value if it can not
33591bc56edSDimitry Andric   // find a node corresponding to the value.
3367d523365SDimitry Andric   EverMadeChange |= placeDbgValues(F);
33791bc56edSDimitry Andric 
3387a7e6055SDimitry Andric   if (!DisableBranchOpts)
33939d628a0SDimitry Andric     EverMadeChange |= splitBranchCondition(F);
3407a7e6055SDimitry Andric 
3417a7e6055SDimitry Andric   // Split some critical edges where one of the sources is an indirect branch,
3427a7e6055SDimitry Andric   // to help generate sane code for PHIs involving such edges.
3437a7e6055SDimitry Andric   EverMadeChange |= splitIndirectCriticalEdges(F);
34491bc56edSDimitry Andric 
34591bc56edSDimitry Andric   bool MadeChange = true;
34691bc56edSDimitry Andric   while (MadeChange) {
34791bc56edSDimitry Andric     MadeChange = false;
3487a7e6055SDimitry Andric     SeenChainsForSExt.clear();
3497a7e6055SDimitry Andric     ValToSExtendedUses.clear();
3507a7e6055SDimitry Andric     RemovedInsts.clear();
35191bc56edSDimitry Andric     for (Function::iterator I = F.begin(); I != F.end(); ) {
3527d523365SDimitry Andric       BasicBlock *BB = &*I++;
35339d628a0SDimitry Andric       bool ModifiedDTOnIteration = false;
3547d523365SDimitry Andric       MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
35539d628a0SDimitry Andric 
35639d628a0SDimitry Andric       // Restart BB iteration if the dominator tree of the Function was changed
35739d628a0SDimitry Andric       if (ModifiedDTOnIteration)
35839d628a0SDimitry Andric         break;
35991bc56edSDimitry Andric     }
3607a7e6055SDimitry Andric     if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
3617a7e6055SDimitry Andric       MadeChange |= mergeSExts(F);
3627a7e6055SDimitry Andric 
3637a7e6055SDimitry Andric     // Really free removed instructions during promotion.
3647a7e6055SDimitry Andric     for (Instruction *I : RemovedInsts)
365d8866befSDimitry Andric       I->deleteValue();
3667a7e6055SDimitry Andric 
36791bc56edSDimitry Andric     EverMadeChange |= MadeChange;
36891bc56edSDimitry Andric   }
36991bc56edSDimitry Andric 
37091bc56edSDimitry Andric   SunkAddrs.clear();
37191bc56edSDimitry Andric 
37291bc56edSDimitry Andric   if (!DisableBranchOpts) {
37391bc56edSDimitry Andric     MadeChange = false;
37491bc56edSDimitry Andric     SmallPtrSet<BasicBlock*, 8> WorkList;
37539d628a0SDimitry Andric     for (BasicBlock &BB : F) {
37639d628a0SDimitry Andric       SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
37739d628a0SDimitry Andric       MadeChange |= ConstantFoldTerminator(&BB, true);
37891bc56edSDimitry Andric       if (!MadeChange) continue;
37991bc56edSDimitry Andric 
38091bc56edSDimitry Andric       for (SmallVectorImpl<BasicBlock*>::iterator
38191bc56edSDimitry Andric              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
38291bc56edSDimitry Andric         if (pred_begin(*II) == pred_end(*II))
38391bc56edSDimitry Andric           WorkList.insert(*II);
38491bc56edSDimitry Andric     }
38591bc56edSDimitry Andric 
38691bc56edSDimitry Andric     // Delete the dead blocks and any of their dead successors.
38791bc56edSDimitry Andric     MadeChange |= !WorkList.empty();
38891bc56edSDimitry Andric     while (!WorkList.empty()) {
38991bc56edSDimitry Andric       BasicBlock *BB = *WorkList.begin();
39091bc56edSDimitry Andric       WorkList.erase(BB);
39191bc56edSDimitry Andric       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
39291bc56edSDimitry Andric 
39391bc56edSDimitry Andric       DeleteDeadBlock(BB);
39491bc56edSDimitry Andric 
39591bc56edSDimitry Andric       for (SmallVectorImpl<BasicBlock*>::iterator
39691bc56edSDimitry Andric              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
39791bc56edSDimitry Andric         if (pred_begin(*II) == pred_end(*II))
39891bc56edSDimitry Andric           WorkList.insert(*II);
39991bc56edSDimitry Andric     }
40091bc56edSDimitry Andric 
40191bc56edSDimitry Andric     // Merge pairs of basic blocks with unconditional branches, connected by
40291bc56edSDimitry Andric     // a single edge.
40391bc56edSDimitry Andric     if (EverMadeChange || MadeChange)
4047d523365SDimitry Andric       MadeChange |= eliminateFallThrough(F);
40591bc56edSDimitry Andric 
40691bc56edSDimitry Andric     EverMadeChange |= MadeChange;
40791bc56edSDimitry Andric   }
40891bc56edSDimitry Andric 
409ff0cc061SDimitry Andric   if (!DisableGCOpts) {
410ff0cc061SDimitry Andric     SmallVector<Instruction *, 2> Statepoints;
411ff0cc061SDimitry Andric     for (BasicBlock &BB : F)
412ff0cc061SDimitry Andric       for (Instruction &I : BB)
413ff0cc061SDimitry Andric         if (isStatepoint(I))
414ff0cc061SDimitry Andric           Statepoints.push_back(&I);
415ff0cc061SDimitry Andric     for (auto &I : Statepoints)
416ff0cc061SDimitry Andric       EverMadeChange |= simplifyOffsetableRelocate(*I);
417ff0cc061SDimitry Andric   }
41891bc56edSDimitry Andric 
41991bc56edSDimitry Andric   return EverMadeChange;
42091bc56edSDimitry Andric }
42191bc56edSDimitry Andric 
4227d523365SDimitry Andric /// Merge basic blocks which are connected by a single edge, where one of the
4237d523365SDimitry Andric /// basic blocks has a single successor pointing to the other basic block,
4247d523365SDimitry Andric /// which has a single predecessor.
4257d523365SDimitry Andric bool CodeGenPrepare::eliminateFallThrough(Function &F) {
42691bc56edSDimitry Andric   bool Changed = false;
42791bc56edSDimitry Andric   // Scan all of the blocks in the function, except for the entry block.
42891bc56edSDimitry Andric   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
4297d523365SDimitry Andric     BasicBlock *BB = &*I++;
43091bc56edSDimitry Andric     // If the destination block has a single pred, then this is a trivial
43191bc56edSDimitry Andric     // edge, just collapse it.
43291bc56edSDimitry Andric     BasicBlock *SinglePred = BB->getSinglePredecessor();
43391bc56edSDimitry Andric 
43491bc56edSDimitry Andric     // Don't merge if BB's address is taken.
43591bc56edSDimitry Andric     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
43691bc56edSDimitry Andric 
43791bc56edSDimitry Andric     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
43891bc56edSDimitry Andric     if (Term && !Term->isConditional()) {
43991bc56edSDimitry Andric       Changed = true;
44091bc56edSDimitry Andric       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
44191bc56edSDimitry Andric       // Remember if SinglePred was the entry block of the function.
44291bc56edSDimitry Andric       // If so, we will need to move BB back to the entry position.
44391bc56edSDimitry Andric       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
444ff0cc061SDimitry Andric       MergeBasicBlockIntoOnlyPred(BB, nullptr);
44591bc56edSDimitry Andric 
44691bc56edSDimitry Andric       if (isEntry && BB != &BB->getParent()->getEntryBlock())
44791bc56edSDimitry Andric         BB->moveBefore(&BB->getParent()->getEntryBlock());
44891bc56edSDimitry Andric 
44991bc56edSDimitry Andric       // We have erased a block. Update the iterator.
4507d523365SDimitry Andric       I = BB->getIterator();
45191bc56edSDimitry Andric     }
45291bc56edSDimitry Andric   }
45391bc56edSDimitry Andric   return Changed;
45491bc56edSDimitry Andric }
45591bc56edSDimitry Andric 
456d88c1a5aSDimitry Andric /// Find a destination block from BB if BB is mergeable empty block.
457d88c1a5aSDimitry Andric BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
458d88c1a5aSDimitry Andric   // If this block doesn't end with an uncond branch, ignore it.
459d88c1a5aSDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
460d88c1a5aSDimitry Andric   if (!BI || !BI->isUnconditional())
461d88c1a5aSDimitry Andric     return nullptr;
462d88c1a5aSDimitry Andric 
463d88c1a5aSDimitry Andric   // If the instruction before the branch (skipping debug info) isn't a phi
464d88c1a5aSDimitry Andric   // node, then other stuff is happening here.
465d88c1a5aSDimitry Andric   BasicBlock::iterator BBI = BI->getIterator();
466d88c1a5aSDimitry Andric   if (BBI != BB->begin()) {
467d88c1a5aSDimitry Andric     --BBI;
468d88c1a5aSDimitry Andric     while (isa<DbgInfoIntrinsic>(BBI)) {
469d88c1a5aSDimitry Andric       if (BBI == BB->begin())
470d88c1a5aSDimitry Andric         break;
471d88c1a5aSDimitry Andric       --BBI;
472d88c1a5aSDimitry Andric     }
473d88c1a5aSDimitry Andric     if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
474d88c1a5aSDimitry Andric       return nullptr;
475d88c1a5aSDimitry Andric   }
476d88c1a5aSDimitry Andric 
477d88c1a5aSDimitry Andric   // Do not break infinite loops.
478d88c1a5aSDimitry Andric   BasicBlock *DestBB = BI->getSuccessor(0);
479d88c1a5aSDimitry Andric   if (DestBB == BB)
480d88c1a5aSDimitry Andric     return nullptr;
481d88c1a5aSDimitry Andric 
482d88c1a5aSDimitry Andric   if (!canMergeBlocks(BB, DestBB))
483d88c1a5aSDimitry Andric     DestBB = nullptr;
484d88c1a5aSDimitry Andric 
485d88c1a5aSDimitry Andric   return DestBB;
486d88c1a5aSDimitry Andric }
487d88c1a5aSDimitry Andric 
4887a7e6055SDimitry Andric // Return the unique indirectbr predecessor of a block. This may return null
4897a7e6055SDimitry Andric // even if such a predecessor exists, if it's not useful for splitting.
4907a7e6055SDimitry Andric // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
4917a7e6055SDimitry Andric // predecessors of BB.
4927a7e6055SDimitry Andric static BasicBlock *
4937a7e6055SDimitry Andric findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
4947a7e6055SDimitry Andric   // If the block doesn't have any PHIs, we don't care about it, since there's
4957a7e6055SDimitry Andric   // no point in splitting it.
4967a7e6055SDimitry Andric   PHINode *PN = dyn_cast<PHINode>(BB->begin());
4977a7e6055SDimitry Andric   if (!PN)
4987a7e6055SDimitry Andric     return nullptr;
4997a7e6055SDimitry Andric 
5007a7e6055SDimitry Andric   // Verify we have exactly one IBR predecessor.
5017a7e6055SDimitry Andric   // Conservatively bail out if one of the other predecessors is not a "regular"
5027a7e6055SDimitry Andric   // terminator (that is, not a switch or a br).
5037a7e6055SDimitry Andric   BasicBlock *IBB = nullptr;
5047a7e6055SDimitry Andric   for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
5057a7e6055SDimitry Andric     BasicBlock *PredBB = PN->getIncomingBlock(Pred);
5067a7e6055SDimitry Andric     TerminatorInst *PredTerm = PredBB->getTerminator();
5077a7e6055SDimitry Andric     switch (PredTerm->getOpcode()) {
5087a7e6055SDimitry Andric     case Instruction::IndirectBr:
5097a7e6055SDimitry Andric       if (IBB)
5107a7e6055SDimitry Andric         return nullptr;
5117a7e6055SDimitry Andric       IBB = PredBB;
5127a7e6055SDimitry Andric       break;
5137a7e6055SDimitry Andric     case Instruction::Br:
5147a7e6055SDimitry Andric     case Instruction::Switch:
5157a7e6055SDimitry Andric       OtherPreds.push_back(PredBB);
5167a7e6055SDimitry Andric       continue;
5177a7e6055SDimitry Andric     default:
5187a7e6055SDimitry Andric       return nullptr;
5197a7e6055SDimitry Andric     }
5207a7e6055SDimitry Andric   }
5217a7e6055SDimitry Andric 
5227a7e6055SDimitry Andric   return IBB;
5237a7e6055SDimitry Andric }
5247a7e6055SDimitry Andric 
5257a7e6055SDimitry Andric // Split critical edges where the source of the edge is an indirectbr
5267a7e6055SDimitry Andric // instruction. This isn't always possible, but we can handle some easy cases.
5277a7e6055SDimitry Andric // This is useful because MI is unable to split such critical edges,
5287a7e6055SDimitry Andric // which means it will not be able to sink instructions along those edges.
5297a7e6055SDimitry Andric // This is especially painful for indirect branches with many successors, where
5307a7e6055SDimitry Andric // we end up having to prepare all outgoing values in the origin block.
5317a7e6055SDimitry Andric //
5327a7e6055SDimitry Andric // Our normal algorithm for splitting critical edges requires us to update
5337a7e6055SDimitry Andric // the outgoing edges of the edge origin block, but for an indirectbr this
5347a7e6055SDimitry Andric // is hard, since it would require finding and updating the block addresses
5357a7e6055SDimitry Andric // the indirect branch uses. But if a block only has a single indirectbr
5367a7e6055SDimitry Andric // predecessor, with the others being regular branches, we can do it in a
5377a7e6055SDimitry Andric // different way.
5387a7e6055SDimitry Andric // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
5397a7e6055SDimitry Andric // We can split D into D0 and D1, where D0 contains only the PHIs from D,
5407a7e6055SDimitry Andric // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
5417a7e6055SDimitry Andric // create the following structure:
5427a7e6055SDimitry Andric // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
5437a7e6055SDimitry Andric bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
5447a7e6055SDimitry Andric   // Check whether the function has any indirectbrs, and collect which blocks
5457a7e6055SDimitry Andric   // they may jump to. Since most functions don't have indirect branches,
5467a7e6055SDimitry Andric   // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
5477a7e6055SDimitry Andric   SmallSetVector<BasicBlock *, 16> Targets;
5487a7e6055SDimitry Andric   for (auto &BB : F) {
5497a7e6055SDimitry Andric     auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
5507a7e6055SDimitry Andric     if (!IBI)
5517a7e6055SDimitry Andric       continue;
5527a7e6055SDimitry Andric 
5537a7e6055SDimitry Andric     for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
5547a7e6055SDimitry Andric       Targets.insert(IBI->getSuccessor(Succ));
5557a7e6055SDimitry Andric   }
5567a7e6055SDimitry Andric 
5577a7e6055SDimitry Andric   if (Targets.empty())
5587a7e6055SDimitry Andric     return false;
5597a7e6055SDimitry Andric 
5607a7e6055SDimitry Andric   bool Changed = false;
5617a7e6055SDimitry Andric   for (BasicBlock *Target : Targets) {
5627a7e6055SDimitry Andric     SmallVector<BasicBlock *, 16> OtherPreds;
5637a7e6055SDimitry Andric     BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
5647a7e6055SDimitry Andric     // If we did not found an indirectbr, or the indirectbr is the only
5657a7e6055SDimitry Andric     // incoming edge, this isn't the kind of edge we're looking for.
5667a7e6055SDimitry Andric     if (!IBRPred || OtherPreds.empty())
5677a7e6055SDimitry Andric       continue;
5687a7e6055SDimitry Andric 
5697a7e6055SDimitry Andric     // Don't even think about ehpads/landingpads.
5707a7e6055SDimitry Andric     Instruction *FirstNonPHI = Target->getFirstNonPHI();
5717a7e6055SDimitry Andric     if (FirstNonPHI->isEHPad() || Target->isLandingPad())
5727a7e6055SDimitry Andric       continue;
5737a7e6055SDimitry Andric 
5747a7e6055SDimitry Andric     BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
5757a7e6055SDimitry Andric     // It's possible Target was its own successor through an indirectbr.
5767a7e6055SDimitry Andric     // In this case, the indirectbr now comes from BodyBlock.
5777a7e6055SDimitry Andric     if (IBRPred == Target)
5787a7e6055SDimitry Andric       IBRPred = BodyBlock;
5797a7e6055SDimitry Andric 
5807a7e6055SDimitry Andric     // At this point Target only has PHIs, and BodyBlock has the rest of the
5817a7e6055SDimitry Andric     // block's body. Create a copy of Target that will be used by the "direct"
5827a7e6055SDimitry Andric     // preds.
5837a7e6055SDimitry Andric     ValueToValueMapTy VMap;
5847a7e6055SDimitry Andric     BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
5857a7e6055SDimitry Andric 
5866bc11b14SDimitry Andric     for (BasicBlock *Pred : OtherPreds) {
5876bc11b14SDimitry Andric       // If the target is a loop to itself, then the terminator of the split
5886bc11b14SDimitry Andric       // block needs to be updated.
5896bc11b14SDimitry Andric       if (Pred == Target)
5906bc11b14SDimitry Andric         BodyBlock->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
5916bc11b14SDimitry Andric       else
5927a7e6055SDimitry Andric         Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
5936bc11b14SDimitry Andric     }
5947a7e6055SDimitry Andric 
5957a7e6055SDimitry Andric     // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
5967a7e6055SDimitry Andric     // they are clones, so the number of PHIs are the same.
5977a7e6055SDimitry Andric     // (a) Remove the edge coming from IBRPred from the "Direct" PHI
5987a7e6055SDimitry Andric     // (b) Leave that as the only edge in the "Indirect" PHI.
5997a7e6055SDimitry Andric     // (c) Merge the two in the body block.
6007a7e6055SDimitry Andric     BasicBlock::iterator Indirect = Target->begin(),
6017a7e6055SDimitry Andric                          End = Target->getFirstNonPHI()->getIterator();
6027a7e6055SDimitry Andric     BasicBlock::iterator Direct = DirectSucc->begin();
6037a7e6055SDimitry Andric     BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
6047a7e6055SDimitry Andric 
6057a7e6055SDimitry Andric     assert(&*End == Target->getTerminator() &&
6067a7e6055SDimitry Andric            "Block was expected to only contain PHIs");
6077a7e6055SDimitry Andric 
6087a7e6055SDimitry Andric     while (Indirect != End) {
6097a7e6055SDimitry Andric       PHINode *DirPHI = cast<PHINode>(Direct);
6107a7e6055SDimitry Andric       PHINode *IndPHI = cast<PHINode>(Indirect);
6117a7e6055SDimitry Andric 
6127a7e6055SDimitry Andric       // Now, clean up - the direct block shouldn't get the indirect value,
6137a7e6055SDimitry Andric       // and vice versa.
6147a7e6055SDimitry Andric       DirPHI->removeIncomingValue(IBRPred);
6157a7e6055SDimitry Andric       Direct++;
6167a7e6055SDimitry Andric 
6177a7e6055SDimitry Andric       // Advance the pointer here, to avoid invalidation issues when the old
6187a7e6055SDimitry Andric       // PHI is erased.
6197a7e6055SDimitry Andric       Indirect++;
6207a7e6055SDimitry Andric 
6217a7e6055SDimitry Andric       PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
6227a7e6055SDimitry Andric       NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
6237a7e6055SDimitry Andric                              IBRPred);
6247a7e6055SDimitry Andric 
6257a7e6055SDimitry Andric       // Create a PHI in the body block, to merge the direct and indirect
6267a7e6055SDimitry Andric       // predecessors.
6277a7e6055SDimitry Andric       PHINode *MergePHI =
6287a7e6055SDimitry Andric           PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
6297a7e6055SDimitry Andric       MergePHI->addIncoming(NewIndPHI, Target);
6307a7e6055SDimitry Andric       MergePHI->addIncoming(DirPHI, DirectSucc);
6317a7e6055SDimitry Andric 
6327a7e6055SDimitry Andric       IndPHI->replaceAllUsesWith(MergePHI);
6337a7e6055SDimitry Andric       IndPHI->eraseFromParent();
6347a7e6055SDimitry Andric     }
6357a7e6055SDimitry Andric 
6367a7e6055SDimitry Andric     Changed = true;
6377a7e6055SDimitry Andric   }
6387a7e6055SDimitry Andric 
6397a7e6055SDimitry Andric   return Changed;
6407a7e6055SDimitry Andric }
6417a7e6055SDimitry Andric 
6427d523365SDimitry Andric /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
6437d523365SDimitry Andric /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
6447d523365SDimitry Andric /// edges in ways that are non-optimal for isel. Start by eliminating these
6457d523365SDimitry Andric /// blocks so we can split them the way we want them.
6467d523365SDimitry Andric bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
6473ca95b02SDimitry Andric   SmallPtrSet<BasicBlock *, 16> Preheaders;
6483ca95b02SDimitry Andric   SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
6493ca95b02SDimitry Andric   while (!LoopList.empty()) {
6503ca95b02SDimitry Andric     Loop *L = LoopList.pop_back_val();
6513ca95b02SDimitry Andric     LoopList.insert(LoopList.end(), L->begin(), L->end());
6523ca95b02SDimitry Andric     if (BasicBlock *Preheader = L->getLoopPreheader())
6533ca95b02SDimitry Andric       Preheaders.insert(Preheader);
6543ca95b02SDimitry Andric   }
6553ca95b02SDimitry Andric 
65691bc56edSDimitry Andric   bool MadeChange = false;
65791bc56edSDimitry Andric   // Note that this intentionally skips the entry block.
65891bc56edSDimitry Andric   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
6597d523365SDimitry Andric     BasicBlock *BB = &*I++;
660d88c1a5aSDimitry Andric     BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
661d88c1a5aSDimitry Andric     if (!DestBB ||
662d88c1a5aSDimitry Andric         !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
6633ca95b02SDimitry Andric       continue;
6643ca95b02SDimitry Andric 
6657d523365SDimitry Andric     eliminateMostlyEmptyBlock(BB);
66691bc56edSDimitry Andric     MadeChange = true;
66791bc56edSDimitry Andric   }
66891bc56edSDimitry Andric   return MadeChange;
66991bc56edSDimitry Andric }
67091bc56edSDimitry Andric 
671d88c1a5aSDimitry Andric bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
672d88c1a5aSDimitry Andric                                                    BasicBlock *DestBB,
673d88c1a5aSDimitry Andric                                                    bool isPreheader) {
674d88c1a5aSDimitry Andric   // Do not delete loop preheaders if doing so would create a critical edge.
675d88c1a5aSDimitry Andric   // Loop preheaders can be good locations to spill registers. If the
676d88c1a5aSDimitry Andric   // preheader is deleted and we create a critical edge, registers may be
677d88c1a5aSDimitry Andric   // spilled in the loop body instead.
678d88c1a5aSDimitry Andric   if (!DisablePreheaderProtect && isPreheader &&
679d88c1a5aSDimitry Andric       !(BB->getSinglePredecessor() &&
680d88c1a5aSDimitry Andric         BB->getSinglePredecessor()->getSingleSuccessor()))
681d88c1a5aSDimitry Andric     return false;
682d88c1a5aSDimitry Andric 
683d88c1a5aSDimitry Andric   // Try to skip merging if the unique predecessor of BB is terminated by a
684d88c1a5aSDimitry Andric   // switch or indirect branch instruction, and BB is used as an incoming block
685d88c1a5aSDimitry Andric   // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
686d88c1a5aSDimitry Andric   // add COPY instructions in the predecessor of BB instead of BB (if it is not
687d88c1a5aSDimitry Andric   // merged). Note that the critical edge created by merging such blocks wont be
688d88c1a5aSDimitry Andric   // split in MachineSink because the jump table is not analyzable. By keeping
689d88c1a5aSDimitry Andric   // such empty block (BB), ISel will place COPY instructions in BB, not in the
690d88c1a5aSDimitry Andric   // predecessor of BB.
691d88c1a5aSDimitry Andric   BasicBlock *Pred = BB->getUniquePredecessor();
692d88c1a5aSDimitry Andric   if (!Pred ||
693d88c1a5aSDimitry Andric       !(isa<SwitchInst>(Pred->getTerminator()) ||
694d88c1a5aSDimitry Andric         isa<IndirectBrInst>(Pred->getTerminator())))
695d88c1a5aSDimitry Andric     return true;
696d88c1a5aSDimitry Andric 
697d88c1a5aSDimitry Andric   if (BB->getTerminator() != BB->getFirstNonPHI())
698d88c1a5aSDimitry Andric     return true;
699d88c1a5aSDimitry Andric 
700d88c1a5aSDimitry Andric   // We use a simple cost heuristic which determine skipping merging is
701d88c1a5aSDimitry Andric   // profitable if the cost of skipping merging is less than the cost of
702d88c1a5aSDimitry Andric   // merging : Cost(skipping merging) < Cost(merging BB), where the
703d88c1a5aSDimitry Andric   // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
704d88c1a5aSDimitry Andric   // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
705d88c1a5aSDimitry Andric   // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
706d88c1a5aSDimitry Andric   //   Freq(Pred) / Freq(BB) > 2.
707d88c1a5aSDimitry Andric   // Note that if there are multiple empty blocks sharing the same incoming
708d88c1a5aSDimitry Andric   // value for the PHIs in the DestBB, we consider them together. In such
709d88c1a5aSDimitry Andric   // case, Cost(merging BB) will be the sum of their frequencies.
710d88c1a5aSDimitry Andric 
711d88c1a5aSDimitry Andric   if (!isa<PHINode>(DestBB->begin()))
712d88c1a5aSDimitry Andric     return true;
713d88c1a5aSDimitry Andric 
714d88c1a5aSDimitry Andric   SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
715d88c1a5aSDimitry Andric 
716d88c1a5aSDimitry Andric   // Find all other incoming blocks from which incoming values of all PHIs in
717d88c1a5aSDimitry Andric   // DestBB are the same as the ones from BB.
718d88c1a5aSDimitry Andric   for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
719d88c1a5aSDimitry Andric        ++PI) {
720d88c1a5aSDimitry Andric     BasicBlock *DestBBPred = *PI;
721d88c1a5aSDimitry Andric     if (DestBBPred == BB)
722d88c1a5aSDimitry Andric       continue;
723d88c1a5aSDimitry Andric 
724d88c1a5aSDimitry Andric     bool HasAllSameValue = true;
725d88c1a5aSDimitry Andric     BasicBlock::const_iterator DestBBI = DestBB->begin();
726d88c1a5aSDimitry Andric     while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
727d88c1a5aSDimitry Andric       if (DestPN->getIncomingValueForBlock(BB) !=
728d88c1a5aSDimitry Andric           DestPN->getIncomingValueForBlock(DestBBPred)) {
729d88c1a5aSDimitry Andric         HasAllSameValue = false;
730d88c1a5aSDimitry Andric         break;
731d88c1a5aSDimitry Andric       }
732d88c1a5aSDimitry Andric     }
733d88c1a5aSDimitry Andric     if (HasAllSameValue)
734d88c1a5aSDimitry Andric       SameIncomingValueBBs.insert(DestBBPred);
735d88c1a5aSDimitry Andric   }
736d88c1a5aSDimitry Andric 
737d88c1a5aSDimitry Andric   // See if all BB's incoming values are same as the value from Pred. In this
738d88c1a5aSDimitry Andric   // case, no reason to skip merging because COPYs are expected to be place in
739d88c1a5aSDimitry Andric   // Pred already.
740d88c1a5aSDimitry Andric   if (SameIncomingValueBBs.count(Pred))
741d88c1a5aSDimitry Andric     return true;
742d88c1a5aSDimitry Andric 
743d88c1a5aSDimitry Andric   if (!BFI) {
744d88c1a5aSDimitry Andric     Function &F = *BB->getParent();
745d88c1a5aSDimitry Andric     LoopInfo LI{DominatorTree(F)};
746d88c1a5aSDimitry Andric     BPI.reset(new BranchProbabilityInfo(F, LI));
747d88c1a5aSDimitry Andric     BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
748d88c1a5aSDimitry Andric   }
749d88c1a5aSDimitry Andric 
750d88c1a5aSDimitry Andric   BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
751d88c1a5aSDimitry Andric   BlockFrequency BBFreq = BFI->getBlockFreq(BB);
752d88c1a5aSDimitry Andric 
753d88c1a5aSDimitry Andric   for (auto SameValueBB : SameIncomingValueBBs)
754d88c1a5aSDimitry Andric     if (SameValueBB->getUniquePredecessor() == Pred &&
755d88c1a5aSDimitry Andric         DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
756d88c1a5aSDimitry Andric       BBFreq += BFI->getBlockFreq(SameValueBB);
757d88c1a5aSDimitry Andric 
758d88c1a5aSDimitry Andric   return PredFreq.getFrequency() <=
759d88c1a5aSDimitry Andric          BBFreq.getFrequency() * FreqRatioToSkipMerge;
760d88c1a5aSDimitry Andric }
761d88c1a5aSDimitry Andric 
7627d523365SDimitry Andric /// Return true if we can merge BB into DestBB if there is a single
7637d523365SDimitry Andric /// unconditional branch between them, and BB contains no other non-phi
76491bc56edSDimitry Andric /// instructions.
7657d523365SDimitry Andric bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
76691bc56edSDimitry Andric                                     const BasicBlock *DestBB) const {
76791bc56edSDimitry Andric   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
76891bc56edSDimitry Andric   // the successor.  If there are more complex condition (e.g. preheaders),
76991bc56edSDimitry Andric   // don't mess around with them.
77091bc56edSDimitry Andric   BasicBlock::const_iterator BBI = BB->begin();
77191bc56edSDimitry Andric   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
77291bc56edSDimitry Andric     for (const User *U : PN->users()) {
77391bc56edSDimitry Andric       const Instruction *UI = cast<Instruction>(U);
77491bc56edSDimitry Andric       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
77591bc56edSDimitry Andric         return false;
77691bc56edSDimitry Andric       // If User is inside DestBB block and it is a PHINode then check
77791bc56edSDimitry Andric       // incoming value. If incoming value is not from BB then this is
77891bc56edSDimitry Andric       // a complex condition (e.g. preheaders) we want to avoid here.
77991bc56edSDimitry Andric       if (UI->getParent() == DestBB) {
78091bc56edSDimitry Andric         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
78191bc56edSDimitry Andric           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
78291bc56edSDimitry Andric             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
78391bc56edSDimitry Andric             if (Insn && Insn->getParent() == BB &&
78491bc56edSDimitry Andric                 Insn->getParent() != UPN->getIncomingBlock(I))
78591bc56edSDimitry Andric               return false;
78691bc56edSDimitry Andric           }
78791bc56edSDimitry Andric       }
78891bc56edSDimitry Andric     }
78991bc56edSDimitry Andric   }
79091bc56edSDimitry Andric 
79191bc56edSDimitry Andric   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
79291bc56edSDimitry Andric   // and DestBB may have conflicting incoming values for the block.  If so, we
79391bc56edSDimitry Andric   // can't merge the block.
79491bc56edSDimitry Andric   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
79591bc56edSDimitry Andric   if (!DestBBPN) return true;  // no conflict.
79691bc56edSDimitry Andric 
79791bc56edSDimitry Andric   // Collect the preds of BB.
79891bc56edSDimitry Andric   SmallPtrSet<const BasicBlock*, 16> BBPreds;
79991bc56edSDimitry Andric   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
80091bc56edSDimitry Andric     // It is faster to get preds from a PHI than with pred_iterator.
80191bc56edSDimitry Andric     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
80291bc56edSDimitry Andric       BBPreds.insert(BBPN->getIncomingBlock(i));
80391bc56edSDimitry Andric   } else {
80491bc56edSDimitry Andric     BBPreds.insert(pred_begin(BB), pred_end(BB));
80591bc56edSDimitry Andric   }
80691bc56edSDimitry Andric 
80791bc56edSDimitry Andric   // Walk the preds of DestBB.
80891bc56edSDimitry Andric   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
80991bc56edSDimitry Andric     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
81091bc56edSDimitry Andric     if (BBPreds.count(Pred)) {   // Common predecessor?
81191bc56edSDimitry Andric       BBI = DestBB->begin();
81291bc56edSDimitry Andric       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
81391bc56edSDimitry Andric         const Value *V1 = PN->getIncomingValueForBlock(Pred);
81491bc56edSDimitry Andric         const Value *V2 = PN->getIncomingValueForBlock(BB);
81591bc56edSDimitry Andric 
81691bc56edSDimitry Andric         // If V2 is a phi node in BB, look up what the mapped value will be.
81791bc56edSDimitry Andric         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
81891bc56edSDimitry Andric           if (V2PN->getParent() == BB)
81991bc56edSDimitry Andric             V2 = V2PN->getIncomingValueForBlock(Pred);
82091bc56edSDimitry Andric 
82191bc56edSDimitry Andric         // If there is a conflict, bail out.
82291bc56edSDimitry Andric         if (V1 != V2) return false;
82391bc56edSDimitry Andric       }
82491bc56edSDimitry Andric     }
82591bc56edSDimitry Andric   }
82691bc56edSDimitry Andric 
82791bc56edSDimitry Andric   return true;
82891bc56edSDimitry Andric }
82991bc56edSDimitry Andric 
83091bc56edSDimitry Andric 
8317d523365SDimitry Andric /// Eliminate a basic block that has only phi's and an unconditional branch in
8327d523365SDimitry Andric /// it.
8337d523365SDimitry Andric void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
83491bc56edSDimitry Andric   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
83591bc56edSDimitry Andric   BasicBlock *DestBB = BI->getSuccessor(0);
83691bc56edSDimitry Andric 
83791bc56edSDimitry Andric   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
83891bc56edSDimitry Andric 
83991bc56edSDimitry Andric   // If the destination block has a single pred, then this is a trivial edge,
84091bc56edSDimitry Andric   // just collapse it.
84191bc56edSDimitry Andric   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
84291bc56edSDimitry Andric     if (SinglePred != DestBB) {
84391bc56edSDimitry Andric       // Remember if SinglePred was the entry block of the function.  If so, we
84491bc56edSDimitry Andric       // will need to move BB back to the entry position.
84591bc56edSDimitry Andric       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
846ff0cc061SDimitry Andric       MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
84791bc56edSDimitry Andric 
84891bc56edSDimitry Andric       if (isEntry && BB != &BB->getParent()->getEntryBlock())
84991bc56edSDimitry Andric         BB->moveBefore(&BB->getParent()->getEntryBlock());
85091bc56edSDimitry Andric 
85191bc56edSDimitry Andric       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
85291bc56edSDimitry Andric       return;
85391bc56edSDimitry Andric     }
85491bc56edSDimitry Andric   }
85591bc56edSDimitry Andric 
85691bc56edSDimitry Andric   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
85791bc56edSDimitry Andric   // to handle the new incoming edges it is about to have.
85891bc56edSDimitry Andric   PHINode *PN;
85991bc56edSDimitry Andric   for (BasicBlock::iterator BBI = DestBB->begin();
86091bc56edSDimitry Andric        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
86191bc56edSDimitry Andric     // Remove the incoming value for BB, and remember it.
86291bc56edSDimitry Andric     Value *InVal = PN->removeIncomingValue(BB, false);
86391bc56edSDimitry Andric 
86491bc56edSDimitry Andric     // Two options: either the InVal is a phi node defined in BB or it is some
86591bc56edSDimitry Andric     // value that dominates BB.
86691bc56edSDimitry Andric     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
86791bc56edSDimitry Andric     if (InValPhi && InValPhi->getParent() == BB) {
86891bc56edSDimitry Andric       // Add all of the input values of the input PHI as inputs of this phi.
86991bc56edSDimitry Andric       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
87091bc56edSDimitry Andric         PN->addIncoming(InValPhi->getIncomingValue(i),
87191bc56edSDimitry Andric                         InValPhi->getIncomingBlock(i));
87291bc56edSDimitry Andric     } else {
87391bc56edSDimitry Andric       // Otherwise, add one instance of the dominating value for each edge that
87491bc56edSDimitry Andric       // we will be adding.
87591bc56edSDimitry Andric       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
87691bc56edSDimitry Andric         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
87791bc56edSDimitry Andric           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
87891bc56edSDimitry Andric       } else {
87991bc56edSDimitry Andric         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
88091bc56edSDimitry Andric           PN->addIncoming(InVal, *PI);
88191bc56edSDimitry Andric       }
88291bc56edSDimitry Andric     }
88391bc56edSDimitry Andric   }
88491bc56edSDimitry Andric 
88591bc56edSDimitry Andric   // The PHIs are now updated, change everything that refers to BB to use
88691bc56edSDimitry Andric   // DestBB and remove BB.
88791bc56edSDimitry Andric   BB->replaceAllUsesWith(DestBB);
88891bc56edSDimitry Andric   BB->eraseFromParent();
88991bc56edSDimitry Andric   ++NumBlocksElim;
89091bc56edSDimitry Andric 
89191bc56edSDimitry Andric   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
89291bc56edSDimitry Andric }
89391bc56edSDimitry Andric 
894ff0cc061SDimitry Andric // Computes a map of base pointer relocation instructions to corresponding
895ff0cc061SDimitry Andric // derived pointer relocation instructions given a vector of all relocate calls
896ff0cc061SDimitry Andric static void computeBaseDerivedRelocateMap(
8974d0b32cdSDimitry Andric     const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
8984d0b32cdSDimitry Andric     DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
8994d0b32cdSDimitry Andric         &RelocateInstMap) {
900ff0cc061SDimitry Andric   // Collect information in two maps: one primarily for locating the base object
901ff0cc061SDimitry Andric   // while filling the second map; the second map is the final structure holding
902ff0cc061SDimitry Andric   // a mapping between Base and corresponding Derived relocate calls
9034d0b32cdSDimitry Andric   DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
9044d0b32cdSDimitry Andric   for (auto *ThisRelocate : AllRelocateCalls) {
9054d0b32cdSDimitry Andric     auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
9064d0b32cdSDimitry Andric                             ThisRelocate->getDerivedPtrIndex());
9074d0b32cdSDimitry Andric     RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
908ff0cc061SDimitry Andric   }
909ff0cc061SDimitry Andric   for (auto &Item : RelocateIdxMap) {
910ff0cc061SDimitry Andric     std::pair<unsigned, unsigned> Key = Item.first;
911ff0cc061SDimitry Andric     if (Key.first == Key.second)
912ff0cc061SDimitry Andric       // Base relocation: nothing to insert
913ff0cc061SDimitry Andric       continue;
914ff0cc061SDimitry Andric 
9154d0b32cdSDimitry Andric     GCRelocateInst *I = Item.second;
916ff0cc061SDimitry Andric     auto BaseKey = std::make_pair(Key.first, Key.first);
917ff0cc061SDimitry Andric 
918ff0cc061SDimitry Andric     // We're iterating over RelocateIdxMap so we cannot modify it.
919ff0cc061SDimitry Andric     auto MaybeBase = RelocateIdxMap.find(BaseKey);
920ff0cc061SDimitry Andric     if (MaybeBase == RelocateIdxMap.end())
921ff0cc061SDimitry Andric       // TODO: We might want to insert a new base object relocate and gep off
922ff0cc061SDimitry Andric       // that, if there are enough derived object relocates.
923ff0cc061SDimitry Andric       continue;
924ff0cc061SDimitry Andric 
925ff0cc061SDimitry Andric     RelocateInstMap[MaybeBase->second].push_back(I);
926ff0cc061SDimitry Andric   }
927ff0cc061SDimitry Andric }
928ff0cc061SDimitry Andric 
929ff0cc061SDimitry Andric // Accepts a GEP and extracts the operands into a vector provided they're all
930ff0cc061SDimitry Andric // small integer constants
931ff0cc061SDimitry Andric static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
932ff0cc061SDimitry Andric                                           SmallVectorImpl<Value *> &OffsetV) {
933ff0cc061SDimitry Andric   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
934ff0cc061SDimitry Andric     // Only accept small constant integer operands
935ff0cc061SDimitry Andric     auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
936ff0cc061SDimitry Andric     if (!Op || Op->getZExtValue() > 20)
937ff0cc061SDimitry Andric       return false;
938ff0cc061SDimitry Andric   }
939ff0cc061SDimitry Andric 
940ff0cc061SDimitry Andric   for (unsigned i = 1; i < GEP->getNumOperands(); i++)
941ff0cc061SDimitry Andric     OffsetV.push_back(GEP->getOperand(i));
942ff0cc061SDimitry Andric   return true;
943ff0cc061SDimitry Andric }
944ff0cc061SDimitry Andric 
945ff0cc061SDimitry Andric // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
946ff0cc061SDimitry Andric // replace, computes a replacement, and affects it.
947ff0cc061SDimitry Andric static bool
9484d0b32cdSDimitry Andric simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
9494d0b32cdSDimitry Andric                           const SmallVectorImpl<GCRelocateInst *> &Targets) {
950ff0cc061SDimitry Andric   bool MadeChange = false;
9514d0b32cdSDimitry Andric   for (GCRelocateInst *ToReplace : Targets) {
9524d0b32cdSDimitry Andric     assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
953ff0cc061SDimitry Andric            "Not relocating a derived object of the original base object");
9544d0b32cdSDimitry Andric     if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
955ff0cc061SDimitry Andric       // A duplicate relocate call. TODO: coalesce duplicates.
956ff0cc061SDimitry Andric       continue;
957ff0cc061SDimitry Andric     }
958ff0cc061SDimitry Andric 
9597d523365SDimitry Andric     if (RelocatedBase->getParent() != ToReplace->getParent()) {
9607d523365SDimitry Andric       // Base and derived relocates are in different basic blocks.
9617d523365SDimitry Andric       // In this case transform is only valid when base dominates derived
9627d523365SDimitry Andric       // relocate. However it would be too expensive to check dominance
9637d523365SDimitry Andric       // for each such relocate, so we skip the whole transformation.
9647d523365SDimitry Andric       continue;
9657d523365SDimitry Andric     }
9667d523365SDimitry Andric 
9674d0b32cdSDimitry Andric     Value *Base = ToReplace->getBasePtr();
9684d0b32cdSDimitry Andric     auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
969ff0cc061SDimitry Andric     if (!Derived || Derived->getPointerOperand() != Base)
970ff0cc061SDimitry Andric       continue;
971ff0cc061SDimitry Andric 
972ff0cc061SDimitry Andric     SmallVector<Value *, 2> OffsetV;
973ff0cc061SDimitry Andric     if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
974ff0cc061SDimitry Andric       continue;
975ff0cc061SDimitry Andric 
976ff0cc061SDimitry Andric     // Create a Builder and replace the target callsite with a gep
9773ca95b02SDimitry Andric     assert(RelocatedBase->getNextNode() &&
9783ca95b02SDimitry Andric            "Should always have one since it's not a terminator");
979ff0cc061SDimitry Andric 
980ff0cc061SDimitry Andric     // Insert after RelocatedBase
981ff0cc061SDimitry Andric     IRBuilder<> Builder(RelocatedBase->getNextNode());
982ff0cc061SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
983ff0cc061SDimitry Andric 
984ff0cc061SDimitry Andric     // If gc_relocate does not match the actual type, cast it to the right type.
985ff0cc061SDimitry Andric     // In theory, there must be a bitcast after gc_relocate if the type does not
986ff0cc061SDimitry Andric     // match, and we should reuse it to get the derived pointer. But it could be
987ff0cc061SDimitry Andric     // cases like this:
988ff0cc061SDimitry Andric     // bb1:
989ff0cc061SDimitry Andric     //  ...
990ff0cc061SDimitry Andric     //  %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
991ff0cc061SDimitry Andric     //  br label %merge
992ff0cc061SDimitry Andric     //
993ff0cc061SDimitry Andric     // bb2:
994ff0cc061SDimitry Andric     //  ...
995ff0cc061SDimitry Andric     //  %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
996ff0cc061SDimitry Andric     //  br label %merge
997ff0cc061SDimitry Andric     //
998ff0cc061SDimitry Andric     // merge:
999ff0cc061SDimitry Andric     //  %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1000ff0cc061SDimitry Andric     //  %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1001ff0cc061SDimitry Andric     //
1002ff0cc061SDimitry Andric     // In this case, we can not find the bitcast any more. So we insert a new bitcast
1003ff0cc061SDimitry Andric     // no matter there is already one or not. In this way, we can handle all cases, and
1004ff0cc061SDimitry Andric     // the extra bitcast should be optimized away in later passes.
10057d523365SDimitry Andric     Value *ActualRelocatedBase = RelocatedBase;
1006ff0cc061SDimitry Andric     if (RelocatedBase->getType() != Base->getType()) {
1007ff0cc061SDimitry Andric       ActualRelocatedBase =
10087d523365SDimitry Andric           Builder.CreateBitCast(RelocatedBase, Base->getType());
1009ff0cc061SDimitry Andric     }
1010ff0cc061SDimitry Andric     Value *Replacement = Builder.CreateGEP(
1011ff0cc061SDimitry Andric         Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
1012ff0cc061SDimitry Andric     Replacement->takeName(ToReplace);
1013ff0cc061SDimitry Andric     // If the newly generated derived pointer's type does not match the original derived
1014ff0cc061SDimitry Andric     // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
10157d523365SDimitry Andric     Value *ActualReplacement = Replacement;
10167d523365SDimitry Andric     if (Replacement->getType() != ToReplace->getType()) {
1017ff0cc061SDimitry Andric       ActualReplacement =
10187d523365SDimitry Andric           Builder.CreateBitCast(Replacement, ToReplace->getType());
1019ff0cc061SDimitry Andric     }
1020ff0cc061SDimitry Andric     ToReplace->replaceAllUsesWith(ActualReplacement);
1021ff0cc061SDimitry Andric     ToReplace->eraseFromParent();
1022ff0cc061SDimitry Andric 
1023ff0cc061SDimitry Andric     MadeChange = true;
1024ff0cc061SDimitry Andric   }
1025ff0cc061SDimitry Andric   return MadeChange;
1026ff0cc061SDimitry Andric }
1027ff0cc061SDimitry Andric 
1028ff0cc061SDimitry Andric // Turns this:
1029ff0cc061SDimitry Andric //
1030ff0cc061SDimitry Andric // %base = ...
1031ff0cc061SDimitry Andric // %ptr = gep %base + 15
1032ff0cc061SDimitry Andric // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1033ff0cc061SDimitry Andric // %base' = relocate(%tok, i32 4, i32 4)
1034ff0cc061SDimitry Andric // %ptr' = relocate(%tok, i32 4, i32 5)
1035ff0cc061SDimitry Andric // %val = load %ptr'
1036ff0cc061SDimitry Andric //
1037ff0cc061SDimitry Andric // into this:
1038ff0cc061SDimitry Andric //
1039ff0cc061SDimitry Andric // %base = ...
1040ff0cc061SDimitry Andric // %ptr = gep %base + 15
1041ff0cc061SDimitry Andric // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1042ff0cc061SDimitry Andric // %base' = gc.relocate(%tok, i32 4, i32 4)
1043ff0cc061SDimitry Andric // %ptr' = gep %base' + 15
1044ff0cc061SDimitry Andric // %val = load %ptr'
1045ff0cc061SDimitry Andric bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1046ff0cc061SDimitry Andric   bool MadeChange = false;
10474d0b32cdSDimitry Andric   SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1048ff0cc061SDimitry Andric 
1049ff0cc061SDimitry Andric   for (auto *U : I.users())
10504d0b32cdSDimitry Andric     if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1051ff0cc061SDimitry Andric       // Collect all the relocate calls associated with a statepoint
10524d0b32cdSDimitry Andric       AllRelocateCalls.push_back(Relocate);
1053ff0cc061SDimitry Andric 
1054ff0cc061SDimitry Andric   // We need atleast one base pointer relocation + one derived pointer
1055ff0cc061SDimitry Andric   // relocation to mangle
1056ff0cc061SDimitry Andric   if (AllRelocateCalls.size() < 2)
1057ff0cc061SDimitry Andric     return false;
1058ff0cc061SDimitry Andric 
1059ff0cc061SDimitry Andric   // RelocateInstMap is a mapping from the base relocate instruction to the
1060ff0cc061SDimitry Andric   // corresponding derived relocate instructions
10614d0b32cdSDimitry Andric   DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1062ff0cc061SDimitry Andric   computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1063ff0cc061SDimitry Andric   if (RelocateInstMap.empty())
1064ff0cc061SDimitry Andric     return false;
1065ff0cc061SDimitry Andric 
1066ff0cc061SDimitry Andric   for (auto &Item : RelocateInstMap)
1067ff0cc061SDimitry Andric     // Item.first is the RelocatedBase to offset against
1068ff0cc061SDimitry Andric     // Item.second is the vector of Targets to replace
1069ff0cc061SDimitry Andric     MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1070ff0cc061SDimitry Andric   return MadeChange;
1071ff0cc061SDimitry Andric }
1072ff0cc061SDimitry Andric 
107391bc56edSDimitry Andric /// SinkCast - Sink the specified cast instruction into its user blocks
107491bc56edSDimitry Andric static bool SinkCast(CastInst *CI) {
107591bc56edSDimitry Andric   BasicBlock *DefBB = CI->getParent();
107691bc56edSDimitry Andric 
107791bc56edSDimitry Andric   /// InsertedCasts - Only insert a cast in each block once.
107891bc56edSDimitry Andric   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
107991bc56edSDimitry Andric 
108091bc56edSDimitry Andric   bool MadeChange = false;
108191bc56edSDimitry Andric   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
108291bc56edSDimitry Andric        UI != E; ) {
108391bc56edSDimitry Andric     Use &TheUse = UI.getUse();
108491bc56edSDimitry Andric     Instruction *User = cast<Instruction>(*UI);
108591bc56edSDimitry Andric 
108691bc56edSDimitry Andric     // Figure out which BB this cast is used in.  For PHI's this is the
108791bc56edSDimitry Andric     // appropriate predecessor block.
108891bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
108991bc56edSDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(User)) {
109091bc56edSDimitry Andric       UserBB = PN->getIncomingBlock(TheUse);
109191bc56edSDimitry Andric     }
109291bc56edSDimitry Andric 
109391bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
109491bc56edSDimitry Andric     ++UI;
109591bc56edSDimitry Andric 
10963ca95b02SDimitry Andric     // The first insertion point of a block containing an EH pad is after the
10973ca95b02SDimitry Andric     // pad.  If the pad is the user, we cannot sink the cast past the pad.
10983ca95b02SDimitry Andric     if (User->isEHPad())
10993ca95b02SDimitry Andric       continue;
11003ca95b02SDimitry Andric 
11017d523365SDimitry Andric     // If the block selected to receive the cast is an EH pad that does not
11027d523365SDimitry Andric     // allow non-PHI instructions before the terminator, we can't sink the
11037d523365SDimitry Andric     // cast.
11047d523365SDimitry Andric     if (UserBB->getTerminator()->isEHPad())
11057d523365SDimitry Andric       continue;
11067d523365SDimitry Andric 
110791bc56edSDimitry Andric     // If this user is in the same block as the cast, don't change the cast.
110891bc56edSDimitry Andric     if (UserBB == DefBB) continue;
110991bc56edSDimitry Andric 
111091bc56edSDimitry Andric     // If we have already inserted a cast into this block, use it.
111191bc56edSDimitry Andric     CastInst *&InsertedCast = InsertedCasts[UserBB];
111291bc56edSDimitry Andric 
111391bc56edSDimitry Andric     if (!InsertedCast) {
111491bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
11157d523365SDimitry Andric       assert(InsertPt != UserBB->end());
11167d523365SDimitry Andric       InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
11177d523365SDimitry Andric                                       CI->getType(), "", &*InsertPt);
111891bc56edSDimitry Andric     }
111991bc56edSDimitry Andric 
112091bc56edSDimitry Andric     // Replace a use of the cast with a use of the new cast.
112191bc56edSDimitry Andric     TheUse = InsertedCast;
1122ff0cc061SDimitry Andric     MadeChange = true;
112391bc56edSDimitry Andric     ++NumCastUses;
112491bc56edSDimitry Andric   }
112591bc56edSDimitry Andric 
112691bc56edSDimitry Andric   // If we removed all uses, nuke the cast.
112791bc56edSDimitry Andric   if (CI->use_empty()) {
112891bc56edSDimitry Andric     CI->eraseFromParent();
112991bc56edSDimitry Andric     MadeChange = true;
113091bc56edSDimitry Andric   }
113191bc56edSDimitry Andric 
113291bc56edSDimitry Andric   return MadeChange;
113391bc56edSDimitry Andric }
113491bc56edSDimitry Andric 
11357d523365SDimitry Andric /// If the specified cast instruction is a noop copy (e.g. it's casting from
11367d523365SDimitry Andric /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
11377d523365SDimitry Andric /// reduce the number of virtual registers that must be created and coalesced.
113891bc56edSDimitry Andric ///
113991bc56edSDimitry Andric /// Return true if any changes are made.
114091bc56edSDimitry Andric ///
1141875ed548SDimitry Andric static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1142875ed548SDimitry Andric                                        const DataLayout &DL) {
1143d88c1a5aSDimitry Andric   // Sink only "cheap" (or nop) address-space casts.  This is a weaker condition
1144d88c1a5aSDimitry Andric   // than sinking only nop casts, but is helpful on some platforms.
1145d88c1a5aSDimitry Andric   if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1146d88c1a5aSDimitry Andric     if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1147d88c1a5aSDimitry Andric                                   ASC->getDestAddressSpace()))
1148d88c1a5aSDimitry Andric       return false;
1149d88c1a5aSDimitry Andric   }
1150d88c1a5aSDimitry Andric 
115191bc56edSDimitry Andric   // If this is a noop copy,
1152875ed548SDimitry Andric   EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1153875ed548SDimitry Andric   EVT DstVT = TLI.getValueType(DL, CI->getType());
115491bc56edSDimitry Andric 
115591bc56edSDimitry Andric   // This is an fp<->int conversion?
115691bc56edSDimitry Andric   if (SrcVT.isInteger() != DstVT.isInteger())
115791bc56edSDimitry Andric     return false;
115891bc56edSDimitry Andric 
115991bc56edSDimitry Andric   // If this is an extension, it will be a zero or sign extension, which
116091bc56edSDimitry Andric   // isn't a noop.
116191bc56edSDimitry Andric   if (SrcVT.bitsLT(DstVT)) return false;
116291bc56edSDimitry Andric 
116391bc56edSDimitry Andric   // If these values will be promoted, find out what they will be promoted
116491bc56edSDimitry Andric   // to.  This helps us consider truncates on PPC as noop copies when they
116591bc56edSDimitry Andric   // are.
116691bc56edSDimitry Andric   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
116791bc56edSDimitry Andric       TargetLowering::TypePromoteInteger)
116891bc56edSDimitry Andric     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
116991bc56edSDimitry Andric   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
117091bc56edSDimitry Andric       TargetLowering::TypePromoteInteger)
117191bc56edSDimitry Andric     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
117291bc56edSDimitry Andric 
117391bc56edSDimitry Andric   // If, after promotion, these are the same types, this is a noop copy.
117491bc56edSDimitry Andric   if (SrcVT != DstVT)
117591bc56edSDimitry Andric     return false;
117691bc56edSDimitry Andric 
117791bc56edSDimitry Andric   return SinkCast(CI);
117891bc56edSDimitry Andric }
117991bc56edSDimitry Andric 
11807d523365SDimitry Andric /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
11817d523365SDimitry Andric /// possible.
1182ff0cc061SDimitry Andric ///
1183ff0cc061SDimitry Andric /// Return true if any changes were made.
1184ff0cc061SDimitry Andric static bool CombineUAddWithOverflow(CmpInst *CI) {
1185ff0cc061SDimitry Andric   Value *A, *B;
1186ff0cc061SDimitry Andric   Instruction *AddI;
1187ff0cc061SDimitry Andric   if (!match(CI,
1188ff0cc061SDimitry Andric              m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1189ff0cc061SDimitry Andric     return false;
1190ff0cc061SDimitry Andric 
1191ff0cc061SDimitry Andric   Type *Ty = AddI->getType();
1192ff0cc061SDimitry Andric   if (!isa<IntegerType>(Ty))
1193ff0cc061SDimitry Andric     return false;
1194ff0cc061SDimitry Andric 
1195ff0cc061SDimitry Andric   // We don't want to move around uses of condition values this late, so we we
1196ff0cc061SDimitry Andric   // check if it is legal to create the call to the intrinsic in the basic
1197ff0cc061SDimitry Andric   // block containing the icmp:
1198ff0cc061SDimitry Andric 
1199ff0cc061SDimitry Andric   if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1200ff0cc061SDimitry Andric     return false;
1201ff0cc061SDimitry Andric 
1202ff0cc061SDimitry Andric #ifndef NDEBUG
1203ff0cc061SDimitry Andric   // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1204ff0cc061SDimitry Andric   // for now:
1205ff0cc061SDimitry Andric   if (AddI->hasOneUse())
1206ff0cc061SDimitry Andric     assert(*AddI->user_begin() == CI && "expected!");
1207ff0cc061SDimitry Andric #endif
1208ff0cc061SDimitry Andric 
12097d523365SDimitry Andric   Module *M = CI->getModule();
1210ff0cc061SDimitry Andric   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1211ff0cc061SDimitry Andric 
1212ff0cc061SDimitry Andric   auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1213ff0cc061SDimitry Andric 
1214ff0cc061SDimitry Andric   auto *UAddWithOverflow =
1215ff0cc061SDimitry Andric       CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1216ff0cc061SDimitry Andric   auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1217ff0cc061SDimitry Andric   auto *Overflow =
1218ff0cc061SDimitry Andric       ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1219ff0cc061SDimitry Andric 
1220ff0cc061SDimitry Andric   CI->replaceAllUsesWith(Overflow);
1221ff0cc061SDimitry Andric   AddI->replaceAllUsesWith(UAdd);
1222ff0cc061SDimitry Andric   CI->eraseFromParent();
1223ff0cc061SDimitry Andric   AddI->eraseFromParent();
1224ff0cc061SDimitry Andric   return true;
1225ff0cc061SDimitry Andric }
1226ff0cc061SDimitry Andric 
12277d523365SDimitry Andric /// Sink the given CmpInst into user blocks to reduce the number of virtual
12287d523365SDimitry Andric /// registers that must be created and coalesced. This is a clear win except on
12297d523365SDimitry Andric /// targets with multiple condition code registers (PowerPC), where it might
12307d523365SDimitry Andric /// lose; some adjustment may be wanted there.
123191bc56edSDimitry Andric ///
123291bc56edSDimitry Andric /// Return true if any changes are made.
12333ca95b02SDimitry Andric static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
123491bc56edSDimitry Andric   BasicBlock *DefBB = CI->getParent();
123591bc56edSDimitry Andric 
12363ca95b02SDimitry Andric   // Avoid sinking soft-FP comparisons, since this can move them into a loop.
12373ca95b02SDimitry Andric   if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
12383ca95b02SDimitry Andric     return false;
12393ca95b02SDimitry Andric 
12403ca95b02SDimitry Andric   // Only insert a cmp in each block once.
124191bc56edSDimitry Andric   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
124291bc56edSDimitry Andric 
124391bc56edSDimitry Andric   bool MadeChange = false;
124491bc56edSDimitry Andric   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
124591bc56edSDimitry Andric        UI != E; ) {
124691bc56edSDimitry Andric     Use &TheUse = UI.getUse();
124791bc56edSDimitry Andric     Instruction *User = cast<Instruction>(*UI);
124891bc56edSDimitry Andric 
124991bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
125091bc56edSDimitry Andric     ++UI;
125191bc56edSDimitry Andric 
125291bc56edSDimitry Andric     // Don't bother for PHI nodes.
125391bc56edSDimitry Andric     if (isa<PHINode>(User))
125491bc56edSDimitry Andric       continue;
125591bc56edSDimitry Andric 
125691bc56edSDimitry Andric     // Figure out which BB this cmp is used in.
125791bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
125891bc56edSDimitry Andric 
125991bc56edSDimitry Andric     // If this user is in the same block as the cmp, don't change the cmp.
126091bc56edSDimitry Andric     if (UserBB == DefBB) continue;
126191bc56edSDimitry Andric 
126291bc56edSDimitry Andric     // If we have already inserted a cmp into this block, use it.
126391bc56edSDimitry Andric     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
126491bc56edSDimitry Andric 
126591bc56edSDimitry Andric     if (!InsertedCmp) {
126691bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
12677d523365SDimitry Andric       assert(InsertPt != UserBB->end());
126891bc56edSDimitry Andric       InsertedCmp =
12697d523365SDimitry Andric           CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
12707d523365SDimitry Andric                           CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
1271d88c1a5aSDimitry Andric       // Propagate the debug info.
1272d88c1a5aSDimitry Andric       InsertedCmp->setDebugLoc(CI->getDebugLoc());
127391bc56edSDimitry Andric     }
127491bc56edSDimitry Andric 
127591bc56edSDimitry Andric     // Replace a use of the cmp with a use of the new cmp.
127691bc56edSDimitry Andric     TheUse = InsertedCmp;
1277ff0cc061SDimitry Andric     MadeChange = true;
127891bc56edSDimitry Andric     ++NumCmpUses;
127991bc56edSDimitry Andric   }
128091bc56edSDimitry Andric 
128191bc56edSDimitry Andric   // If we removed all uses, nuke the cmp.
1282ff0cc061SDimitry Andric   if (CI->use_empty()) {
128391bc56edSDimitry Andric     CI->eraseFromParent();
1284ff0cc061SDimitry Andric     MadeChange = true;
1285ff0cc061SDimitry Andric   }
128691bc56edSDimitry Andric 
128791bc56edSDimitry Andric   return MadeChange;
128891bc56edSDimitry Andric }
128991bc56edSDimitry Andric 
12903ca95b02SDimitry Andric static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
12913ca95b02SDimitry Andric   if (SinkCmpExpression(CI, TLI))
1292ff0cc061SDimitry Andric     return true;
1293ff0cc061SDimitry Andric 
1294ff0cc061SDimitry Andric   if (CombineUAddWithOverflow(CI))
1295ff0cc061SDimitry Andric     return true;
1296ff0cc061SDimitry Andric 
1297ff0cc061SDimitry Andric   return false;
1298ff0cc061SDimitry Andric }
1299ff0cc061SDimitry Andric 
13007a7e6055SDimitry Andric /// Duplicate and sink the given 'and' instruction into user blocks where it is
13017a7e6055SDimitry Andric /// used in a compare to allow isel to generate better code for targets where
13027a7e6055SDimitry Andric /// this operation can be combined.
13037a7e6055SDimitry Andric ///
13047a7e6055SDimitry Andric /// Return true if any changes are made.
13057a7e6055SDimitry Andric static bool sinkAndCmp0Expression(Instruction *AndI,
13067a7e6055SDimitry Andric                                   const TargetLowering &TLI,
13077a7e6055SDimitry Andric                                   SetOfInstrs &InsertedInsts) {
13087a7e6055SDimitry Andric   // Double-check that we're not trying to optimize an instruction that was
13097a7e6055SDimitry Andric   // already optimized by some other part of this pass.
13107a7e6055SDimitry Andric   assert(!InsertedInsts.count(AndI) &&
13117a7e6055SDimitry Andric          "Attempting to optimize already optimized and instruction");
13127a7e6055SDimitry Andric   (void) InsertedInsts;
13137a7e6055SDimitry Andric 
13147a7e6055SDimitry Andric   // Nothing to do for single use in same basic block.
13157a7e6055SDimitry Andric   if (AndI->hasOneUse() &&
13167a7e6055SDimitry Andric       AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
13177a7e6055SDimitry Andric     return false;
13187a7e6055SDimitry Andric 
13197a7e6055SDimitry Andric   // Try to avoid cases where sinking/duplicating is likely to increase register
13207a7e6055SDimitry Andric   // pressure.
13217a7e6055SDimitry Andric   if (!isa<ConstantInt>(AndI->getOperand(0)) &&
13227a7e6055SDimitry Andric       !isa<ConstantInt>(AndI->getOperand(1)) &&
13237a7e6055SDimitry Andric       AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
13247a7e6055SDimitry Andric     return false;
13257a7e6055SDimitry Andric 
13267a7e6055SDimitry Andric   for (auto *U : AndI->users()) {
13277a7e6055SDimitry Andric     Instruction *User = cast<Instruction>(U);
13287a7e6055SDimitry Andric 
13297a7e6055SDimitry Andric     // Only sink for and mask feeding icmp with 0.
13307a7e6055SDimitry Andric     if (!isa<ICmpInst>(User))
13317a7e6055SDimitry Andric       return false;
13327a7e6055SDimitry Andric 
13337a7e6055SDimitry Andric     auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
13347a7e6055SDimitry Andric     if (!CmpC || !CmpC->isZero())
13357a7e6055SDimitry Andric       return false;
13367a7e6055SDimitry Andric   }
13377a7e6055SDimitry Andric 
13387a7e6055SDimitry Andric   if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
13397a7e6055SDimitry Andric     return false;
13407a7e6055SDimitry Andric 
13417a7e6055SDimitry Andric   DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
13427a7e6055SDimitry Andric   DEBUG(AndI->getParent()->dump());
13437a7e6055SDimitry Andric 
13447a7e6055SDimitry Andric   // Push the 'and' into the same block as the icmp 0.  There should only be
13457a7e6055SDimitry Andric   // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
13467a7e6055SDimitry Andric   // others, so we don't need to keep track of which BBs we insert into.
13477a7e6055SDimitry Andric   for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
13487a7e6055SDimitry Andric        UI != E; ) {
13497a7e6055SDimitry Andric     Use &TheUse = UI.getUse();
13507a7e6055SDimitry Andric     Instruction *User = cast<Instruction>(*UI);
13517a7e6055SDimitry Andric 
13527a7e6055SDimitry Andric     // Preincrement use iterator so we don't invalidate it.
13537a7e6055SDimitry Andric     ++UI;
13547a7e6055SDimitry Andric 
13557a7e6055SDimitry Andric     DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
13567a7e6055SDimitry Andric 
13577a7e6055SDimitry Andric     // Keep the 'and' in the same place if the use is already in the same block.
13587a7e6055SDimitry Andric     Instruction *InsertPt =
13597a7e6055SDimitry Andric         User->getParent() == AndI->getParent() ? AndI : User;
13607a7e6055SDimitry Andric     Instruction *InsertedAnd =
13617a7e6055SDimitry Andric         BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
13627a7e6055SDimitry Andric                                AndI->getOperand(1), "", InsertPt);
13637a7e6055SDimitry Andric     // Propagate the debug info.
13647a7e6055SDimitry Andric     InsertedAnd->setDebugLoc(AndI->getDebugLoc());
13657a7e6055SDimitry Andric 
13667a7e6055SDimitry Andric     // Replace a use of the 'and' with a use of the new 'and'.
13677a7e6055SDimitry Andric     TheUse = InsertedAnd;
13687a7e6055SDimitry Andric     ++NumAndUses;
13697a7e6055SDimitry Andric     DEBUG(User->getParent()->dump());
13707a7e6055SDimitry Andric   }
13717a7e6055SDimitry Andric 
13727a7e6055SDimitry Andric   // We removed all uses, nuke the and.
13737a7e6055SDimitry Andric   AndI->eraseFromParent();
13747a7e6055SDimitry Andric   return true;
13757a7e6055SDimitry Andric }
13767a7e6055SDimitry Andric 
13777d523365SDimitry Andric /// Check if the candidates could be combined with a shift instruction, which
13787d523365SDimitry Andric /// includes:
137991bc56edSDimitry Andric /// 1. Truncate instruction
138091bc56edSDimitry Andric /// 2. And instruction and the imm is a mask of the low bits:
138191bc56edSDimitry Andric /// imm & (imm+1) == 0
138291bc56edSDimitry Andric static bool isExtractBitsCandidateUse(Instruction *User) {
138391bc56edSDimitry Andric   if (!isa<TruncInst>(User)) {
138491bc56edSDimitry Andric     if (User->getOpcode() != Instruction::And ||
138591bc56edSDimitry Andric         !isa<ConstantInt>(User->getOperand(1)))
138691bc56edSDimitry Andric       return false;
138791bc56edSDimitry Andric 
138891bc56edSDimitry Andric     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
138991bc56edSDimitry Andric 
139091bc56edSDimitry Andric     if ((Cimm & (Cimm + 1)).getBoolValue())
139191bc56edSDimitry Andric       return false;
139291bc56edSDimitry Andric   }
139391bc56edSDimitry Andric   return true;
139491bc56edSDimitry Andric }
139591bc56edSDimitry Andric 
13967d523365SDimitry Andric /// Sink both shift and truncate instruction to the use of truncate's BB.
139791bc56edSDimitry Andric static bool
139891bc56edSDimitry Andric SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
139991bc56edSDimitry Andric                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1400875ed548SDimitry Andric                      const TargetLowering &TLI, const DataLayout &DL) {
140191bc56edSDimitry Andric   BasicBlock *UserBB = User->getParent();
140291bc56edSDimitry Andric   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
140391bc56edSDimitry Andric   TruncInst *TruncI = dyn_cast<TruncInst>(User);
140491bc56edSDimitry Andric   bool MadeChange = false;
140591bc56edSDimitry Andric 
140691bc56edSDimitry Andric   for (Value::user_iterator TruncUI = TruncI->user_begin(),
140791bc56edSDimitry Andric                             TruncE = TruncI->user_end();
140891bc56edSDimitry Andric        TruncUI != TruncE;) {
140991bc56edSDimitry Andric 
141091bc56edSDimitry Andric     Use &TruncTheUse = TruncUI.getUse();
141191bc56edSDimitry Andric     Instruction *TruncUser = cast<Instruction>(*TruncUI);
141291bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
141391bc56edSDimitry Andric 
141491bc56edSDimitry Andric     ++TruncUI;
141591bc56edSDimitry Andric 
141691bc56edSDimitry Andric     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
141791bc56edSDimitry Andric     if (!ISDOpcode)
141891bc56edSDimitry Andric       continue;
141991bc56edSDimitry Andric 
142039d628a0SDimitry Andric     // If the use is actually a legal node, there will not be an
142139d628a0SDimitry Andric     // implicit truncate.
142239d628a0SDimitry Andric     // FIXME: always querying the result type is just an
142339d628a0SDimitry Andric     // approximation; some nodes' legality is determined by the
142439d628a0SDimitry Andric     // operand or other means. There's no good way to find out though.
142539d628a0SDimitry Andric     if (TLI.isOperationLegalOrCustom(
1426875ed548SDimitry Andric             ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
142791bc56edSDimitry Andric       continue;
142891bc56edSDimitry Andric 
142991bc56edSDimitry Andric     // Don't bother for PHI nodes.
143091bc56edSDimitry Andric     if (isa<PHINode>(TruncUser))
143191bc56edSDimitry Andric       continue;
143291bc56edSDimitry Andric 
143391bc56edSDimitry Andric     BasicBlock *TruncUserBB = TruncUser->getParent();
143491bc56edSDimitry Andric 
143591bc56edSDimitry Andric     if (UserBB == TruncUserBB)
143691bc56edSDimitry Andric       continue;
143791bc56edSDimitry Andric 
143891bc56edSDimitry Andric     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
143991bc56edSDimitry Andric     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
144091bc56edSDimitry Andric 
144191bc56edSDimitry Andric     if (!InsertedShift && !InsertedTrunc) {
144291bc56edSDimitry Andric       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
14437d523365SDimitry Andric       assert(InsertPt != TruncUserBB->end());
144491bc56edSDimitry Andric       // Sink the shift
144591bc56edSDimitry Andric       if (ShiftI->getOpcode() == Instruction::AShr)
14467d523365SDimitry Andric         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
14477d523365SDimitry Andric                                                    "", &*InsertPt);
144891bc56edSDimitry Andric       else
14497d523365SDimitry Andric         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
14507d523365SDimitry Andric                                                    "", &*InsertPt);
145191bc56edSDimitry Andric 
145291bc56edSDimitry Andric       // Sink the trunc
145391bc56edSDimitry Andric       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
145491bc56edSDimitry Andric       TruncInsertPt++;
14557d523365SDimitry Andric       assert(TruncInsertPt != TruncUserBB->end());
145691bc56edSDimitry Andric 
145791bc56edSDimitry Andric       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
14587d523365SDimitry Andric                                        TruncI->getType(), "", &*TruncInsertPt);
145991bc56edSDimitry Andric 
146091bc56edSDimitry Andric       MadeChange = true;
146191bc56edSDimitry Andric 
146291bc56edSDimitry Andric       TruncTheUse = InsertedTrunc;
146391bc56edSDimitry Andric     }
146491bc56edSDimitry Andric   }
146591bc56edSDimitry Andric   return MadeChange;
146691bc56edSDimitry Andric }
146791bc56edSDimitry Andric 
14687d523365SDimitry Andric /// Sink the shift *right* instruction into user blocks if the uses could
14697d523365SDimitry Andric /// potentially be combined with this shift instruction and generate BitExtract
14707d523365SDimitry Andric /// instruction. It will only be applied if the architecture supports BitExtract
14717d523365SDimitry Andric /// instruction. Here is an example:
147291bc56edSDimitry Andric /// BB1:
147391bc56edSDimitry Andric ///   %x.extract.shift = lshr i64 %arg1, 32
147491bc56edSDimitry Andric /// BB2:
147591bc56edSDimitry Andric ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
147691bc56edSDimitry Andric /// ==>
147791bc56edSDimitry Andric ///
147891bc56edSDimitry Andric /// BB2:
147991bc56edSDimitry Andric ///   %x.extract.shift.1 = lshr i64 %arg1, 32
148091bc56edSDimitry Andric ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
148191bc56edSDimitry Andric ///
148291bc56edSDimitry Andric /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
148391bc56edSDimitry Andric /// instruction.
148491bc56edSDimitry Andric /// Return true if any changes are made.
148591bc56edSDimitry Andric static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1486875ed548SDimitry Andric                                 const TargetLowering &TLI,
1487875ed548SDimitry Andric                                 const DataLayout &DL) {
148891bc56edSDimitry Andric   BasicBlock *DefBB = ShiftI->getParent();
148991bc56edSDimitry Andric 
149091bc56edSDimitry Andric   /// Only insert instructions in each block once.
149191bc56edSDimitry Andric   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
149291bc56edSDimitry Andric 
1493875ed548SDimitry Andric   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
149491bc56edSDimitry Andric 
149591bc56edSDimitry Andric   bool MadeChange = false;
149691bc56edSDimitry Andric   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
149791bc56edSDimitry Andric        UI != E;) {
149891bc56edSDimitry Andric     Use &TheUse = UI.getUse();
149991bc56edSDimitry Andric     Instruction *User = cast<Instruction>(*UI);
150091bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
150191bc56edSDimitry Andric     ++UI;
150291bc56edSDimitry Andric 
150391bc56edSDimitry Andric     // Don't bother for PHI nodes.
150491bc56edSDimitry Andric     if (isa<PHINode>(User))
150591bc56edSDimitry Andric       continue;
150691bc56edSDimitry Andric 
150791bc56edSDimitry Andric     if (!isExtractBitsCandidateUse(User))
150891bc56edSDimitry Andric       continue;
150991bc56edSDimitry Andric 
151091bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
151191bc56edSDimitry Andric 
151291bc56edSDimitry Andric     if (UserBB == DefBB) {
151391bc56edSDimitry Andric       // If the shift and truncate instruction are in the same BB. The use of
151491bc56edSDimitry Andric       // the truncate(TruncUse) may still introduce another truncate if not
151591bc56edSDimitry Andric       // legal. In this case, we would like to sink both shift and truncate
151691bc56edSDimitry Andric       // instruction to the BB of TruncUse.
151791bc56edSDimitry Andric       // for example:
151891bc56edSDimitry Andric       // BB1:
151991bc56edSDimitry Andric       // i64 shift.result = lshr i64 opnd, imm
152091bc56edSDimitry Andric       // trunc.result = trunc shift.result to i16
152191bc56edSDimitry Andric       //
152291bc56edSDimitry Andric       // BB2:
152391bc56edSDimitry Andric       //   ----> We will have an implicit truncate here if the architecture does
152491bc56edSDimitry Andric       //   not have i16 compare.
152591bc56edSDimitry Andric       // cmp i16 trunc.result, opnd2
152691bc56edSDimitry Andric       //
152791bc56edSDimitry Andric       if (isa<TruncInst>(User) && shiftIsLegal
152891bc56edSDimitry Andric           // If the type of the truncate is legal, no trucate will be
152991bc56edSDimitry Andric           // introduced in other basic blocks.
1530875ed548SDimitry Andric           &&
1531875ed548SDimitry Andric           (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
153291bc56edSDimitry Andric         MadeChange =
1533875ed548SDimitry Andric             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
153491bc56edSDimitry Andric 
153591bc56edSDimitry Andric       continue;
153691bc56edSDimitry Andric     }
153791bc56edSDimitry Andric     // If we have already inserted a shift into this block, use it.
153891bc56edSDimitry Andric     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
153991bc56edSDimitry Andric 
154091bc56edSDimitry Andric     if (!InsertedShift) {
154191bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
15427d523365SDimitry Andric       assert(InsertPt != UserBB->end());
154391bc56edSDimitry Andric 
154491bc56edSDimitry Andric       if (ShiftI->getOpcode() == Instruction::AShr)
15457d523365SDimitry Andric         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
15467d523365SDimitry Andric                                                    "", &*InsertPt);
154791bc56edSDimitry Andric       else
15487d523365SDimitry Andric         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
15497d523365SDimitry Andric                                                    "", &*InsertPt);
155091bc56edSDimitry Andric 
155191bc56edSDimitry Andric       MadeChange = true;
155291bc56edSDimitry Andric     }
155391bc56edSDimitry Andric 
155491bc56edSDimitry Andric     // Replace a use of the shift with a use of the new shift.
155591bc56edSDimitry Andric     TheUse = InsertedShift;
155691bc56edSDimitry Andric   }
155791bc56edSDimitry Andric 
155891bc56edSDimitry Andric   // If we removed all uses, nuke the shift.
155991bc56edSDimitry Andric   if (ShiftI->use_empty())
156091bc56edSDimitry Andric     ShiftI->eraseFromParent();
156191bc56edSDimitry Andric 
156291bc56edSDimitry Andric   return MadeChange;
156391bc56edSDimitry Andric }
156491bc56edSDimitry Andric 
15657d523365SDimitry Andric /// If counting leading or trailing zeros is an expensive operation and a zero
15667d523365SDimitry Andric /// input is defined, add a check for zero to avoid calling the intrinsic.
15677d523365SDimitry Andric ///
15687d523365SDimitry Andric /// We want to transform:
15697d523365SDimitry Andric ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
15707d523365SDimitry Andric ///
15717d523365SDimitry Andric /// into:
15727d523365SDimitry Andric ///   entry:
15737d523365SDimitry Andric ///     %cmpz = icmp eq i64 %A, 0
15747d523365SDimitry Andric ///     br i1 %cmpz, label %cond.end, label %cond.false
15757d523365SDimitry Andric ///   cond.false:
15767d523365SDimitry Andric ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
15777d523365SDimitry Andric ///     br label %cond.end
15787d523365SDimitry Andric ///   cond.end:
15797d523365SDimitry Andric ///     %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
15807d523365SDimitry Andric ///
15817d523365SDimitry Andric /// If the transform is performed, return true and set ModifiedDT to true.
15827d523365SDimitry Andric static bool despeculateCountZeros(IntrinsicInst *CountZeros,
15837d523365SDimitry Andric                                   const TargetLowering *TLI,
15847d523365SDimitry Andric                                   const DataLayout *DL,
15857d523365SDimitry Andric                                   bool &ModifiedDT) {
15867d523365SDimitry Andric   if (!TLI || !DL)
15877d523365SDimitry Andric     return false;
15887d523365SDimitry Andric 
15897d523365SDimitry Andric   // If a zero input is undefined, it doesn't make sense to despeculate that.
15907d523365SDimitry Andric   if (match(CountZeros->getOperand(1), m_One()))
15917d523365SDimitry Andric     return false;
15927d523365SDimitry Andric 
15937d523365SDimitry Andric   // If it's cheap to speculate, there's nothing to do.
15947d523365SDimitry Andric   auto IntrinsicID = CountZeros->getIntrinsicID();
15957d523365SDimitry Andric   if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
15967d523365SDimitry Andric       (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
15977d523365SDimitry Andric     return false;
15987d523365SDimitry Andric 
15997d523365SDimitry Andric   // Only handle legal scalar cases. Anything else requires too much work.
16007d523365SDimitry Andric   Type *Ty = CountZeros->getType();
16017d523365SDimitry Andric   unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
16023ca95b02SDimitry Andric   if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
16037d523365SDimitry Andric     return false;
16047d523365SDimitry Andric 
16057d523365SDimitry Andric   // The intrinsic will be sunk behind a compare against zero and branch.
16067d523365SDimitry Andric   BasicBlock *StartBlock = CountZeros->getParent();
16077d523365SDimitry Andric   BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
16087d523365SDimitry Andric 
16097d523365SDimitry Andric   // Create another block after the count zero intrinsic. A PHI will be added
16107d523365SDimitry Andric   // in this block to select the result of the intrinsic or the bit-width
16117d523365SDimitry Andric   // constant if the input to the intrinsic is zero.
16127d523365SDimitry Andric   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
16137d523365SDimitry Andric   BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
16147d523365SDimitry Andric 
16157d523365SDimitry Andric   // Set up a builder to create a compare, conditional branch, and PHI.
16167d523365SDimitry Andric   IRBuilder<> Builder(CountZeros->getContext());
16177d523365SDimitry Andric   Builder.SetInsertPoint(StartBlock->getTerminator());
16187d523365SDimitry Andric   Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
16197d523365SDimitry Andric 
16207d523365SDimitry Andric   // Replace the unconditional branch that was created by the first split with
16217d523365SDimitry Andric   // a compare against zero and a conditional branch.
16227d523365SDimitry Andric   Value *Zero = Constant::getNullValue(Ty);
16237d523365SDimitry Andric   Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
16247d523365SDimitry Andric   Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
16257d523365SDimitry Andric   StartBlock->getTerminator()->eraseFromParent();
16267d523365SDimitry Andric 
16277d523365SDimitry Andric   // Create a PHI in the end block to select either the output of the intrinsic
16287d523365SDimitry Andric   // or the bit width of the operand.
16297d523365SDimitry Andric   Builder.SetInsertPoint(&EndBlock->front());
16307d523365SDimitry Andric   PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
16317d523365SDimitry Andric   CountZeros->replaceAllUsesWith(PN);
16327d523365SDimitry Andric   Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
16337d523365SDimitry Andric   PN->addIncoming(BitWidth, StartBlock);
16347d523365SDimitry Andric   PN->addIncoming(CountZeros, CallBlock);
16357d523365SDimitry Andric 
16367d523365SDimitry Andric   // We are explicitly handling the zero case, so we can set the intrinsic's
16377d523365SDimitry Andric   // undefined zero argument to 'true'. This will also prevent reprocessing the
16387d523365SDimitry Andric   // intrinsic; we only despeculate when a zero input is defined.
16397d523365SDimitry Andric   CountZeros->setArgOperand(1, Builder.getTrue());
16407d523365SDimitry Andric   ModifiedDT = true;
16417d523365SDimitry Andric   return true;
16427d523365SDimitry Andric }
16437d523365SDimitry Andric 
1644f9448bf3SDimitry Andric // This class provides helper functions to expand a memcmp library call into an
1645f9448bf3SDimitry Andric // inline expansion.
1646f9448bf3SDimitry Andric class MemCmpExpansion {
1647f9448bf3SDimitry Andric   struct ResultBlock {
1648f9448bf3SDimitry Andric     BasicBlock *BB;
1649f9448bf3SDimitry Andric     PHINode *PhiSrc1;
1650f9448bf3SDimitry Andric     PHINode *PhiSrc2;
1651f9448bf3SDimitry Andric     ResultBlock();
1652f9448bf3SDimitry Andric   };
1653f9448bf3SDimitry Andric 
1654f9448bf3SDimitry Andric   CallInst *CI;
1655f9448bf3SDimitry Andric   ResultBlock ResBlock;
1656f9448bf3SDimitry Andric   unsigned MaxLoadSize;
1657f9448bf3SDimitry Andric   unsigned NumBlocks;
1658f9448bf3SDimitry Andric   unsigned NumBlocksNonOneByte;
1659f9448bf3SDimitry Andric   unsigned NumLoadsPerBlock;
1660f9448bf3SDimitry Andric   std::vector<BasicBlock *> LoadCmpBlocks;
1661f9448bf3SDimitry Andric   BasicBlock *EndBlock;
1662f9448bf3SDimitry Andric   PHINode *PhiRes;
1663f9448bf3SDimitry Andric   bool IsUsedForZeroCmp;
1664db17bf38SDimitry Andric   const DataLayout &DL;
1665a580b014SDimitry Andric   IRBuilder<> Builder;
1666db17bf38SDimitry Andric 
1667edd7eaddSDimitry Andric   unsigned calculateNumBlocks(unsigned Size);
1668f9448bf3SDimitry Andric   void createLoadCmpBlocks();
1669f9448bf3SDimitry Andric   void createResultBlock();
1670f9448bf3SDimitry Andric   void setupResultBlockPHINodes();
1671f9448bf3SDimitry Andric   void setupEndBlockPHINodes();
1672edd7eaddSDimitry Andric   void emitLoadCompareBlock(unsigned Index, unsigned LoadSize,
1673edd7eaddSDimitry Andric                             unsigned GEPIndex);
1674db17bf38SDimitry Andric   Value *getCompareLoadPairs(unsigned Index, unsigned Size,
1675a580b014SDimitry Andric                              unsigned &NumBytesProcessed);
1676f9448bf3SDimitry Andric   void emitLoadCompareBlockMultipleLoads(unsigned Index, unsigned Size,
1677f9448bf3SDimitry Andric                                          unsigned &NumBytesProcessed);
1678edd7eaddSDimitry Andric   void emitLoadCompareByteBlock(unsigned Index, unsigned GEPIndex);
1679db17bf38SDimitry Andric   void emitMemCmpResultBlock();
1680db17bf38SDimitry Andric   Value *getMemCmpExpansionZeroCase(unsigned Size);
1681db17bf38SDimitry Andric   Value *getMemCmpEqZeroOneBlock(unsigned Size);
1682a580b014SDimitry Andric   Value *getMemCmpOneBlock(unsigned Size);
1683f9448bf3SDimitry Andric   unsigned getLoadSize(unsigned Size);
1684f9448bf3SDimitry Andric   unsigned getNumLoads(unsigned Size);
1685f9448bf3SDimitry Andric 
1686f9448bf3SDimitry Andric public:
1687db17bf38SDimitry Andric   MemCmpExpansion(CallInst *CI, uint64_t Size, unsigned MaxLoadSize,
1688db17bf38SDimitry Andric                   unsigned NumLoadsPerBlock, const DataLayout &DL);
1689db17bf38SDimitry Andric   Value *getMemCmpExpansion(uint64_t Size);
1690f9448bf3SDimitry Andric };
1691f9448bf3SDimitry Andric 
1692f9448bf3SDimitry Andric MemCmpExpansion::ResultBlock::ResultBlock()
1693f9448bf3SDimitry Andric     : BB(nullptr), PhiSrc1(nullptr), PhiSrc2(nullptr) {}
1694f9448bf3SDimitry Andric 
1695f9448bf3SDimitry Andric // Initialize the basic block structure required for expansion of memcmp call
1696f9448bf3SDimitry Andric // with given maximum load size and memcmp size parameter.
1697f9448bf3SDimitry Andric // This structure includes:
1698f9448bf3SDimitry Andric // 1. A list of load compare blocks - LoadCmpBlocks.
1699f9448bf3SDimitry Andric // 2. An EndBlock, split from original instruction point, which is the block to
1700f9448bf3SDimitry Andric // return from.
1701f9448bf3SDimitry Andric // 3. ResultBlock, block to branch to for early exit when a
1702f9448bf3SDimitry Andric // LoadCmpBlock finds a difference.
1703db17bf38SDimitry Andric MemCmpExpansion::MemCmpExpansion(CallInst *CI, uint64_t Size,
1704db17bf38SDimitry Andric                                  unsigned MaxLoadSize, unsigned LoadsPerBlock,
1705db17bf38SDimitry Andric                                  const DataLayout &TheDataLayout)
1706db17bf38SDimitry Andric     : CI(CI), MaxLoadSize(MaxLoadSize), NumLoadsPerBlock(LoadsPerBlock),
1707a580b014SDimitry Andric       DL(TheDataLayout), Builder(CI) {
1708f9448bf3SDimitry Andric 
1709db17bf38SDimitry Andric   // A memcmp with zero-comparison with only one block of load and compare does
1710db17bf38SDimitry Andric   // not need to set up any extra blocks. This case could be handled in the DAG,
1711db17bf38SDimitry Andric   // but since we have all of the machinery to flexibly expand any memcpy here,
1712db17bf38SDimitry Andric   // we choose to handle this case too to avoid fragmented lowering.
1713db17bf38SDimitry Andric   IsUsedForZeroCmp = isOnlyUsedInZeroEqualityComparison(CI);
1714db17bf38SDimitry Andric   NumBlocks = calculateNumBlocks(Size);
1715a580b014SDimitry Andric   if ((!IsUsedForZeroCmp && NumLoadsPerBlock != 1) || NumBlocks != 1) {
1716f9448bf3SDimitry Andric     BasicBlock *StartBlock = CI->getParent();
1717f9448bf3SDimitry Andric     EndBlock = StartBlock->splitBasicBlock(CI, "endblock");
1718f9448bf3SDimitry Andric     setupEndBlockPHINodes();
1719f9448bf3SDimitry Andric     createResultBlock();
1720f9448bf3SDimitry Andric 
1721f9448bf3SDimitry Andric     // If return value of memcmp is not used in a zero equality, we need to
1722f9448bf3SDimitry Andric     // calculate which source was larger. The calculation requires the
1723f9448bf3SDimitry Andric     // two loaded source values of each load compare block.
1724f9448bf3SDimitry Andric     // These will be saved in the phi nodes created by setupResultBlockPHINodes.
1725f9448bf3SDimitry Andric     if (!IsUsedForZeroCmp)
1726f9448bf3SDimitry Andric       setupResultBlockPHINodes();
1727f9448bf3SDimitry Andric 
1728f9448bf3SDimitry Andric     // Create the number of required load compare basic blocks.
1729f9448bf3SDimitry Andric     createLoadCmpBlocks();
1730f9448bf3SDimitry Andric 
1731f9448bf3SDimitry Andric     // Update the terminator added by splitBasicBlock to branch to the first
1732f9448bf3SDimitry Andric     // LoadCmpBlock.
1733f9448bf3SDimitry Andric     StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]);
1734f9448bf3SDimitry Andric   }
1735f9448bf3SDimitry Andric 
1736db17bf38SDimitry Andric   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1737db17bf38SDimitry Andric }
1738db17bf38SDimitry Andric 
1739f9448bf3SDimitry Andric void MemCmpExpansion::createLoadCmpBlocks() {
1740f9448bf3SDimitry Andric   for (unsigned i = 0; i < NumBlocks; i++) {
1741f9448bf3SDimitry Andric     BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
1742f9448bf3SDimitry Andric                                         EndBlock->getParent(), EndBlock);
1743f9448bf3SDimitry Andric     LoadCmpBlocks.push_back(BB);
1744f9448bf3SDimitry Andric   }
1745f9448bf3SDimitry Andric }
1746f9448bf3SDimitry Andric 
1747f9448bf3SDimitry Andric void MemCmpExpansion::createResultBlock() {
1748f9448bf3SDimitry Andric   ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
1749f9448bf3SDimitry Andric                                    EndBlock->getParent(), EndBlock);
1750f9448bf3SDimitry Andric }
1751f9448bf3SDimitry Andric 
1752f9448bf3SDimitry Andric // This function creates the IR instructions for loading and comparing 1 byte.
1753db17bf38SDimitry Andric // It loads 1 byte from each source of the memcmp parameters with the given
1754f9448bf3SDimitry Andric // GEPIndex. It then subtracts the two loaded values and adds this result to the
1755f9448bf3SDimitry Andric // final phi node for selecting the memcmp result.
1756edd7eaddSDimitry Andric void MemCmpExpansion::emitLoadCompareByteBlock(unsigned Index,
1757edd7eaddSDimitry Andric                                                unsigned GEPIndex) {
1758f9448bf3SDimitry Andric   Value *Source1 = CI->getArgOperand(0);
1759f9448bf3SDimitry Andric   Value *Source2 = CI->getArgOperand(1);
1760f9448bf3SDimitry Andric 
1761f9448bf3SDimitry Andric   Builder.SetInsertPoint(LoadCmpBlocks[Index]);
1762f9448bf3SDimitry Andric   Type *LoadSizeType = Type::getInt8Ty(CI->getContext());
1763db17bf38SDimitry Andric   // Cast source to LoadSizeType*.
1764f9448bf3SDimitry Andric   if (Source1->getType() != LoadSizeType)
1765f9448bf3SDimitry Andric     Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1766f9448bf3SDimitry Andric   if (Source2->getType() != LoadSizeType)
1767f9448bf3SDimitry Andric     Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1768f9448bf3SDimitry Andric 
1769db17bf38SDimitry Andric   // Get the base address using the GEPIndex.
1770f9448bf3SDimitry Andric   if (GEPIndex != 0) {
1771f9448bf3SDimitry Andric     Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1772f9448bf3SDimitry Andric                                 ConstantInt::get(LoadSizeType, GEPIndex));
1773f9448bf3SDimitry Andric     Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1774f9448bf3SDimitry Andric                                 ConstantInt::get(LoadSizeType, GEPIndex));
1775f9448bf3SDimitry Andric   }
1776f9448bf3SDimitry Andric 
1777f9448bf3SDimitry Andric   Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1778f9448bf3SDimitry Andric   Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1779f9448bf3SDimitry Andric 
1780f9448bf3SDimitry Andric   LoadSrc1 = Builder.CreateZExt(LoadSrc1, Type::getInt32Ty(CI->getContext()));
1781f9448bf3SDimitry Andric   LoadSrc2 = Builder.CreateZExt(LoadSrc2, Type::getInt32Ty(CI->getContext()));
1782f9448bf3SDimitry Andric   Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2);
1783f9448bf3SDimitry Andric 
1784f9448bf3SDimitry Andric   PhiRes->addIncoming(Diff, LoadCmpBlocks[Index]);
1785f9448bf3SDimitry Andric 
1786f9448bf3SDimitry Andric   if (Index < (LoadCmpBlocks.size() - 1)) {
1787db17bf38SDimitry Andric     // Early exit branch if difference found to EndBlock. Otherwise, continue to
1788db17bf38SDimitry Andric     // next LoadCmpBlock,
1789f9448bf3SDimitry Andric     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
1790f9448bf3SDimitry Andric                                     ConstantInt::get(Diff->getType(), 0));
1791f9448bf3SDimitry Andric     BranchInst *CmpBr =
1792f9448bf3SDimitry Andric         BranchInst::Create(EndBlock, LoadCmpBlocks[Index + 1], Cmp);
1793f9448bf3SDimitry Andric     Builder.Insert(CmpBr);
1794f9448bf3SDimitry Andric   } else {
1795db17bf38SDimitry Andric     // The last block has an unconditional branch to EndBlock.
1796f9448bf3SDimitry Andric     BranchInst *CmpBr = BranchInst::Create(EndBlock);
1797f9448bf3SDimitry Andric     Builder.Insert(CmpBr);
1798f9448bf3SDimitry Andric   }
1799f9448bf3SDimitry Andric }
1800f9448bf3SDimitry Andric 
1801f9448bf3SDimitry Andric unsigned MemCmpExpansion::getNumLoads(unsigned Size) {
1802f9448bf3SDimitry Andric   return (Size / MaxLoadSize) + countPopulation(Size % MaxLoadSize);
1803f9448bf3SDimitry Andric }
1804f9448bf3SDimitry Andric 
1805f9448bf3SDimitry Andric unsigned MemCmpExpansion::getLoadSize(unsigned Size) {
1806f9448bf3SDimitry Andric   return MinAlign(PowerOf2Floor(Size), MaxLoadSize);
1807f9448bf3SDimitry Andric }
1808f9448bf3SDimitry Andric 
1809db17bf38SDimitry Andric /// Generate an equality comparison for one or more pairs of loaded values.
1810db17bf38SDimitry Andric /// This is used in the case where the memcmp() call is compared equal or not
1811db17bf38SDimitry Andric /// equal to zero.
1812db17bf38SDimitry Andric Value *MemCmpExpansion::getCompareLoadPairs(unsigned Index, unsigned Size,
1813a580b014SDimitry Andric                                             unsigned &NumBytesProcessed) {
1814f9448bf3SDimitry Andric   std::vector<Value *> XorList, OrList;
1815f9448bf3SDimitry Andric   Value *Diff;
1816f9448bf3SDimitry Andric 
1817f9448bf3SDimitry Andric   unsigned RemainingBytes = Size - NumBytesProcessed;
1818f9448bf3SDimitry Andric   unsigned NumLoadsRemaining = getNumLoads(RemainingBytes);
1819f9448bf3SDimitry Andric   unsigned NumLoads = std::min(NumLoadsRemaining, NumLoadsPerBlock);
1820f9448bf3SDimitry Andric 
1821db17bf38SDimitry Andric   // For a single-block expansion, start inserting before the memcmp call.
1822db17bf38SDimitry Andric   if (LoadCmpBlocks.empty())
1823db17bf38SDimitry Andric     Builder.SetInsertPoint(CI);
1824db17bf38SDimitry Andric   else
1825f9448bf3SDimitry Andric     Builder.SetInsertPoint(LoadCmpBlocks[Index]);
1826f9448bf3SDimitry Andric 
1827db17bf38SDimitry Andric   Value *Cmp = nullptr;
1828f9448bf3SDimitry Andric   for (unsigned i = 0; i < NumLoads; ++i) {
1829f9448bf3SDimitry Andric     unsigned LoadSize = getLoadSize(RemainingBytes);
1830f9448bf3SDimitry Andric     unsigned GEPIndex = NumBytesProcessed / LoadSize;
1831f9448bf3SDimitry Andric     NumBytesProcessed += LoadSize;
1832f9448bf3SDimitry Andric     RemainingBytes -= LoadSize;
1833f9448bf3SDimitry Andric 
1834f9448bf3SDimitry Andric     Type *LoadSizeType = IntegerType::get(CI->getContext(), LoadSize * 8);
1835f9448bf3SDimitry Andric     Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
1836edd7eaddSDimitry Andric     assert(LoadSize <= MaxLoadSize && "Unexpected load type");
1837f9448bf3SDimitry Andric 
1838f9448bf3SDimitry Andric     Value *Source1 = CI->getArgOperand(0);
1839f9448bf3SDimitry Andric     Value *Source2 = CI->getArgOperand(1);
1840f9448bf3SDimitry Andric 
1841db17bf38SDimitry Andric     // Cast source to LoadSizeType*.
1842f9448bf3SDimitry Andric     if (Source1->getType() != LoadSizeType)
1843f9448bf3SDimitry Andric       Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1844f9448bf3SDimitry Andric     if (Source2->getType() != LoadSizeType)
1845f9448bf3SDimitry Andric       Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1846f9448bf3SDimitry Andric 
1847db17bf38SDimitry Andric     // Get the base address using the GEPIndex.
1848f9448bf3SDimitry Andric     if (GEPIndex != 0) {
1849f9448bf3SDimitry Andric       Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1850f9448bf3SDimitry Andric                                   ConstantInt::get(LoadSizeType, GEPIndex));
1851f9448bf3SDimitry Andric       Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1852f9448bf3SDimitry Andric                                   ConstantInt::get(LoadSizeType, GEPIndex));
1853f9448bf3SDimitry Andric     }
1854f9448bf3SDimitry Andric 
1855edd7eaddSDimitry Andric     // Get a constant or load a value for each source address.
1856edd7eaddSDimitry Andric     Value *LoadSrc1 = nullptr;
1857edd7eaddSDimitry Andric     if (auto *Source1C = dyn_cast<Constant>(Source1))
1858edd7eaddSDimitry Andric       LoadSrc1 = ConstantFoldLoadFromConstPtr(Source1C, LoadSizeType, DL);
1859edd7eaddSDimitry Andric     if (!LoadSrc1)
1860edd7eaddSDimitry Andric       LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1861edd7eaddSDimitry Andric 
1862edd7eaddSDimitry Andric     Value *LoadSrc2 = nullptr;
1863edd7eaddSDimitry Andric     if (auto *Source2C = dyn_cast<Constant>(Source2))
1864edd7eaddSDimitry Andric       LoadSrc2 = ConstantFoldLoadFromConstPtr(Source2C, LoadSizeType, DL);
1865edd7eaddSDimitry Andric     if (!LoadSrc2)
1866edd7eaddSDimitry Andric       LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1867edd7eaddSDimitry Andric 
1868db17bf38SDimitry Andric     if (NumLoads != 1) {
1869f9448bf3SDimitry Andric       if (LoadSizeType != MaxLoadType) {
1870edd7eaddSDimitry Andric         LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType);
1871edd7eaddSDimitry Andric         LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType);
1872f9448bf3SDimitry Andric       }
1873db17bf38SDimitry Andric       // If we have multiple loads per block, we need to generate a composite
1874db17bf38SDimitry Andric       // comparison using xor+or.
1875f9448bf3SDimitry Andric       Diff = Builder.CreateXor(LoadSrc1, LoadSrc2);
1876edd7eaddSDimitry Andric       Diff = Builder.CreateZExt(Diff, MaxLoadType);
1877f9448bf3SDimitry Andric       XorList.push_back(Diff);
1878db17bf38SDimitry Andric     } else {
1879db17bf38SDimitry Andric       // If there's only one load per block, we just compare the loaded values.
1880db17bf38SDimitry Andric       Cmp = Builder.CreateICmpNE(LoadSrc1, LoadSrc2);
1881db17bf38SDimitry Andric     }
1882f9448bf3SDimitry Andric   }
1883f9448bf3SDimitry Andric 
1884f9448bf3SDimitry Andric   auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
1885f9448bf3SDimitry Andric     std::vector<Value *> OutList;
1886f9448bf3SDimitry Andric     for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
1887f9448bf3SDimitry Andric       Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
1888f9448bf3SDimitry Andric       OutList.push_back(Or);
1889f9448bf3SDimitry Andric     }
1890f9448bf3SDimitry Andric     if (InList.size() % 2 != 0)
1891f9448bf3SDimitry Andric       OutList.push_back(InList.back());
1892f9448bf3SDimitry Andric     return OutList;
1893f9448bf3SDimitry Andric   };
1894f9448bf3SDimitry Andric 
1895db17bf38SDimitry Andric   if (!Cmp) {
1896db17bf38SDimitry Andric     // Pairwise OR the XOR results.
1897f9448bf3SDimitry Andric     OrList = pairWiseOr(XorList);
1898f9448bf3SDimitry Andric 
1899db17bf38SDimitry Andric     // Pairwise OR the OR results until one result left.
1900f9448bf3SDimitry Andric     while (OrList.size() != 1) {
1901f9448bf3SDimitry Andric       OrList = pairWiseOr(OrList);
1902f9448bf3SDimitry Andric     }
1903db17bf38SDimitry Andric     Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
1904db17bf38SDimitry Andric   }
1905f9448bf3SDimitry Andric 
1906db17bf38SDimitry Andric   return Cmp;
1907db17bf38SDimitry Andric }
1908db17bf38SDimitry Andric 
1909db17bf38SDimitry Andric void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(
1910db17bf38SDimitry Andric     unsigned Index, unsigned Size, unsigned &NumBytesProcessed) {
1911a580b014SDimitry Andric   Value *Cmp = getCompareLoadPairs(Index, Size, NumBytesProcessed);
1912db17bf38SDimitry Andric 
1913f9448bf3SDimitry Andric   BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1))
1914f9448bf3SDimitry Andric                            ? EndBlock
1915f9448bf3SDimitry Andric                            : LoadCmpBlocks[Index + 1];
1916db17bf38SDimitry Andric   // Early exit branch if difference found to ResultBlock. Otherwise,
1917db17bf38SDimitry Andric   // continue to next LoadCmpBlock or EndBlock.
1918f9448bf3SDimitry Andric   BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
1919f9448bf3SDimitry Andric   Builder.Insert(CmpBr);
1920f9448bf3SDimitry Andric 
1921f9448bf3SDimitry Andric   // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
1922f9448bf3SDimitry Andric   // since early exit to ResultBlock was not taken (no difference was found in
1923db17bf38SDimitry Andric   // any of the bytes).
1924f9448bf3SDimitry Andric   if (Index == LoadCmpBlocks.size() - 1) {
1925f9448bf3SDimitry Andric     Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
1926f9448bf3SDimitry Andric     PhiRes->addIncoming(Zero, LoadCmpBlocks[Index]);
1927f9448bf3SDimitry Andric   }
1928f9448bf3SDimitry Andric }
1929f9448bf3SDimitry Andric 
1930f9448bf3SDimitry Andric // This function creates the IR intructions for loading and comparing using the
1931f9448bf3SDimitry Andric // given LoadSize. It loads the number of bytes specified by LoadSize from each
1932f9448bf3SDimitry Andric // source of the memcmp parameters. It then does a subtract to see if there was
1933f9448bf3SDimitry Andric // a difference in the loaded values. If a difference is found, it branches
1934f9448bf3SDimitry Andric // with an early exit to the ResultBlock for calculating which source was
1935f9448bf3SDimitry Andric // larger. Otherwise, it falls through to the either the next LoadCmpBlock or
1936f9448bf3SDimitry Andric // the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
1937f9448bf3SDimitry Andric // a special case through emitLoadCompareByteBlock. The special handling can
1938f9448bf3SDimitry Andric // simply subtract the loaded values and add it to the result phi node.
1939edd7eaddSDimitry Andric void MemCmpExpansion::emitLoadCompareBlock(unsigned Index, unsigned LoadSize,
1940edd7eaddSDimitry Andric                                            unsigned GEPIndex) {
1941f9448bf3SDimitry Andric   if (LoadSize == 1) {
1942f9448bf3SDimitry Andric     MemCmpExpansion::emitLoadCompareByteBlock(Index, GEPIndex);
1943f9448bf3SDimitry Andric     return;
1944f9448bf3SDimitry Andric   }
1945f9448bf3SDimitry Andric 
1946f9448bf3SDimitry Andric   Type *LoadSizeType = IntegerType::get(CI->getContext(), LoadSize * 8);
1947f9448bf3SDimitry Andric   Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
1948edd7eaddSDimitry Andric   assert(LoadSize <= MaxLoadSize && "Unexpected load type");
1949f9448bf3SDimitry Andric 
1950f9448bf3SDimitry Andric   Value *Source1 = CI->getArgOperand(0);
1951f9448bf3SDimitry Andric   Value *Source2 = CI->getArgOperand(1);
1952f9448bf3SDimitry Andric 
1953f9448bf3SDimitry Andric   Builder.SetInsertPoint(LoadCmpBlocks[Index]);
1954db17bf38SDimitry Andric   // Cast source to LoadSizeType*.
1955f9448bf3SDimitry Andric   if (Source1->getType() != LoadSizeType)
1956f9448bf3SDimitry Andric     Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1957f9448bf3SDimitry Andric   if (Source2->getType() != LoadSizeType)
1958f9448bf3SDimitry Andric     Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1959f9448bf3SDimitry Andric 
1960db17bf38SDimitry Andric   // Get the base address using the GEPIndex.
1961f9448bf3SDimitry Andric   if (GEPIndex != 0) {
1962f9448bf3SDimitry Andric     Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1963f9448bf3SDimitry Andric                                 ConstantInt::get(LoadSizeType, GEPIndex));
1964f9448bf3SDimitry Andric     Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1965f9448bf3SDimitry Andric                                 ConstantInt::get(LoadSizeType, GEPIndex));
1966f9448bf3SDimitry Andric   }
1967f9448bf3SDimitry Andric 
1968db17bf38SDimitry Andric   // Load LoadSizeType from the base address.
1969f9448bf3SDimitry Andric   Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1970f9448bf3SDimitry Andric   Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1971f9448bf3SDimitry Andric 
1972db17bf38SDimitry Andric   if (DL.isLittleEndian()) {
1973a580b014SDimitry Andric     Function *Bswap = Intrinsic::getDeclaration(CI->getModule(),
1974f9448bf3SDimitry Andric                                                 Intrinsic::bswap, LoadSizeType);
1975f9448bf3SDimitry Andric     LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1);
1976f9448bf3SDimitry Andric     LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2);
1977f9448bf3SDimitry Andric   }
1978f9448bf3SDimitry Andric 
1979f9448bf3SDimitry Andric   if (LoadSizeType != MaxLoadType) {
1980edd7eaddSDimitry Andric     LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType);
1981edd7eaddSDimitry Andric     LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType);
1982f9448bf3SDimitry Andric   }
1983f9448bf3SDimitry Andric 
1984f9448bf3SDimitry Andric   // Add the loaded values to the phi nodes for calculating memcmp result only
1985f9448bf3SDimitry Andric   // if result is not used in a zero equality.
1986f9448bf3SDimitry Andric   if (!IsUsedForZeroCmp) {
1987f9448bf3SDimitry Andric     ResBlock.PhiSrc1->addIncoming(LoadSrc1, LoadCmpBlocks[Index]);
1988f9448bf3SDimitry Andric     ResBlock.PhiSrc2->addIncoming(LoadSrc2, LoadCmpBlocks[Index]);
1989f9448bf3SDimitry Andric   }
1990f9448bf3SDimitry Andric 
1991a580b014SDimitry Andric   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, LoadSrc1, LoadSrc2);
1992f9448bf3SDimitry Andric   BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1))
1993f9448bf3SDimitry Andric                            ? EndBlock
1994f9448bf3SDimitry Andric                            : LoadCmpBlocks[Index + 1];
1995db17bf38SDimitry Andric   // Early exit branch if difference found to ResultBlock. Otherwise, continue
1996db17bf38SDimitry Andric   // to next LoadCmpBlock or EndBlock.
1997a580b014SDimitry Andric   BranchInst *CmpBr = BranchInst::Create(NextBB, ResBlock.BB, Cmp);
1998f9448bf3SDimitry Andric   Builder.Insert(CmpBr);
1999f9448bf3SDimitry Andric 
2000f9448bf3SDimitry Andric   // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
2001f9448bf3SDimitry Andric   // since early exit to ResultBlock was not taken (no difference was found in
2002db17bf38SDimitry Andric   // any of the bytes).
2003f9448bf3SDimitry Andric   if (Index == LoadCmpBlocks.size() - 1) {
2004f9448bf3SDimitry Andric     Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
2005f9448bf3SDimitry Andric     PhiRes->addIncoming(Zero, LoadCmpBlocks[Index]);
2006f9448bf3SDimitry Andric   }
2007f9448bf3SDimitry Andric }
2008f9448bf3SDimitry Andric 
2009f9448bf3SDimitry Andric // This function populates the ResultBlock with a sequence to calculate the
2010f9448bf3SDimitry Andric // memcmp result. It compares the two loaded source values and returns -1 if
2011f9448bf3SDimitry Andric // src1 < src2 and 1 if src1 > src2.
2012db17bf38SDimitry Andric void MemCmpExpansion::emitMemCmpResultBlock() {
2013f9448bf3SDimitry Andric   // Special case: if memcmp result is used in a zero equality, result does not
2014f9448bf3SDimitry Andric   // need to be calculated and can simply return 1.
2015f9448bf3SDimitry Andric   if (IsUsedForZeroCmp) {
2016f9448bf3SDimitry Andric     BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
2017f9448bf3SDimitry Andric     Builder.SetInsertPoint(ResBlock.BB, InsertPt);
2018f9448bf3SDimitry Andric     Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
2019f9448bf3SDimitry Andric     PhiRes->addIncoming(Res, ResBlock.BB);
2020f9448bf3SDimitry Andric     BranchInst *NewBr = BranchInst::Create(EndBlock);
2021f9448bf3SDimitry Andric     Builder.Insert(NewBr);
2022f9448bf3SDimitry Andric     return;
2023f9448bf3SDimitry Andric   }
2024f9448bf3SDimitry Andric   BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
2025f9448bf3SDimitry Andric   Builder.SetInsertPoint(ResBlock.BB, InsertPt);
2026f9448bf3SDimitry Andric 
2027f9448bf3SDimitry Andric   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
2028f9448bf3SDimitry Andric                                   ResBlock.PhiSrc2);
2029f9448bf3SDimitry Andric 
2030f9448bf3SDimitry Andric   Value *Res =
2031f9448bf3SDimitry Andric       Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1),
2032f9448bf3SDimitry Andric                            ConstantInt::get(Builder.getInt32Ty(), 1));
2033f9448bf3SDimitry Andric 
2034f9448bf3SDimitry Andric   BranchInst *NewBr = BranchInst::Create(EndBlock);
2035f9448bf3SDimitry Andric   Builder.Insert(NewBr);
2036f9448bf3SDimitry Andric   PhiRes->addIncoming(Res, ResBlock.BB);
2037f9448bf3SDimitry Andric }
2038f9448bf3SDimitry Andric 
2039edd7eaddSDimitry Andric unsigned MemCmpExpansion::calculateNumBlocks(unsigned Size) {
2040edd7eaddSDimitry Andric   unsigned NumBlocks = 0;
2041db17bf38SDimitry Andric   bool HaveOneByteLoad = false;
2042f9448bf3SDimitry Andric   unsigned RemainingSize = Size;
2043f9448bf3SDimitry Andric   unsigned LoadSize = MaxLoadSize;
2044f9448bf3SDimitry Andric   while (RemainingSize) {
2045f9448bf3SDimitry Andric     if (LoadSize == 1)
2046db17bf38SDimitry Andric       HaveOneByteLoad = true;
2047f9448bf3SDimitry Andric     NumBlocks += RemainingSize / LoadSize;
2048f9448bf3SDimitry Andric     RemainingSize = RemainingSize % LoadSize;
2049f9448bf3SDimitry Andric     LoadSize = LoadSize / 2;
2050f9448bf3SDimitry Andric   }
2051db17bf38SDimitry Andric   NumBlocksNonOneByte = HaveOneByteLoad ? (NumBlocks - 1) : NumBlocks;
2052f9448bf3SDimitry Andric 
2053f9448bf3SDimitry Andric   if (IsUsedForZeroCmp)
2054f9448bf3SDimitry Andric     NumBlocks = NumBlocks / NumLoadsPerBlock +
2055f9448bf3SDimitry Andric                 (NumBlocks % NumLoadsPerBlock != 0 ? 1 : 0);
2056f9448bf3SDimitry Andric 
2057f9448bf3SDimitry Andric   return NumBlocks;
2058f9448bf3SDimitry Andric }
2059f9448bf3SDimitry Andric 
2060f9448bf3SDimitry Andric void MemCmpExpansion::setupResultBlockPHINodes() {
2061f9448bf3SDimitry Andric   Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
2062f9448bf3SDimitry Andric   Builder.SetInsertPoint(ResBlock.BB);
2063f9448bf3SDimitry Andric   ResBlock.PhiSrc1 =
2064f9448bf3SDimitry Andric       Builder.CreatePHI(MaxLoadType, NumBlocksNonOneByte, "phi.src1");
2065f9448bf3SDimitry Andric   ResBlock.PhiSrc2 =
2066f9448bf3SDimitry Andric       Builder.CreatePHI(MaxLoadType, NumBlocksNonOneByte, "phi.src2");
2067f9448bf3SDimitry Andric }
2068f9448bf3SDimitry Andric 
2069f9448bf3SDimitry Andric void MemCmpExpansion::setupEndBlockPHINodes() {
2070f9448bf3SDimitry Andric   Builder.SetInsertPoint(&EndBlock->front());
2071f9448bf3SDimitry Andric   PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
2072f9448bf3SDimitry Andric }
2073f9448bf3SDimitry Andric 
2074db17bf38SDimitry Andric Value *MemCmpExpansion::getMemCmpExpansionZeroCase(unsigned Size) {
2075f9448bf3SDimitry Andric   unsigned NumBytesProcessed = 0;
2076db17bf38SDimitry Andric   // This loop populates each of the LoadCmpBlocks with the IR sequence to
2077db17bf38SDimitry Andric   // handle multiple loads per block.
2078db17bf38SDimitry Andric   for (unsigned i = 0; i < NumBlocks; ++i)
2079f9448bf3SDimitry Andric     emitLoadCompareBlockMultipleLoads(i, Size, NumBytesProcessed);
2080db17bf38SDimitry Andric 
2081db17bf38SDimitry Andric   emitMemCmpResultBlock();
2082db17bf38SDimitry Andric   return PhiRes;
2083f9448bf3SDimitry Andric }
2084f9448bf3SDimitry Andric 
2085db17bf38SDimitry Andric /// A memcmp expansion that compares equality with 0 and only has one block of
2086db17bf38SDimitry Andric /// load and compare can bypass the compare, branch, and phi IR that is required
2087db17bf38SDimitry Andric /// in the general case.
2088db17bf38SDimitry Andric Value *MemCmpExpansion::getMemCmpEqZeroOneBlock(unsigned Size) {
2089db17bf38SDimitry Andric   unsigned NumBytesProcessed = 0;
2090a580b014SDimitry Andric   Value *Cmp = getCompareLoadPairs(0, Size, NumBytesProcessed);
2091db17bf38SDimitry Andric   return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext()));
2092f9448bf3SDimitry Andric }
2093f9448bf3SDimitry Andric 
2094a580b014SDimitry Andric /// A memcmp expansion that only has one block of load and compare can bypass
2095a580b014SDimitry Andric /// the compare, branch, and phi IR that is required in the general case.
2096a580b014SDimitry Andric Value *MemCmpExpansion::getMemCmpOneBlock(unsigned Size) {
2097a580b014SDimitry Andric   assert(NumLoadsPerBlock == 1 && "Only handles one load pair per block");
2098a580b014SDimitry Andric 
2099a580b014SDimitry Andric   Type *LoadSizeType = IntegerType::get(CI->getContext(), Size * 8);
2100a580b014SDimitry Andric   Value *Source1 = CI->getArgOperand(0);
2101a580b014SDimitry Andric   Value *Source2 = CI->getArgOperand(1);
2102a580b014SDimitry Andric 
2103a580b014SDimitry Andric   // Cast source to LoadSizeType*.
2104a580b014SDimitry Andric   if (Source1->getType() != LoadSizeType)
2105a580b014SDimitry Andric     Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
2106a580b014SDimitry Andric   if (Source2->getType() != LoadSizeType)
2107a580b014SDimitry Andric     Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
2108a580b014SDimitry Andric 
2109a580b014SDimitry Andric   // Load LoadSizeType from the base address.
2110a580b014SDimitry Andric   Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
2111a580b014SDimitry Andric   Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
2112a580b014SDimitry Andric 
2113a580b014SDimitry Andric   if (DL.isLittleEndian() && Size != 1) {
2114a580b014SDimitry Andric     Function *Bswap = Intrinsic::getDeclaration(CI->getModule(),
2115a580b014SDimitry Andric                                                 Intrinsic::bswap, LoadSizeType);
2116a580b014SDimitry Andric     LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1);
2117a580b014SDimitry Andric     LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2);
2118a580b014SDimitry Andric   }
2119a580b014SDimitry Andric 
2120a580b014SDimitry Andric   // TODO: Instead of comparing ULT, just subtract and return the difference?
2121a580b014SDimitry Andric   Value *CmpNE = Builder.CreateICmpNE(LoadSrc1, LoadSrc2);
2122a580b014SDimitry Andric   Value *CmpULT = Builder.CreateICmpULT(LoadSrc1, LoadSrc2);
2123a580b014SDimitry Andric   Type *I32 = Builder.getInt32Ty();
2124a580b014SDimitry Andric   Value *Sel1 = Builder.CreateSelect(CmpULT, ConstantInt::get(I32, -1),
2125a580b014SDimitry Andric                                              ConstantInt::get(I32, 1));
2126a580b014SDimitry Andric   return Builder.CreateSelect(CmpNE, Sel1, ConstantInt::get(I32, 0));
2127a580b014SDimitry Andric }
2128a580b014SDimitry Andric 
2129f9448bf3SDimitry Andric // This function expands the memcmp call into an inline expansion and returns
2130f9448bf3SDimitry Andric // the memcmp result.
2131db17bf38SDimitry Andric Value *MemCmpExpansion::getMemCmpExpansion(uint64_t Size) {
2132db17bf38SDimitry Andric   if (IsUsedForZeroCmp)
2133db17bf38SDimitry Andric     return NumBlocks == 1 ? getMemCmpEqZeroOneBlock(Size) :
2134db17bf38SDimitry Andric                             getMemCmpExpansionZeroCase(Size);
2135f9448bf3SDimitry Andric 
2136a580b014SDimitry Andric   // TODO: Handle more than one load pair per block in getMemCmpOneBlock().
2137a580b014SDimitry Andric   if (NumBlocks == 1 && NumLoadsPerBlock == 1)
2138a580b014SDimitry Andric     return getMemCmpOneBlock(Size);
2139a580b014SDimitry Andric 
2140db17bf38SDimitry Andric   // This loop calls emitLoadCompareBlock for comparing Size bytes of the two
2141db17bf38SDimitry Andric   // memcmp sources. It starts with loading using the maximum load size set by
2142f9448bf3SDimitry Andric   // the target. It processes any remaining bytes using a load size which is the
2143f9448bf3SDimitry Andric   // next smallest power of 2.
2144edd7eaddSDimitry Andric   unsigned LoadSize = MaxLoadSize;
2145edd7eaddSDimitry Andric   unsigned NumBytesToBeProcessed = Size;
2146db17bf38SDimitry Andric   unsigned Index = 0;
2147f9448bf3SDimitry Andric   while (NumBytesToBeProcessed) {
2148db17bf38SDimitry Andric     // Calculate how many blocks we can create with the current load size.
2149edd7eaddSDimitry Andric     unsigned NumBlocks = NumBytesToBeProcessed / LoadSize;
2150edd7eaddSDimitry Andric     unsigned GEPIndex = (Size - NumBytesToBeProcessed) / LoadSize;
2151f9448bf3SDimitry Andric     NumBytesToBeProcessed = NumBytesToBeProcessed % LoadSize;
2152f9448bf3SDimitry Andric 
2153f9448bf3SDimitry Andric     // For each NumBlocks, populate the instruction sequence for loading and
2154db17bf38SDimitry Andric     // comparing LoadSize bytes.
2155f9448bf3SDimitry Andric     while (NumBlocks--) {
2156db17bf38SDimitry Andric       emitLoadCompareBlock(Index, LoadSize, GEPIndex);
2157f9448bf3SDimitry Andric       Index++;
2158f9448bf3SDimitry Andric       GEPIndex++;
2159f9448bf3SDimitry Andric     }
2160db17bf38SDimitry Andric     // Get the next LoadSize to use.
2161f9448bf3SDimitry Andric     LoadSize = LoadSize / 2;
2162f9448bf3SDimitry Andric   }
2163f9448bf3SDimitry Andric 
2164db17bf38SDimitry Andric   emitMemCmpResultBlock();
2165f9448bf3SDimitry Andric   return PhiRes;
2166f9448bf3SDimitry Andric }
2167f9448bf3SDimitry Andric 
2168f9448bf3SDimitry Andric // This function checks to see if an expansion of memcmp can be generated.
2169f9448bf3SDimitry Andric // It checks for constant compare size that is less than the max inline size.
2170f9448bf3SDimitry Andric // If an expansion cannot occur, returns false to leave as a library call.
2171db17bf38SDimitry Andric // Otherwise, the library call is replaced with a new IR instruction sequence.
2172f9448bf3SDimitry Andric /// We want to transform:
2173f9448bf3SDimitry Andric /// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
2174f9448bf3SDimitry Andric /// To:
2175f9448bf3SDimitry Andric /// loadbb:
2176f9448bf3SDimitry Andric ///  %0 = bitcast i32* %buffer2 to i8*
2177f9448bf3SDimitry Andric ///  %1 = bitcast i32* %buffer1 to i8*
2178f9448bf3SDimitry Andric ///  %2 = bitcast i8* %1 to i64*
2179f9448bf3SDimitry Andric ///  %3 = bitcast i8* %0 to i64*
2180f9448bf3SDimitry Andric ///  %4 = load i64, i64* %2
2181f9448bf3SDimitry Andric ///  %5 = load i64, i64* %3
2182f9448bf3SDimitry Andric ///  %6 = call i64 @llvm.bswap.i64(i64 %4)
2183f9448bf3SDimitry Andric ///  %7 = call i64 @llvm.bswap.i64(i64 %5)
2184f9448bf3SDimitry Andric ///  %8 = sub i64 %6, %7
2185f9448bf3SDimitry Andric ///  %9 = icmp ne i64 %8, 0
2186f9448bf3SDimitry Andric ///  br i1 %9, label %res_block, label %loadbb1
2187f9448bf3SDimitry Andric /// res_block:                                        ; preds = %loadbb2,
2188f9448bf3SDimitry Andric /// %loadbb1, %loadbb
2189f9448bf3SDimitry Andric ///  %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
2190f9448bf3SDimitry Andric ///  %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
2191f9448bf3SDimitry Andric ///  %10 = icmp ult i64 %phi.src1, %phi.src2
2192f9448bf3SDimitry Andric ///  %11 = select i1 %10, i32 -1, i32 1
2193f9448bf3SDimitry Andric ///  br label %endblock
2194f9448bf3SDimitry Andric /// loadbb1:                                          ; preds = %loadbb
2195f9448bf3SDimitry Andric ///  %12 = bitcast i32* %buffer2 to i8*
2196f9448bf3SDimitry Andric ///  %13 = bitcast i32* %buffer1 to i8*
2197f9448bf3SDimitry Andric ///  %14 = bitcast i8* %13 to i32*
2198f9448bf3SDimitry Andric ///  %15 = bitcast i8* %12 to i32*
2199f9448bf3SDimitry Andric ///  %16 = getelementptr i32, i32* %14, i32 2
2200f9448bf3SDimitry Andric ///  %17 = getelementptr i32, i32* %15, i32 2
2201f9448bf3SDimitry Andric ///  %18 = load i32, i32* %16
2202f9448bf3SDimitry Andric ///  %19 = load i32, i32* %17
2203f9448bf3SDimitry Andric ///  %20 = call i32 @llvm.bswap.i32(i32 %18)
2204f9448bf3SDimitry Andric ///  %21 = call i32 @llvm.bswap.i32(i32 %19)
2205f9448bf3SDimitry Andric ///  %22 = zext i32 %20 to i64
2206f9448bf3SDimitry Andric ///  %23 = zext i32 %21 to i64
2207f9448bf3SDimitry Andric ///  %24 = sub i64 %22, %23
2208f9448bf3SDimitry Andric ///  %25 = icmp ne i64 %24, 0
2209f9448bf3SDimitry Andric ///  br i1 %25, label %res_block, label %loadbb2
2210f9448bf3SDimitry Andric /// loadbb2:                                          ; preds = %loadbb1
2211f9448bf3SDimitry Andric ///  %26 = bitcast i32* %buffer2 to i8*
2212f9448bf3SDimitry Andric ///  %27 = bitcast i32* %buffer1 to i8*
2213f9448bf3SDimitry Andric ///  %28 = bitcast i8* %27 to i16*
2214f9448bf3SDimitry Andric ///  %29 = bitcast i8* %26 to i16*
2215f9448bf3SDimitry Andric ///  %30 = getelementptr i16, i16* %28, i16 6
2216f9448bf3SDimitry Andric ///  %31 = getelementptr i16, i16* %29, i16 6
2217f9448bf3SDimitry Andric ///  %32 = load i16, i16* %30
2218f9448bf3SDimitry Andric ///  %33 = load i16, i16* %31
2219f9448bf3SDimitry Andric ///  %34 = call i16 @llvm.bswap.i16(i16 %32)
2220f9448bf3SDimitry Andric ///  %35 = call i16 @llvm.bswap.i16(i16 %33)
2221f9448bf3SDimitry Andric ///  %36 = zext i16 %34 to i64
2222f9448bf3SDimitry Andric ///  %37 = zext i16 %35 to i64
2223f9448bf3SDimitry Andric ///  %38 = sub i64 %36, %37
2224f9448bf3SDimitry Andric ///  %39 = icmp ne i64 %38, 0
2225f9448bf3SDimitry Andric ///  br i1 %39, label %res_block, label %loadbb3
2226f9448bf3SDimitry Andric /// loadbb3:                                          ; preds = %loadbb2
2227f9448bf3SDimitry Andric ///  %40 = bitcast i32* %buffer2 to i8*
2228f9448bf3SDimitry Andric ///  %41 = bitcast i32* %buffer1 to i8*
2229f9448bf3SDimitry Andric ///  %42 = getelementptr i8, i8* %41, i8 14
2230f9448bf3SDimitry Andric ///  %43 = getelementptr i8, i8* %40, i8 14
2231f9448bf3SDimitry Andric ///  %44 = load i8, i8* %42
2232f9448bf3SDimitry Andric ///  %45 = load i8, i8* %43
2233f9448bf3SDimitry Andric ///  %46 = zext i8 %44 to i32
2234f9448bf3SDimitry Andric ///  %47 = zext i8 %45 to i32
2235f9448bf3SDimitry Andric ///  %48 = sub i32 %46, %47
2236f9448bf3SDimitry Andric ///  br label %endblock
2237f9448bf3SDimitry Andric /// endblock:                                         ; preds = %res_block,
2238f9448bf3SDimitry Andric /// %loadbb3
2239f9448bf3SDimitry Andric ///  %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
2240f9448bf3SDimitry Andric ///  ret i32 %phi.res
2241f9448bf3SDimitry Andric static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
2242f9448bf3SDimitry Andric                          const TargetLowering *TLI, const DataLayout *DL) {
2243f9448bf3SDimitry Andric   NumMemCmpCalls++;
2244f9448bf3SDimitry Andric 
2245db17bf38SDimitry Andric   // TTI call to check if target would like to expand memcmp. Also, get the
2246db17bf38SDimitry Andric   // MaxLoadSize.
2247f9448bf3SDimitry Andric   unsigned MaxLoadSize;
2248f9448bf3SDimitry Andric   if (!TTI->expandMemCmp(CI, MaxLoadSize))
2249f9448bf3SDimitry Andric     return false;
2250f9448bf3SDimitry Andric 
2251db17bf38SDimitry Andric   // Early exit from expansion if -Oz.
2252db17bf38SDimitry Andric   if (CI->getFunction()->optForMinSize())
2253f9448bf3SDimitry Andric     return false;
2254f9448bf3SDimitry Andric 
2255db17bf38SDimitry Andric   // Early exit from expansion if size is not a constant.
2256f9448bf3SDimitry Andric   ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2257f9448bf3SDimitry Andric   if (!SizeCast) {
2258f9448bf3SDimitry Andric     NumMemCmpNotConstant++;
2259f9448bf3SDimitry Andric     return false;
2260f9448bf3SDimitry Andric   }
2261f9448bf3SDimitry Andric 
2262db17bf38SDimitry Andric   // Early exit from expansion if size greater than max bytes to load.
2263f9448bf3SDimitry Andric   uint64_t SizeVal = SizeCast->getZExtValue();
2264f9448bf3SDimitry Andric   unsigned NumLoads = 0;
2265f9448bf3SDimitry Andric   unsigned RemainingSize = SizeVal;
2266f9448bf3SDimitry Andric   unsigned LoadSize = MaxLoadSize;
2267f9448bf3SDimitry Andric   while (RemainingSize) {
2268f9448bf3SDimitry Andric     NumLoads += RemainingSize / LoadSize;
2269f9448bf3SDimitry Andric     RemainingSize = RemainingSize % LoadSize;
2270f9448bf3SDimitry Andric     LoadSize = LoadSize / 2;
2271f9448bf3SDimitry Andric   }
2272f9448bf3SDimitry Andric 
2273db17bf38SDimitry Andric   if (NumLoads > TLI->getMaxExpandSizeMemcmp(CI->getFunction()->optForSize())) {
2274f9448bf3SDimitry Andric     NumMemCmpGreaterThanMax++;
2275f9448bf3SDimitry Andric     return false;
2276f9448bf3SDimitry Andric   }
2277f9448bf3SDimitry Andric 
2278f9448bf3SDimitry Andric   NumMemCmpInlined++;
2279f9448bf3SDimitry Andric 
2280db17bf38SDimitry Andric   // MemCmpHelper object creates and sets up basic blocks required for
2281db17bf38SDimitry Andric   // expanding memcmp with size SizeVal.
2282f9448bf3SDimitry Andric   unsigned NumLoadsPerBlock = MemCmpNumLoadsPerBlock;
2283db17bf38SDimitry Andric   MemCmpExpansion MemCmpHelper(CI, SizeVal, MaxLoadSize, NumLoadsPerBlock, *DL);
2284f9448bf3SDimitry Andric 
2285db17bf38SDimitry Andric   Value *Res = MemCmpHelper.getMemCmpExpansion(SizeVal);
2286f9448bf3SDimitry Andric 
2287db17bf38SDimitry Andric   // Replace call with result of expansion and erase call.
2288f9448bf3SDimitry Andric   CI->replaceAllUsesWith(Res);
2289f9448bf3SDimitry Andric   CI->eraseFromParent();
2290f9448bf3SDimitry Andric 
2291f9448bf3SDimitry Andric   return true;
2292f9448bf3SDimitry Andric }
2293f9448bf3SDimitry Andric 
22947d523365SDimitry Andric bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
229591bc56edSDimitry Andric   BasicBlock *BB = CI->getParent();
229691bc56edSDimitry Andric 
229791bc56edSDimitry Andric   // Lower inline assembly if we can.
229891bc56edSDimitry Andric   // If we found an inline asm expession, and if the target knows how to
229991bc56edSDimitry Andric   // lower it to normal LLVM code, do so now.
230091bc56edSDimitry Andric   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
230191bc56edSDimitry Andric     if (TLI->ExpandInlineAsm(CI)) {
230291bc56edSDimitry Andric       // Avoid invalidating the iterator.
230391bc56edSDimitry Andric       CurInstIterator = BB->begin();
230491bc56edSDimitry Andric       // Avoid processing instructions out of order, which could cause
230591bc56edSDimitry Andric       // reuse before a value is defined.
230691bc56edSDimitry Andric       SunkAddrs.clear();
230791bc56edSDimitry Andric       return true;
230891bc56edSDimitry Andric     }
230991bc56edSDimitry Andric     // Sink address computing for memory operands into the block.
23107d523365SDimitry Andric     if (optimizeInlineAsmInst(CI))
231191bc56edSDimitry Andric       return true;
231291bc56edSDimitry Andric   }
231391bc56edSDimitry Andric 
2314ff0cc061SDimitry Andric   // Align the pointer arguments to this call if the target thinks it's a good
2315ff0cc061SDimitry Andric   // idea
2316ff0cc061SDimitry Andric   unsigned MinSize, PrefAlign;
2317875ed548SDimitry Andric   if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2318ff0cc061SDimitry Andric     for (auto &Arg : CI->arg_operands()) {
2319ff0cc061SDimitry Andric       // We want to align both objects whose address is used directly and
2320ff0cc061SDimitry Andric       // objects whose address is used in casts and GEPs, though it only makes
2321ff0cc061SDimitry Andric       // sense for GEPs if the offset is a multiple of the desired alignment and
2322ff0cc061SDimitry Andric       // if size - offset meets the size threshold.
2323ff0cc061SDimitry Andric       if (!Arg->getType()->isPointerTy())
2324ff0cc061SDimitry Andric         continue;
2325875ed548SDimitry Andric       APInt Offset(DL->getPointerSizeInBits(
2326875ed548SDimitry Andric                        cast<PointerType>(Arg->getType())->getAddressSpace()),
2327875ed548SDimitry Andric                    0);
2328875ed548SDimitry Andric       Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2329ff0cc061SDimitry Andric       uint64_t Offset2 = Offset.getLimitedValue();
2330ff0cc061SDimitry Andric       if ((Offset2 & (PrefAlign-1)) != 0)
2331ff0cc061SDimitry Andric         continue;
2332ff0cc061SDimitry Andric       AllocaInst *AI;
2333875ed548SDimitry Andric       if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2334875ed548SDimitry Andric           DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2335ff0cc061SDimitry Andric         AI->setAlignment(PrefAlign);
2336ff0cc061SDimitry Andric       // Global variables can only be aligned if they are defined in this
2337ff0cc061SDimitry Andric       // object (i.e. they are uniquely initialized in this object), and
2338ff0cc061SDimitry Andric       // over-aligning global variables that have an explicit section is
2339ff0cc061SDimitry Andric       // forbidden.
2340ff0cc061SDimitry Andric       GlobalVariable *GV;
2341cdd9644cSDimitry Andric       if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
23423ca95b02SDimitry Andric           GV->getPointerAlignment(*DL) < PrefAlign &&
23433ca95b02SDimitry Andric           DL->getTypeAllocSize(GV->getValueType()) >=
2344875ed548SDimitry Andric               MinSize + Offset2)
2345ff0cc061SDimitry Andric         GV->setAlignment(PrefAlign);
2346ff0cc061SDimitry Andric     }
2347ff0cc061SDimitry Andric     // If this is a memcpy (or similar) then we may be able to improve the
2348ff0cc061SDimitry Andric     // alignment
2349ff0cc061SDimitry Andric     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2350875ed548SDimitry Andric       unsigned Align = getKnownAlignment(MI->getDest(), *DL);
2351ff0cc061SDimitry Andric       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
2352875ed548SDimitry Andric         Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
2353ff0cc061SDimitry Andric       if (Align > MI->getAlignment())
2354ff0cc061SDimitry Andric         MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
2355ff0cc061SDimitry Andric     }
2356ff0cc061SDimitry Andric   }
2357ff0cc061SDimitry Andric 
23583ca95b02SDimitry Andric   // If we have a cold call site, try to sink addressing computation into the
23593ca95b02SDimitry Andric   // cold block.  This interacts with our handling for loads and stores to
23603ca95b02SDimitry Andric   // ensure that we can fold all uses of a potential addressing computation
23613ca95b02SDimitry Andric   // into their uses.  TODO: generalize this to work over profiling data
23623ca95b02SDimitry Andric   if (!OptSize && CI->hasFnAttr(Attribute::Cold))
23633ca95b02SDimitry Andric     for (auto &Arg : CI->arg_operands()) {
23643ca95b02SDimitry Andric       if (!Arg->getType()->isPointerTy())
23653ca95b02SDimitry Andric         continue;
23663ca95b02SDimitry Andric       unsigned AS = Arg->getType()->getPointerAddressSpace();
23673ca95b02SDimitry Andric       return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
23683ca95b02SDimitry Andric     }
23693ca95b02SDimitry Andric 
237091bc56edSDimitry Andric   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
237139d628a0SDimitry Andric   if (II) {
237239d628a0SDimitry Andric     switch (II->getIntrinsicID()) {
237339d628a0SDimitry Andric     default: break;
237439d628a0SDimitry Andric     case Intrinsic::objectsize: {
237539d628a0SDimitry Andric       // Lower all uses of llvm.objectsize.*
2376d88c1a5aSDimitry Andric       ConstantInt *RetVal =
2377d88c1a5aSDimitry Andric           lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
237891bc56edSDimitry Andric       // Substituting this can cause recursive simplifications, which can
2379f37b6182SDimitry Andric       // invalidate our iterator.  Use a WeakTrackingVH to hold onto it in case
2380f37b6182SDimitry Andric       // this
238191bc56edSDimitry Andric       // happens.
23823ca95b02SDimitry Andric       Value *CurValue = &*CurInstIterator;
2383f37b6182SDimitry Andric       WeakTrackingVH IterHandle(CurValue);
238491bc56edSDimitry Andric 
23853ca95b02SDimitry Andric       replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
238691bc56edSDimitry Andric 
238791bc56edSDimitry Andric       // If the iterator instruction was recursively deleted, start over at the
238891bc56edSDimitry Andric       // start of the block.
23893ca95b02SDimitry Andric       if (IterHandle != CurValue) {
239091bc56edSDimitry Andric         CurInstIterator = BB->begin();
239191bc56edSDimitry Andric         SunkAddrs.clear();
239291bc56edSDimitry Andric       }
239391bc56edSDimitry Andric       return true;
239491bc56edSDimitry Andric     }
2395ff0cc061SDimitry Andric     case Intrinsic::aarch64_stlxr:
2396ff0cc061SDimitry Andric     case Intrinsic::aarch64_stxr: {
2397ff0cc061SDimitry Andric       ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2398ff0cc061SDimitry Andric       if (!ExtVal || !ExtVal->hasOneUse() ||
2399ff0cc061SDimitry Andric           ExtVal->getParent() == CI->getParent())
2400ff0cc061SDimitry Andric         return false;
2401ff0cc061SDimitry Andric       // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2402ff0cc061SDimitry Andric       ExtVal->moveBefore(CI);
24038f0fd8f6SDimitry Andric       // Mark this instruction as "inserted by CGP", so that other
24048f0fd8f6SDimitry Andric       // optimizations don't touch it.
24058f0fd8f6SDimitry Andric       InsertedInsts.insert(ExtVal);
2406ff0cc061SDimitry Andric       return true;
2407ff0cc061SDimitry Andric     }
24087d523365SDimitry Andric     case Intrinsic::invariant_group_barrier:
24097d523365SDimitry Andric       II->replaceAllUsesWith(II->getArgOperand(0));
24107d523365SDimitry Andric       II->eraseFromParent();
24117d523365SDimitry Andric       return true;
24127d523365SDimitry Andric 
24137d523365SDimitry Andric     case Intrinsic::cttz:
24147d523365SDimitry Andric     case Intrinsic::ctlz:
24157d523365SDimitry Andric       // If counting zeros is expensive, try to avoid it.
24167d523365SDimitry Andric       return despeculateCountZeros(II, TLI, DL, ModifiedDT);
241739d628a0SDimitry Andric     }
241891bc56edSDimitry Andric 
241939d628a0SDimitry Andric     if (TLI) {
242091bc56edSDimitry Andric       SmallVector<Value*, 2> PtrOps;
242191bc56edSDimitry Andric       Type *AccessTy;
24227a7e6055SDimitry Andric       if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
24237a7e6055SDimitry Andric         while (!PtrOps.empty()) {
24247a7e6055SDimitry Andric           Value *PtrVal = PtrOps.pop_back_val();
24257a7e6055SDimitry Andric           unsigned AS = PtrVal->getType()->getPointerAddressSpace();
24267a7e6055SDimitry Andric           if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
242791bc56edSDimitry Andric             return true;
242891bc56edSDimitry Andric         }
242939d628a0SDimitry Andric     }
24307a7e6055SDimitry Andric   }
243191bc56edSDimitry Andric 
243291bc56edSDimitry Andric   // From here on out we're working with named functions.
243391bc56edSDimitry Andric   if (!CI->getCalledFunction()) return false;
243491bc56edSDimitry Andric 
243591bc56edSDimitry Andric   // Lower all default uses of _chk calls.  This is very similar
243691bc56edSDimitry Andric   // to what InstCombineCalls does, but here we are only lowering calls
243739d628a0SDimitry Andric   // to fortified library functions (e.g. __memcpy_chk) that have the default
243839d628a0SDimitry Andric   // "don't know" as the objectsize.  Anything else should be left alone.
2439ff0cc061SDimitry Andric   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
244039d628a0SDimitry Andric   if (Value *V = Simplifier.optimizeCall(CI)) {
244139d628a0SDimitry Andric     CI->replaceAllUsesWith(V);
244239d628a0SDimitry Andric     CI->eraseFromParent();
244339d628a0SDimitry Andric     return true;
244439d628a0SDimitry Andric   }
2445f9448bf3SDimitry Andric 
2446f9448bf3SDimitry Andric   LibFunc Func;
2447db17bf38SDimitry Andric   if (TLInfo->getLibFunc(ImmutableCallSite(CI), Func) &&
2448db17bf38SDimitry Andric       Func == LibFunc_memcmp && expandMemCmp(CI, TTI, TLI, DL)) {
2449f9448bf3SDimitry Andric     ModifiedDT = true;
2450f9448bf3SDimitry Andric     return true;
2451f9448bf3SDimitry Andric   }
245239d628a0SDimitry Andric   return false;
245391bc56edSDimitry Andric }
245491bc56edSDimitry Andric 
24557d523365SDimitry Andric /// Look for opportunities to duplicate return instructions to the predecessor
24567d523365SDimitry Andric /// to enable tail call optimizations. The case it is currently looking for is:
245791bc56edSDimitry Andric /// @code
245891bc56edSDimitry Andric /// bb0:
245991bc56edSDimitry Andric ///   %tmp0 = tail call i32 @f0()
246091bc56edSDimitry Andric ///   br label %return
246191bc56edSDimitry Andric /// bb1:
246291bc56edSDimitry Andric ///   %tmp1 = tail call i32 @f1()
246391bc56edSDimitry Andric ///   br label %return
246491bc56edSDimitry Andric /// bb2:
246591bc56edSDimitry Andric ///   %tmp2 = tail call i32 @f2()
246691bc56edSDimitry Andric ///   br label %return
246791bc56edSDimitry Andric /// return:
246891bc56edSDimitry Andric ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
246991bc56edSDimitry Andric ///   ret i32 %retval
247091bc56edSDimitry Andric /// @endcode
247191bc56edSDimitry Andric ///
247291bc56edSDimitry Andric /// =>
247391bc56edSDimitry Andric ///
247491bc56edSDimitry Andric /// @code
247591bc56edSDimitry Andric /// bb0:
247691bc56edSDimitry Andric ///   %tmp0 = tail call i32 @f0()
247791bc56edSDimitry Andric ///   ret i32 %tmp0
247891bc56edSDimitry Andric /// bb1:
247991bc56edSDimitry Andric ///   %tmp1 = tail call i32 @f1()
248091bc56edSDimitry Andric ///   ret i32 %tmp1
248191bc56edSDimitry Andric /// bb2:
248291bc56edSDimitry Andric ///   %tmp2 = tail call i32 @f2()
248391bc56edSDimitry Andric ///   ret i32 %tmp2
248491bc56edSDimitry Andric /// @endcode
24857d523365SDimitry Andric bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
248691bc56edSDimitry Andric   if (!TLI)
248791bc56edSDimitry Andric     return false;
248891bc56edSDimitry Andric 
2489d88c1a5aSDimitry Andric   ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2490d88c1a5aSDimitry Andric   if (!RetI)
249191bc56edSDimitry Andric     return false;
249291bc56edSDimitry Andric 
249391bc56edSDimitry Andric   PHINode *PN = nullptr;
249491bc56edSDimitry Andric   BitCastInst *BCI = nullptr;
2495d88c1a5aSDimitry Andric   Value *V = RetI->getReturnValue();
249691bc56edSDimitry Andric   if (V) {
249791bc56edSDimitry Andric     BCI = dyn_cast<BitCastInst>(V);
249891bc56edSDimitry Andric     if (BCI)
249991bc56edSDimitry Andric       V = BCI->getOperand(0);
250091bc56edSDimitry Andric 
250191bc56edSDimitry Andric     PN = dyn_cast<PHINode>(V);
250291bc56edSDimitry Andric     if (!PN)
250391bc56edSDimitry Andric       return false;
250491bc56edSDimitry Andric   }
250591bc56edSDimitry Andric 
250691bc56edSDimitry Andric   if (PN && PN->getParent() != BB)
250791bc56edSDimitry Andric     return false;
250891bc56edSDimitry Andric 
250991bc56edSDimitry Andric   // Make sure there are no instructions between the PHI and return, or that the
251091bc56edSDimitry Andric   // return is the first instruction in the block.
251191bc56edSDimitry Andric   if (PN) {
251291bc56edSDimitry Andric     BasicBlock::iterator BI = BB->begin();
251391bc56edSDimitry Andric     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
251491bc56edSDimitry Andric     if (&*BI == BCI)
251591bc56edSDimitry Andric       // Also skip over the bitcast.
251691bc56edSDimitry Andric       ++BI;
2517d88c1a5aSDimitry Andric     if (&*BI != RetI)
251891bc56edSDimitry Andric       return false;
251991bc56edSDimitry Andric   } else {
252091bc56edSDimitry Andric     BasicBlock::iterator BI = BB->begin();
252191bc56edSDimitry Andric     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2522d88c1a5aSDimitry Andric     if (&*BI != RetI)
252391bc56edSDimitry Andric       return false;
252491bc56edSDimitry Andric   }
252591bc56edSDimitry Andric 
252691bc56edSDimitry Andric   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
252791bc56edSDimitry Andric   /// call.
2528d88c1a5aSDimitry Andric   const Function *F = BB->getParent();
252991bc56edSDimitry Andric   SmallVector<CallInst*, 4> TailCalls;
253091bc56edSDimitry Andric   if (PN) {
253191bc56edSDimitry Andric     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
253291bc56edSDimitry Andric       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
253391bc56edSDimitry Andric       // Make sure the phi value is indeed produced by the tail call.
253491bc56edSDimitry Andric       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
2535d88c1a5aSDimitry Andric           TLI->mayBeEmittedAsTailCall(CI) &&
2536d88c1a5aSDimitry Andric           attributesPermitTailCall(F, CI, RetI, *TLI))
253791bc56edSDimitry Andric         TailCalls.push_back(CI);
253891bc56edSDimitry Andric     }
253991bc56edSDimitry Andric   } else {
254091bc56edSDimitry Andric     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
254191bc56edSDimitry Andric     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
254239d628a0SDimitry Andric       if (!VisitedBBs.insert(*PI).second)
254391bc56edSDimitry Andric         continue;
254491bc56edSDimitry Andric 
254591bc56edSDimitry Andric       BasicBlock::InstListType &InstList = (*PI)->getInstList();
254691bc56edSDimitry Andric       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
254791bc56edSDimitry Andric       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
254891bc56edSDimitry Andric       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
254991bc56edSDimitry Andric       if (RI == RE)
255091bc56edSDimitry Andric         continue;
255191bc56edSDimitry Andric 
255291bc56edSDimitry Andric       CallInst *CI = dyn_cast<CallInst>(&*RI);
2553d88c1a5aSDimitry Andric       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2554d88c1a5aSDimitry Andric           attributesPermitTailCall(F, CI, RetI, *TLI))
255591bc56edSDimitry Andric         TailCalls.push_back(CI);
255691bc56edSDimitry Andric     }
255791bc56edSDimitry Andric   }
255891bc56edSDimitry Andric 
255991bc56edSDimitry Andric   bool Changed = false;
256091bc56edSDimitry Andric   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
256191bc56edSDimitry Andric     CallInst *CI = TailCalls[i];
256291bc56edSDimitry Andric     CallSite CS(CI);
256391bc56edSDimitry Andric 
256491bc56edSDimitry Andric     // Conservatively require the attributes of the call to match those of the
256591bc56edSDimitry Andric     // return. Ignore noalias because it doesn't affect the call sequence.
25667a7e6055SDimitry Andric     AttributeList CalleeAttrs = CS.getAttributes();
25677a7e6055SDimitry Andric     if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
25687a7e6055SDimitry Andric             .removeAttribute(Attribute::NoAlias) !=
25697a7e6055SDimitry Andric         AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
25707a7e6055SDimitry Andric             .removeAttribute(Attribute::NoAlias))
257191bc56edSDimitry Andric       continue;
257291bc56edSDimitry Andric 
257391bc56edSDimitry Andric     // Make sure the call instruction is followed by an unconditional branch to
257491bc56edSDimitry Andric     // the return block.
257591bc56edSDimitry Andric     BasicBlock *CallBB = CI->getParent();
257691bc56edSDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
257791bc56edSDimitry Andric     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
257891bc56edSDimitry Andric       continue;
257991bc56edSDimitry Andric 
258091bc56edSDimitry Andric     // Duplicate the return into CallBB.
2581d88c1a5aSDimitry Andric     (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
258291bc56edSDimitry Andric     ModifiedDT = Changed = true;
258391bc56edSDimitry Andric     ++NumRetsDup;
258491bc56edSDimitry Andric   }
258591bc56edSDimitry Andric 
258691bc56edSDimitry Andric   // If we eliminated all predecessors of the block, delete the block now.
258791bc56edSDimitry Andric   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
258891bc56edSDimitry Andric     BB->eraseFromParent();
258991bc56edSDimitry Andric 
259091bc56edSDimitry Andric   return Changed;
259191bc56edSDimitry Andric }
259291bc56edSDimitry Andric 
259391bc56edSDimitry Andric //===----------------------------------------------------------------------===//
259491bc56edSDimitry Andric // Memory Optimization
259591bc56edSDimitry Andric //===----------------------------------------------------------------------===//
259691bc56edSDimitry Andric 
259791bc56edSDimitry Andric namespace {
259891bc56edSDimitry Andric 
25997d523365SDimitry Andric /// This is an extended version of TargetLowering::AddrMode
260091bc56edSDimitry Andric /// which holds actual Value*'s for register values.
260191bc56edSDimitry Andric struct ExtAddrMode : public TargetLowering::AddrMode {
260291bc56edSDimitry Andric   Value *BaseReg;
260391bc56edSDimitry Andric   Value *ScaledReg;
260491bc56edSDimitry Andric   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
260591bc56edSDimitry Andric   void print(raw_ostream &OS) const;
260691bc56edSDimitry Andric   void dump() const;
260791bc56edSDimitry Andric 
260891bc56edSDimitry Andric   bool operator==(const ExtAddrMode& O) const {
260991bc56edSDimitry Andric     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
261091bc56edSDimitry Andric            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
261191bc56edSDimitry Andric            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
261291bc56edSDimitry Andric   }
261391bc56edSDimitry Andric };
261491bc56edSDimitry Andric 
261591bc56edSDimitry Andric #ifndef NDEBUG
261691bc56edSDimitry Andric static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
261791bc56edSDimitry Andric   AM.print(OS);
261891bc56edSDimitry Andric   return OS;
261991bc56edSDimitry Andric }
262091bc56edSDimitry Andric #endif
262191bc56edSDimitry Andric 
262291bc56edSDimitry Andric void ExtAddrMode::print(raw_ostream &OS) const {
262391bc56edSDimitry Andric   bool NeedPlus = false;
262491bc56edSDimitry Andric   OS << "[";
262591bc56edSDimitry Andric   if (BaseGV) {
262691bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
262791bc56edSDimitry Andric        << "GV:";
262891bc56edSDimitry Andric     BaseGV->printAsOperand(OS, /*PrintType=*/false);
262991bc56edSDimitry Andric     NeedPlus = true;
263091bc56edSDimitry Andric   }
263191bc56edSDimitry Andric 
263291bc56edSDimitry Andric   if (BaseOffs) {
263391bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
263491bc56edSDimitry Andric        << BaseOffs;
263591bc56edSDimitry Andric     NeedPlus = true;
263691bc56edSDimitry Andric   }
263791bc56edSDimitry Andric 
263891bc56edSDimitry Andric   if (BaseReg) {
263991bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
264091bc56edSDimitry Andric        << "Base:";
264191bc56edSDimitry Andric     BaseReg->printAsOperand(OS, /*PrintType=*/false);
264291bc56edSDimitry Andric     NeedPlus = true;
264391bc56edSDimitry Andric   }
264491bc56edSDimitry Andric   if (Scale) {
264591bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
264691bc56edSDimitry Andric        << Scale << "*";
264791bc56edSDimitry Andric     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
264891bc56edSDimitry Andric   }
264991bc56edSDimitry Andric 
265091bc56edSDimitry Andric   OS << ']';
265191bc56edSDimitry Andric }
265291bc56edSDimitry Andric 
265391bc56edSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
26543ca95b02SDimitry Andric LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
265591bc56edSDimitry Andric   print(dbgs());
265691bc56edSDimitry Andric   dbgs() << '\n';
265791bc56edSDimitry Andric }
265891bc56edSDimitry Andric #endif
265991bc56edSDimitry Andric 
266091bc56edSDimitry Andric /// \brief This class provides transaction based operation on the IR.
266191bc56edSDimitry Andric /// Every change made through this class is recorded in the internal state and
266291bc56edSDimitry Andric /// can be undone (rollback) until commit is called.
266391bc56edSDimitry Andric class TypePromotionTransaction {
266491bc56edSDimitry Andric 
266591bc56edSDimitry Andric   /// \brief This represents the common interface of the individual transaction.
266691bc56edSDimitry Andric   /// Each class implements the logic for doing one specific modification on
266791bc56edSDimitry Andric   /// the IR via the TypePromotionTransaction.
266891bc56edSDimitry Andric   class TypePromotionAction {
266991bc56edSDimitry Andric   protected:
267091bc56edSDimitry Andric     /// The Instruction modified.
267191bc56edSDimitry Andric     Instruction *Inst;
267291bc56edSDimitry Andric 
267391bc56edSDimitry Andric   public:
267491bc56edSDimitry Andric     /// \brief Constructor of the action.
267591bc56edSDimitry Andric     /// The constructor performs the related action on the IR.
267691bc56edSDimitry Andric     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
267791bc56edSDimitry Andric 
267891bc56edSDimitry Andric     virtual ~TypePromotionAction() {}
267991bc56edSDimitry Andric 
268091bc56edSDimitry Andric     /// \brief Undo the modification done by this action.
268191bc56edSDimitry Andric     /// When this method is called, the IR must be in the same state as it was
268291bc56edSDimitry Andric     /// before this action was applied.
268391bc56edSDimitry Andric     /// \pre Undoing the action works if and only if the IR is in the exact same
268491bc56edSDimitry Andric     /// state as it was directly after this action was applied.
268591bc56edSDimitry Andric     virtual void undo() = 0;
268691bc56edSDimitry Andric 
268791bc56edSDimitry Andric     /// \brief Advocate every change made by this action.
268891bc56edSDimitry Andric     /// When the results on the IR of the action are to be kept, it is important
268991bc56edSDimitry Andric     /// to call this function, otherwise hidden information may be kept forever.
269091bc56edSDimitry Andric     virtual void commit() {
269191bc56edSDimitry Andric       // Nothing to be done, this action is not doing anything.
269291bc56edSDimitry Andric     }
269391bc56edSDimitry Andric   };
269491bc56edSDimitry Andric 
269591bc56edSDimitry Andric   /// \brief Utility to remember the position of an instruction.
269691bc56edSDimitry Andric   class InsertionHandler {
269791bc56edSDimitry Andric     /// Position of an instruction.
269891bc56edSDimitry Andric     /// Either an instruction:
269991bc56edSDimitry Andric     /// - Is the first in a basic block: BB is used.
270091bc56edSDimitry Andric     /// - Has a previous instructon: PrevInst is used.
270191bc56edSDimitry Andric     union {
270291bc56edSDimitry Andric       Instruction *PrevInst;
270391bc56edSDimitry Andric       BasicBlock *BB;
270491bc56edSDimitry Andric     } Point;
270591bc56edSDimitry Andric     /// Remember whether or not the instruction had a previous instruction.
270691bc56edSDimitry Andric     bool HasPrevInstruction;
270791bc56edSDimitry Andric 
270891bc56edSDimitry Andric   public:
270991bc56edSDimitry Andric     /// \brief Record the position of \p Inst.
271091bc56edSDimitry Andric     InsertionHandler(Instruction *Inst) {
27117d523365SDimitry Andric       BasicBlock::iterator It = Inst->getIterator();
271291bc56edSDimitry Andric       HasPrevInstruction = (It != (Inst->getParent()->begin()));
271391bc56edSDimitry Andric       if (HasPrevInstruction)
27147d523365SDimitry Andric         Point.PrevInst = &*--It;
271591bc56edSDimitry Andric       else
271691bc56edSDimitry Andric         Point.BB = Inst->getParent();
271791bc56edSDimitry Andric     }
271891bc56edSDimitry Andric 
271991bc56edSDimitry Andric     /// \brief Insert \p Inst at the recorded position.
272091bc56edSDimitry Andric     void insert(Instruction *Inst) {
272191bc56edSDimitry Andric       if (HasPrevInstruction) {
272291bc56edSDimitry Andric         if (Inst->getParent())
272391bc56edSDimitry Andric           Inst->removeFromParent();
272491bc56edSDimitry Andric         Inst->insertAfter(Point.PrevInst);
272591bc56edSDimitry Andric       } else {
27267d523365SDimitry Andric         Instruction *Position = &*Point.BB->getFirstInsertionPt();
272791bc56edSDimitry Andric         if (Inst->getParent())
272891bc56edSDimitry Andric           Inst->moveBefore(Position);
272991bc56edSDimitry Andric         else
273091bc56edSDimitry Andric           Inst->insertBefore(Position);
273191bc56edSDimitry Andric       }
273291bc56edSDimitry Andric     }
273391bc56edSDimitry Andric   };
273491bc56edSDimitry Andric 
273591bc56edSDimitry Andric   /// \brief Move an instruction before another.
273691bc56edSDimitry Andric   class InstructionMoveBefore : public TypePromotionAction {
273791bc56edSDimitry Andric     /// Original position of the instruction.
273891bc56edSDimitry Andric     InsertionHandler Position;
273991bc56edSDimitry Andric 
274091bc56edSDimitry Andric   public:
274191bc56edSDimitry Andric     /// \brief Move \p Inst before \p Before.
274291bc56edSDimitry Andric     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
274391bc56edSDimitry Andric         : TypePromotionAction(Inst), Position(Inst) {
274491bc56edSDimitry Andric       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
274591bc56edSDimitry Andric       Inst->moveBefore(Before);
274691bc56edSDimitry Andric     }
274791bc56edSDimitry Andric 
274891bc56edSDimitry Andric     /// \brief Move the instruction back to its original position.
274991bc56edSDimitry Andric     void undo() override {
275091bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
275191bc56edSDimitry Andric       Position.insert(Inst);
275291bc56edSDimitry Andric     }
275391bc56edSDimitry Andric   };
275491bc56edSDimitry Andric 
275591bc56edSDimitry Andric   /// \brief Set the operand of an instruction with a new value.
275691bc56edSDimitry Andric   class OperandSetter : public TypePromotionAction {
275791bc56edSDimitry Andric     /// Original operand of the instruction.
275891bc56edSDimitry Andric     Value *Origin;
275991bc56edSDimitry Andric     /// Index of the modified instruction.
276091bc56edSDimitry Andric     unsigned Idx;
276191bc56edSDimitry Andric 
276291bc56edSDimitry Andric   public:
276391bc56edSDimitry Andric     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
276491bc56edSDimitry Andric     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
276591bc56edSDimitry Andric         : TypePromotionAction(Inst), Idx(Idx) {
276691bc56edSDimitry Andric       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
276791bc56edSDimitry Andric                    << "for:" << *Inst << "\n"
276891bc56edSDimitry Andric                    << "with:" << *NewVal << "\n");
276991bc56edSDimitry Andric       Origin = Inst->getOperand(Idx);
277091bc56edSDimitry Andric       Inst->setOperand(Idx, NewVal);
277191bc56edSDimitry Andric     }
277291bc56edSDimitry Andric 
277391bc56edSDimitry Andric     /// \brief Restore the original value of the instruction.
277491bc56edSDimitry Andric     void undo() override {
277591bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
277691bc56edSDimitry Andric                    << "for: " << *Inst << "\n"
277791bc56edSDimitry Andric                    << "with: " << *Origin << "\n");
277891bc56edSDimitry Andric       Inst->setOperand(Idx, Origin);
277991bc56edSDimitry Andric     }
278091bc56edSDimitry Andric   };
278191bc56edSDimitry Andric 
278291bc56edSDimitry Andric   /// \brief Hide the operands of an instruction.
278391bc56edSDimitry Andric   /// Do as if this instruction was not using any of its operands.
278491bc56edSDimitry Andric   class OperandsHider : public TypePromotionAction {
278591bc56edSDimitry Andric     /// The list of original operands.
278691bc56edSDimitry Andric     SmallVector<Value *, 4> OriginalValues;
278791bc56edSDimitry Andric 
278891bc56edSDimitry Andric   public:
278991bc56edSDimitry Andric     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
279091bc56edSDimitry Andric     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
279191bc56edSDimitry Andric       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
279291bc56edSDimitry Andric       unsigned NumOpnds = Inst->getNumOperands();
279391bc56edSDimitry Andric       OriginalValues.reserve(NumOpnds);
279491bc56edSDimitry Andric       for (unsigned It = 0; It < NumOpnds; ++It) {
279591bc56edSDimitry Andric         // Save the current operand.
279691bc56edSDimitry Andric         Value *Val = Inst->getOperand(It);
279791bc56edSDimitry Andric         OriginalValues.push_back(Val);
279891bc56edSDimitry Andric         // Set a dummy one.
27997d523365SDimitry Andric         // We could use OperandSetter here, but that would imply an overhead
280091bc56edSDimitry Andric         // that we are not willing to pay.
280191bc56edSDimitry Andric         Inst->setOperand(It, UndefValue::get(Val->getType()));
280291bc56edSDimitry Andric       }
280391bc56edSDimitry Andric     }
280491bc56edSDimitry Andric 
280591bc56edSDimitry Andric     /// \brief Restore the original list of uses.
280691bc56edSDimitry Andric     void undo() override {
280791bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
280891bc56edSDimitry Andric       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
280991bc56edSDimitry Andric         Inst->setOperand(It, OriginalValues[It]);
281091bc56edSDimitry Andric     }
281191bc56edSDimitry Andric   };
281291bc56edSDimitry Andric 
281391bc56edSDimitry Andric   /// \brief Build a truncate instruction.
281491bc56edSDimitry Andric   class TruncBuilder : public TypePromotionAction {
281539d628a0SDimitry Andric     Value *Val;
281691bc56edSDimitry Andric   public:
281791bc56edSDimitry Andric     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
281891bc56edSDimitry Andric     /// result.
281991bc56edSDimitry Andric     /// trunc Opnd to Ty.
282091bc56edSDimitry Andric     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
282191bc56edSDimitry Andric       IRBuilder<> Builder(Opnd);
282239d628a0SDimitry Andric       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
282339d628a0SDimitry Andric       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
282491bc56edSDimitry Andric     }
282591bc56edSDimitry Andric 
282639d628a0SDimitry Andric     /// \brief Get the built value.
282739d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
282891bc56edSDimitry Andric 
282991bc56edSDimitry Andric     /// \brief Remove the built instruction.
283091bc56edSDimitry Andric     void undo() override {
283139d628a0SDimitry Andric       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
283239d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
283339d628a0SDimitry Andric         IVal->eraseFromParent();
283491bc56edSDimitry Andric     }
283591bc56edSDimitry Andric   };
283691bc56edSDimitry Andric 
283791bc56edSDimitry Andric   /// \brief Build a sign extension instruction.
283891bc56edSDimitry Andric   class SExtBuilder : public TypePromotionAction {
283939d628a0SDimitry Andric     Value *Val;
284091bc56edSDimitry Andric   public:
284191bc56edSDimitry Andric     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
284291bc56edSDimitry Andric     /// result.
284391bc56edSDimitry Andric     /// sext Opnd to Ty.
284491bc56edSDimitry Andric     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
284539d628a0SDimitry Andric         : TypePromotionAction(InsertPt) {
284691bc56edSDimitry Andric       IRBuilder<> Builder(InsertPt);
284739d628a0SDimitry Andric       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
284839d628a0SDimitry Andric       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
284991bc56edSDimitry Andric     }
285091bc56edSDimitry Andric 
285139d628a0SDimitry Andric     /// \brief Get the built value.
285239d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
285391bc56edSDimitry Andric 
285491bc56edSDimitry Andric     /// \brief Remove the built instruction.
285591bc56edSDimitry Andric     void undo() override {
285639d628a0SDimitry Andric       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
285739d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
285839d628a0SDimitry Andric         IVal->eraseFromParent();
285939d628a0SDimitry Andric     }
286039d628a0SDimitry Andric   };
286139d628a0SDimitry Andric 
286239d628a0SDimitry Andric   /// \brief Build a zero extension instruction.
286339d628a0SDimitry Andric   class ZExtBuilder : public TypePromotionAction {
286439d628a0SDimitry Andric     Value *Val;
286539d628a0SDimitry Andric   public:
286639d628a0SDimitry Andric     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
286739d628a0SDimitry Andric     /// result.
286839d628a0SDimitry Andric     /// zext Opnd to Ty.
286939d628a0SDimitry Andric     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
287039d628a0SDimitry Andric         : TypePromotionAction(InsertPt) {
287139d628a0SDimitry Andric       IRBuilder<> Builder(InsertPt);
287239d628a0SDimitry Andric       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
287339d628a0SDimitry Andric       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
287439d628a0SDimitry Andric     }
287539d628a0SDimitry Andric 
287639d628a0SDimitry Andric     /// \brief Get the built value.
287739d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
287839d628a0SDimitry Andric 
287939d628a0SDimitry Andric     /// \brief Remove the built instruction.
288039d628a0SDimitry Andric     void undo() override {
288139d628a0SDimitry Andric       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
288239d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
288339d628a0SDimitry Andric         IVal->eraseFromParent();
288491bc56edSDimitry Andric     }
288591bc56edSDimitry Andric   };
288691bc56edSDimitry Andric 
288791bc56edSDimitry Andric   /// \brief Mutate an instruction to another type.
288891bc56edSDimitry Andric   class TypeMutator : public TypePromotionAction {
288991bc56edSDimitry Andric     /// Record the original type.
289091bc56edSDimitry Andric     Type *OrigTy;
289191bc56edSDimitry Andric 
289291bc56edSDimitry Andric   public:
289391bc56edSDimitry Andric     /// \brief Mutate the type of \p Inst into \p NewTy.
289491bc56edSDimitry Andric     TypeMutator(Instruction *Inst, Type *NewTy)
289591bc56edSDimitry Andric         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
289691bc56edSDimitry Andric       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
289791bc56edSDimitry Andric                    << "\n");
289891bc56edSDimitry Andric       Inst->mutateType(NewTy);
289991bc56edSDimitry Andric     }
290091bc56edSDimitry Andric 
290191bc56edSDimitry Andric     /// \brief Mutate the instruction back to its original type.
290291bc56edSDimitry Andric     void undo() override {
290391bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
290491bc56edSDimitry Andric                    << "\n");
290591bc56edSDimitry Andric       Inst->mutateType(OrigTy);
290691bc56edSDimitry Andric     }
290791bc56edSDimitry Andric   };
290891bc56edSDimitry Andric 
290991bc56edSDimitry Andric   /// \brief Replace the uses of an instruction by another instruction.
291091bc56edSDimitry Andric   class UsesReplacer : public TypePromotionAction {
291191bc56edSDimitry Andric     /// Helper structure to keep track of the replaced uses.
291291bc56edSDimitry Andric     struct InstructionAndIdx {
291391bc56edSDimitry Andric       /// The instruction using the instruction.
291491bc56edSDimitry Andric       Instruction *Inst;
291591bc56edSDimitry Andric       /// The index where this instruction is used for Inst.
291691bc56edSDimitry Andric       unsigned Idx;
291791bc56edSDimitry Andric       InstructionAndIdx(Instruction *Inst, unsigned Idx)
291891bc56edSDimitry Andric           : Inst(Inst), Idx(Idx) {}
291991bc56edSDimitry Andric     };
292091bc56edSDimitry Andric 
292191bc56edSDimitry Andric     /// Keep track of the original uses (pair Instruction, Index).
292291bc56edSDimitry Andric     SmallVector<InstructionAndIdx, 4> OriginalUses;
292391bc56edSDimitry Andric     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
292491bc56edSDimitry Andric 
292591bc56edSDimitry Andric   public:
292691bc56edSDimitry Andric     /// \brief Replace all the use of \p Inst by \p New.
292791bc56edSDimitry Andric     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
292891bc56edSDimitry Andric       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
292991bc56edSDimitry Andric                    << "\n");
293091bc56edSDimitry Andric       // Record the original uses.
293191bc56edSDimitry Andric       for (Use &U : Inst->uses()) {
293291bc56edSDimitry Andric         Instruction *UserI = cast<Instruction>(U.getUser());
293391bc56edSDimitry Andric         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
293491bc56edSDimitry Andric       }
293591bc56edSDimitry Andric       // Now, we can replace the uses.
293691bc56edSDimitry Andric       Inst->replaceAllUsesWith(New);
293791bc56edSDimitry Andric     }
293891bc56edSDimitry Andric 
293991bc56edSDimitry Andric     /// \brief Reassign the original uses of Inst to Inst.
294091bc56edSDimitry Andric     void undo() override {
294191bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
294291bc56edSDimitry Andric       for (use_iterator UseIt = OriginalUses.begin(),
294391bc56edSDimitry Andric                         EndIt = OriginalUses.end();
294491bc56edSDimitry Andric            UseIt != EndIt; ++UseIt) {
294591bc56edSDimitry Andric         UseIt->Inst->setOperand(UseIt->Idx, Inst);
294691bc56edSDimitry Andric       }
294791bc56edSDimitry Andric     }
294891bc56edSDimitry Andric   };
294991bc56edSDimitry Andric 
295091bc56edSDimitry Andric   /// \brief Remove an instruction from the IR.
295191bc56edSDimitry Andric   class InstructionRemover : public TypePromotionAction {
295291bc56edSDimitry Andric     /// Original position of the instruction.
295391bc56edSDimitry Andric     InsertionHandler Inserter;
295491bc56edSDimitry Andric     /// Helper structure to hide all the link to the instruction. In other
295591bc56edSDimitry Andric     /// words, this helps to do as if the instruction was removed.
295691bc56edSDimitry Andric     OperandsHider Hider;
295791bc56edSDimitry Andric     /// Keep track of the uses replaced, if any.
295891bc56edSDimitry Andric     UsesReplacer *Replacer;
29597a7e6055SDimitry Andric     /// Keep track of instructions removed.
29607a7e6055SDimitry Andric     SetOfInstrs &RemovedInsts;
296191bc56edSDimitry Andric 
296291bc56edSDimitry Andric   public:
296391bc56edSDimitry Andric     /// \brief Remove all reference of \p Inst and optinally replace all its
296491bc56edSDimitry Andric     /// uses with New.
29657a7e6055SDimitry Andric     /// \p RemovedInsts Keep track of the instructions removed by this Action.
296691bc56edSDimitry Andric     /// \pre If !Inst->use_empty(), then New != nullptr
29677a7e6055SDimitry Andric     InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
29687a7e6055SDimitry Andric                        Value *New = nullptr)
296991bc56edSDimitry Andric         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
29707a7e6055SDimitry Andric           Replacer(nullptr), RemovedInsts(RemovedInsts) {
297191bc56edSDimitry Andric       if (New)
297291bc56edSDimitry Andric         Replacer = new UsesReplacer(Inst, New);
297391bc56edSDimitry Andric       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
29747a7e6055SDimitry Andric       RemovedInsts.insert(Inst);
29757a7e6055SDimitry Andric       /// The instructions removed here will be freed after completing
29767a7e6055SDimitry Andric       /// optimizeBlock() for all blocks as we need to keep track of the
29777a7e6055SDimitry Andric       /// removed instructions during promotion.
297891bc56edSDimitry Andric       Inst->removeFromParent();
297991bc56edSDimitry Andric     }
298091bc56edSDimitry Andric 
2981ff0cc061SDimitry Andric     ~InstructionRemover() override { delete Replacer; }
298291bc56edSDimitry Andric 
298391bc56edSDimitry Andric     /// \brief Resurrect the instruction and reassign it to the proper uses if
298491bc56edSDimitry Andric     /// new value was provided when build this action.
298591bc56edSDimitry Andric     void undo() override {
298691bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
298791bc56edSDimitry Andric       Inserter.insert(Inst);
298891bc56edSDimitry Andric       if (Replacer)
298991bc56edSDimitry Andric         Replacer->undo();
299091bc56edSDimitry Andric       Hider.undo();
29917a7e6055SDimitry Andric       RemovedInsts.erase(Inst);
299291bc56edSDimitry Andric     }
299391bc56edSDimitry Andric   };
299491bc56edSDimitry Andric 
299591bc56edSDimitry Andric public:
299691bc56edSDimitry Andric   /// Restoration point.
299791bc56edSDimitry Andric   /// The restoration point is a pointer to an action instead of an iterator
299891bc56edSDimitry Andric   /// because the iterator may be invalidated but not the pointer.
299991bc56edSDimitry Andric   typedef const TypePromotionAction *ConstRestorationPt;
30007a7e6055SDimitry Andric 
30017a7e6055SDimitry Andric   TypePromotionTransaction(SetOfInstrs &RemovedInsts)
30027a7e6055SDimitry Andric       : RemovedInsts(RemovedInsts) {}
30037a7e6055SDimitry Andric 
300491bc56edSDimitry Andric   /// Advocate every changes made in that transaction.
300591bc56edSDimitry Andric   void commit();
300691bc56edSDimitry Andric   /// Undo all the changes made after the given point.
300791bc56edSDimitry Andric   void rollback(ConstRestorationPt Point);
300891bc56edSDimitry Andric   /// Get the current restoration point.
300991bc56edSDimitry Andric   ConstRestorationPt getRestorationPoint() const;
301091bc56edSDimitry Andric 
301191bc56edSDimitry Andric   /// \name API for IR modification with state keeping to support rollback.
301291bc56edSDimitry Andric   /// @{
301391bc56edSDimitry Andric   /// Same as Instruction::setOperand.
301491bc56edSDimitry Andric   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
301591bc56edSDimitry Andric   /// Same as Instruction::eraseFromParent.
301691bc56edSDimitry Andric   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
301791bc56edSDimitry Andric   /// Same as Value::replaceAllUsesWith.
301891bc56edSDimitry Andric   void replaceAllUsesWith(Instruction *Inst, Value *New);
301991bc56edSDimitry Andric   /// Same as Value::mutateType.
302091bc56edSDimitry Andric   void mutateType(Instruction *Inst, Type *NewTy);
302191bc56edSDimitry Andric   /// Same as IRBuilder::createTrunc.
302239d628a0SDimitry Andric   Value *createTrunc(Instruction *Opnd, Type *Ty);
302391bc56edSDimitry Andric   /// Same as IRBuilder::createSExt.
302439d628a0SDimitry Andric   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
302539d628a0SDimitry Andric   /// Same as IRBuilder::createZExt.
302639d628a0SDimitry Andric   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
302791bc56edSDimitry Andric   /// Same as Instruction::moveBefore.
302891bc56edSDimitry Andric   void moveBefore(Instruction *Inst, Instruction *Before);
302991bc56edSDimitry Andric   /// @}
303091bc56edSDimitry Andric 
303191bc56edSDimitry Andric private:
303291bc56edSDimitry Andric   /// The ordered list of actions made so far.
303391bc56edSDimitry Andric   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
303491bc56edSDimitry Andric   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
30357a7e6055SDimitry Andric   SetOfInstrs &RemovedInsts;
303691bc56edSDimitry Andric };
303791bc56edSDimitry Andric 
303891bc56edSDimitry Andric void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
303991bc56edSDimitry Andric                                           Value *NewVal) {
304091bc56edSDimitry Andric   Actions.push_back(
304191bc56edSDimitry Andric       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
304291bc56edSDimitry Andric }
304391bc56edSDimitry Andric 
304491bc56edSDimitry Andric void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
304591bc56edSDimitry Andric                                                 Value *NewVal) {
304691bc56edSDimitry Andric   Actions.push_back(
30477a7e6055SDimitry Andric       make_unique<TypePromotionTransaction::InstructionRemover>(Inst,
30487a7e6055SDimitry Andric                                                          RemovedInsts, NewVal));
304991bc56edSDimitry Andric }
305091bc56edSDimitry Andric 
305191bc56edSDimitry Andric void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
305291bc56edSDimitry Andric                                                   Value *New) {
305391bc56edSDimitry Andric   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
305491bc56edSDimitry Andric }
305591bc56edSDimitry Andric 
305691bc56edSDimitry Andric void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
305791bc56edSDimitry Andric   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
305891bc56edSDimitry Andric }
305991bc56edSDimitry Andric 
306039d628a0SDimitry Andric Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
306191bc56edSDimitry Andric                                              Type *Ty) {
306291bc56edSDimitry Andric   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
306339d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
306491bc56edSDimitry Andric   Actions.push_back(std::move(Ptr));
306539d628a0SDimitry Andric   return Val;
306691bc56edSDimitry Andric }
306791bc56edSDimitry Andric 
306839d628a0SDimitry Andric Value *TypePromotionTransaction::createSExt(Instruction *Inst,
306991bc56edSDimitry Andric                                             Value *Opnd, Type *Ty) {
307091bc56edSDimitry Andric   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
307139d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
307291bc56edSDimitry Andric   Actions.push_back(std::move(Ptr));
307339d628a0SDimitry Andric   return Val;
307439d628a0SDimitry Andric }
307539d628a0SDimitry Andric 
307639d628a0SDimitry Andric Value *TypePromotionTransaction::createZExt(Instruction *Inst,
307739d628a0SDimitry Andric                                             Value *Opnd, Type *Ty) {
307839d628a0SDimitry Andric   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
307939d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
308039d628a0SDimitry Andric   Actions.push_back(std::move(Ptr));
308139d628a0SDimitry Andric   return Val;
308291bc56edSDimitry Andric }
308391bc56edSDimitry Andric 
308491bc56edSDimitry Andric void TypePromotionTransaction::moveBefore(Instruction *Inst,
308591bc56edSDimitry Andric                                           Instruction *Before) {
308691bc56edSDimitry Andric   Actions.push_back(
308791bc56edSDimitry Andric       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
308891bc56edSDimitry Andric }
308991bc56edSDimitry Andric 
309091bc56edSDimitry Andric TypePromotionTransaction::ConstRestorationPt
309191bc56edSDimitry Andric TypePromotionTransaction::getRestorationPoint() const {
309291bc56edSDimitry Andric   return !Actions.empty() ? Actions.back().get() : nullptr;
309391bc56edSDimitry Andric }
309491bc56edSDimitry Andric 
309591bc56edSDimitry Andric void TypePromotionTransaction::commit() {
309691bc56edSDimitry Andric   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
309791bc56edSDimitry Andric        ++It)
309891bc56edSDimitry Andric     (*It)->commit();
309991bc56edSDimitry Andric   Actions.clear();
310091bc56edSDimitry Andric }
310191bc56edSDimitry Andric 
310291bc56edSDimitry Andric void TypePromotionTransaction::rollback(
310391bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt Point) {
310491bc56edSDimitry Andric   while (!Actions.empty() && Point != Actions.back().get()) {
310591bc56edSDimitry Andric     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
310691bc56edSDimitry Andric     Curr->undo();
310791bc56edSDimitry Andric   }
310891bc56edSDimitry Andric }
310991bc56edSDimitry Andric 
311091bc56edSDimitry Andric /// \brief A helper class for matching addressing modes.
311191bc56edSDimitry Andric ///
311291bc56edSDimitry Andric /// This encapsulates the logic for matching the target-legal addressing modes.
311391bc56edSDimitry Andric class AddressingModeMatcher {
311491bc56edSDimitry Andric   SmallVectorImpl<Instruction*> &AddrModeInsts;
311591bc56edSDimitry Andric   const TargetLowering &TLI;
31167a7e6055SDimitry Andric   const TargetRegisterInfo &TRI;
3117875ed548SDimitry Andric   const DataLayout &DL;
311891bc56edSDimitry Andric 
311991bc56edSDimitry Andric   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
312091bc56edSDimitry Andric   /// the memory instruction that we're computing this address for.
312191bc56edSDimitry Andric   Type *AccessTy;
312297bc6c73SDimitry Andric   unsigned AddrSpace;
312391bc56edSDimitry Andric   Instruction *MemoryInst;
312491bc56edSDimitry Andric 
31257d523365SDimitry Andric   /// This is the addressing mode that we're building up. This is
312691bc56edSDimitry Andric   /// part of the return value of this addressing mode matching stuff.
312791bc56edSDimitry Andric   ExtAddrMode &AddrMode;
312891bc56edSDimitry Andric 
31298f0fd8f6SDimitry Andric   /// The instructions inserted by other CodeGenPrepare optimizations.
31308f0fd8f6SDimitry Andric   const SetOfInstrs &InsertedInsts;
313191bc56edSDimitry Andric   /// A map from the instructions to their type before promotion.
313291bc56edSDimitry Andric   InstrToOrigTy &PromotedInsts;
313391bc56edSDimitry Andric   /// The ongoing transaction where every action should be registered.
313491bc56edSDimitry Andric   TypePromotionTransaction &TPT;
313591bc56edSDimitry Andric 
31367d523365SDimitry Andric   /// This is set to true when we should not do profitability checks.
31377d523365SDimitry Andric   /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
313891bc56edSDimitry Andric   bool IgnoreProfitability;
313991bc56edSDimitry Andric 
314091bc56edSDimitry Andric   AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
31417a7e6055SDimitry Andric                         const TargetLowering &TLI,
31427a7e6055SDimitry Andric                         const TargetRegisterInfo &TRI,
31437a7e6055SDimitry Andric                         Type *AT, unsigned AS,
314497bc6c73SDimitry Andric                         Instruction *MI, ExtAddrMode &AM,
31458f0fd8f6SDimitry Andric                         const SetOfInstrs &InsertedInsts,
314691bc56edSDimitry Andric                         InstrToOrigTy &PromotedInsts,
314791bc56edSDimitry Andric                         TypePromotionTransaction &TPT)
31487a7e6055SDimitry Andric       : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3149875ed548SDimitry Andric         DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3150875ed548SDimitry Andric         MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3151875ed548SDimitry Andric         PromotedInsts(PromotedInsts), TPT(TPT) {
315291bc56edSDimitry Andric     IgnoreProfitability = false;
315391bc56edSDimitry Andric   }
315491bc56edSDimitry Andric public:
315591bc56edSDimitry Andric 
31567d523365SDimitry Andric   /// Find the maximal addressing mode that a load/store of V can fold,
315791bc56edSDimitry Andric   /// give an access type of AccessTy.  This returns a list of involved
315891bc56edSDimitry Andric   /// instructions in AddrModeInsts.
31598f0fd8f6SDimitry Andric   /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
316091bc56edSDimitry Andric   /// optimizations.
316191bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
316291bc56edSDimitry Andric   /// \p The ongoing transaction where every action should be registered.
316397bc6c73SDimitry Andric   static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
316491bc56edSDimitry Andric                            Instruction *MemoryInst,
316591bc56edSDimitry Andric                            SmallVectorImpl<Instruction*> &AddrModeInsts,
31667a7e6055SDimitry Andric                            const TargetLowering &TLI,
31677a7e6055SDimitry Andric                            const TargetRegisterInfo &TRI,
31688f0fd8f6SDimitry Andric                            const SetOfInstrs &InsertedInsts,
316991bc56edSDimitry Andric                            InstrToOrigTy &PromotedInsts,
317091bc56edSDimitry Andric                            TypePromotionTransaction &TPT) {
317191bc56edSDimitry Andric     ExtAddrMode Result;
317291bc56edSDimitry Andric 
31737a7e6055SDimitry Andric     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
31747a7e6055SDimitry Andric                                          AccessTy, AS,
31758f0fd8f6SDimitry Andric                                          MemoryInst, Result, InsertedInsts,
31767d523365SDimitry Andric                                          PromotedInsts, TPT).matchAddr(V, 0);
317791bc56edSDimitry Andric     (void)Success; assert(Success && "Couldn't select *anything*?");
317891bc56edSDimitry Andric     return Result;
317991bc56edSDimitry Andric   }
318091bc56edSDimitry Andric private:
31817d523365SDimitry Andric   bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
31827d523365SDimitry Andric   bool matchAddr(Value *V, unsigned Depth);
31837d523365SDimitry Andric   bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
318491bc56edSDimitry Andric                           bool *MovedAway = nullptr);
31857d523365SDimitry Andric   bool isProfitableToFoldIntoAddressingMode(Instruction *I,
318691bc56edSDimitry Andric                                             ExtAddrMode &AMBefore,
318791bc56edSDimitry Andric                                             ExtAddrMode &AMAfter);
31887d523365SDimitry Andric   bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
31897d523365SDimitry Andric   bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
319091bc56edSDimitry Andric                              Value *PromotedOperand) const;
319191bc56edSDimitry Andric };
319291bc56edSDimitry Andric 
31937d523365SDimitry Andric /// Try adding ScaleReg*Scale to the current addressing mode.
319491bc56edSDimitry Andric /// Return true and update AddrMode if this addr mode is legal for the target,
319591bc56edSDimitry Andric /// false if not.
31967d523365SDimitry Andric bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
319791bc56edSDimitry Andric                                              unsigned Depth) {
319891bc56edSDimitry Andric   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
319991bc56edSDimitry Andric   // mode.  Just process that directly.
320091bc56edSDimitry Andric   if (Scale == 1)
32017d523365SDimitry Andric     return matchAddr(ScaleReg, Depth);
320291bc56edSDimitry Andric 
320391bc56edSDimitry Andric   // If the scale is 0, it takes nothing to add this.
320491bc56edSDimitry Andric   if (Scale == 0)
320591bc56edSDimitry Andric     return true;
320691bc56edSDimitry Andric 
320791bc56edSDimitry Andric   // If we already have a scale of this value, we can add to it, otherwise, we
320891bc56edSDimitry Andric   // need an available scale field.
320991bc56edSDimitry Andric   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
321091bc56edSDimitry Andric     return false;
321191bc56edSDimitry Andric 
321291bc56edSDimitry Andric   ExtAddrMode TestAddrMode = AddrMode;
321391bc56edSDimitry Andric 
321491bc56edSDimitry Andric   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
321591bc56edSDimitry Andric   // [A+B + A*7] -> [B+A*8].
321691bc56edSDimitry Andric   TestAddrMode.Scale += Scale;
321791bc56edSDimitry Andric   TestAddrMode.ScaledReg = ScaleReg;
321891bc56edSDimitry Andric 
321991bc56edSDimitry Andric   // If the new address isn't legal, bail out.
3220875ed548SDimitry Andric   if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
322191bc56edSDimitry Andric     return false;
322291bc56edSDimitry Andric 
322391bc56edSDimitry Andric   // It was legal, so commit it.
322491bc56edSDimitry Andric   AddrMode = TestAddrMode;
322591bc56edSDimitry Andric 
322691bc56edSDimitry Andric   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
322791bc56edSDimitry Andric   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
322891bc56edSDimitry Andric   // X*Scale + C*Scale to addr mode.
322991bc56edSDimitry Andric   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
323091bc56edSDimitry Andric   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
323191bc56edSDimitry Andric       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
323291bc56edSDimitry Andric     TestAddrMode.ScaledReg = AddLHS;
323391bc56edSDimitry Andric     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
323491bc56edSDimitry Andric 
323591bc56edSDimitry Andric     // If this addressing mode is legal, commit it and remember that we folded
323691bc56edSDimitry Andric     // this instruction.
3237875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
323891bc56edSDimitry Andric       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
323991bc56edSDimitry Andric       AddrMode = TestAddrMode;
324091bc56edSDimitry Andric       return true;
324191bc56edSDimitry Andric     }
324291bc56edSDimitry Andric   }
324391bc56edSDimitry Andric 
324491bc56edSDimitry Andric   // Otherwise, not (x+c)*scale, just return what we have.
324591bc56edSDimitry Andric   return true;
324691bc56edSDimitry Andric }
324791bc56edSDimitry Andric 
32487d523365SDimitry Andric /// This is a little filter, which returns true if an addressing computation
32497d523365SDimitry Andric /// involving I might be folded into a load/store accessing it.
32507d523365SDimitry Andric /// This doesn't need to be perfect, but needs to accept at least
325191bc56edSDimitry Andric /// the set of instructions that MatchOperationAddr can.
325291bc56edSDimitry Andric static bool MightBeFoldableInst(Instruction *I) {
325391bc56edSDimitry Andric   switch (I->getOpcode()) {
325491bc56edSDimitry Andric   case Instruction::BitCast:
325591bc56edSDimitry Andric   case Instruction::AddrSpaceCast:
325691bc56edSDimitry Andric     // Don't touch identity bitcasts.
325791bc56edSDimitry Andric     if (I->getType() == I->getOperand(0)->getType())
325891bc56edSDimitry Andric       return false;
325991bc56edSDimitry Andric     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
326091bc56edSDimitry Andric   case Instruction::PtrToInt:
326191bc56edSDimitry Andric     // PtrToInt is always a noop, as we know that the int type is pointer sized.
326291bc56edSDimitry Andric     return true;
326391bc56edSDimitry Andric   case Instruction::IntToPtr:
326491bc56edSDimitry Andric     // We know the input is intptr_t, so this is foldable.
326591bc56edSDimitry Andric     return true;
326691bc56edSDimitry Andric   case Instruction::Add:
326791bc56edSDimitry Andric     return true;
326891bc56edSDimitry Andric   case Instruction::Mul:
326991bc56edSDimitry Andric   case Instruction::Shl:
327091bc56edSDimitry Andric     // Can only handle X*C and X << C.
327191bc56edSDimitry Andric     return isa<ConstantInt>(I->getOperand(1));
327291bc56edSDimitry Andric   case Instruction::GetElementPtr:
327391bc56edSDimitry Andric     return true;
327491bc56edSDimitry Andric   default:
327591bc56edSDimitry Andric     return false;
327691bc56edSDimitry Andric   }
327791bc56edSDimitry Andric }
327891bc56edSDimitry Andric 
327939d628a0SDimitry Andric /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
328039d628a0SDimitry Andric /// \note \p Val is assumed to be the product of some type promotion.
328139d628a0SDimitry Andric /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
328239d628a0SDimitry Andric /// to be legal, as the non-promoted value would have had the same state.
3283875ed548SDimitry Andric static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3284875ed548SDimitry Andric                                        const DataLayout &DL, Value *Val) {
328539d628a0SDimitry Andric   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
328639d628a0SDimitry Andric   if (!PromotedInst)
328739d628a0SDimitry Andric     return false;
328839d628a0SDimitry Andric   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
328939d628a0SDimitry Andric   // If the ISDOpcode is undefined, it was undefined before the promotion.
329039d628a0SDimitry Andric   if (!ISDOpcode)
329139d628a0SDimitry Andric     return true;
329239d628a0SDimitry Andric   // Otherwise, check if the promoted instruction is legal or not.
329339d628a0SDimitry Andric   return TLI.isOperationLegalOrCustom(
3294875ed548SDimitry Andric       ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
329539d628a0SDimitry Andric }
329639d628a0SDimitry Andric 
329791bc56edSDimitry Andric /// \brief Hepler class to perform type promotion.
329891bc56edSDimitry Andric class TypePromotionHelper {
329939d628a0SDimitry Andric   /// \brief Utility function to check whether or not a sign or zero extension
330039d628a0SDimitry Andric   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
330139d628a0SDimitry Andric   /// either using the operands of \p Inst or promoting \p Inst.
330239d628a0SDimitry Andric   /// The type of the extension is defined by \p IsSExt.
330391bc56edSDimitry Andric   /// In other words, check if:
330439d628a0SDimitry Andric   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
330591bc56edSDimitry Andric   /// #1 Promotion applies:
330639d628a0SDimitry Andric   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
330791bc56edSDimitry Andric   /// #2 Operand reuses:
330839d628a0SDimitry Andric   /// ext opnd1 to ConsideredExtType.
330991bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
331039d628a0SDimitry Andric   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
331139d628a0SDimitry Andric                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
331291bc56edSDimitry Andric 
331391bc56edSDimitry Andric   /// \brief Utility function to determine if \p OpIdx should be promoted when
331491bc56edSDimitry Andric   /// promoting \p Inst.
331539d628a0SDimitry Andric   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
33167d523365SDimitry Andric     return !(isa<SelectInst>(Inst) && OpIdx == 0);
331791bc56edSDimitry Andric   }
331891bc56edSDimitry Andric 
331939d628a0SDimitry Andric   /// \brief Utility function to promote the operand of \p Ext when this
332039d628a0SDimitry Andric   /// operand is a promotable trunc or sext or zext.
332191bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
3322ff0cc061SDimitry Andric   /// \p CreatedInstsCost[out] contains the cost of all instructions
332339d628a0SDimitry Andric   /// created to promote the operand of Ext.
332439d628a0SDimitry Andric   /// Newly added extensions are inserted in \p Exts.
332539d628a0SDimitry Andric   /// Newly added truncates are inserted in \p Truncs.
332691bc56edSDimitry Andric   /// Should never be called directly.
332739d628a0SDimitry Andric   /// \return The promoted value which is used instead of Ext.
332839d628a0SDimitry Andric   static Value *promoteOperandForTruncAndAnyExt(
332939d628a0SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
3330ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
333139d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
3332ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
333391bc56edSDimitry Andric 
333439d628a0SDimitry Andric   /// \brief Utility function to promote the operand of \p Ext when this
333591bc56edSDimitry Andric   /// operand is promotable and is not a supported trunc or sext.
333691bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
3337ff0cc061SDimitry Andric   /// \p CreatedInstsCost[out] contains the cost of all the instructions
333839d628a0SDimitry Andric   /// created to promote the operand of Ext.
333939d628a0SDimitry Andric   /// Newly added extensions are inserted in \p Exts.
334039d628a0SDimitry Andric   /// Newly added truncates are inserted in \p Truncs.
334191bc56edSDimitry Andric   /// Should never be called directly.
334239d628a0SDimitry Andric   /// \return The promoted value which is used instead of Ext.
3343ff0cc061SDimitry Andric   static Value *promoteOperandForOther(Instruction *Ext,
3344ff0cc061SDimitry Andric                                        TypePromotionTransaction &TPT,
3345ff0cc061SDimitry Andric                                        InstrToOrigTy &PromotedInsts,
3346ff0cc061SDimitry Andric                                        unsigned &CreatedInstsCost,
334739d628a0SDimitry Andric                                        SmallVectorImpl<Instruction *> *Exts,
3348ff0cc061SDimitry Andric                                        SmallVectorImpl<Instruction *> *Truncs,
3349ff0cc061SDimitry Andric                                        const TargetLowering &TLI, bool IsSExt);
335039d628a0SDimitry Andric 
335139d628a0SDimitry Andric   /// \see promoteOperandForOther.
3352ff0cc061SDimitry Andric   static Value *signExtendOperandForOther(
3353ff0cc061SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
3354ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
335539d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
3356ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3357ff0cc061SDimitry Andric     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3358ff0cc061SDimitry Andric                                   Exts, Truncs, TLI, true);
335939d628a0SDimitry Andric   }
336039d628a0SDimitry Andric 
336139d628a0SDimitry Andric   /// \see promoteOperandForOther.
3362ff0cc061SDimitry Andric   static Value *zeroExtendOperandForOther(
3363ff0cc061SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
3364ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
336539d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
3366ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3367ff0cc061SDimitry Andric     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3368ff0cc061SDimitry Andric                                   Exts, Truncs, TLI, false);
336939d628a0SDimitry Andric   }
337091bc56edSDimitry Andric 
337191bc56edSDimitry Andric public:
337239d628a0SDimitry Andric   /// Type for the utility function that promotes the operand of Ext.
337339d628a0SDimitry Andric   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
3374ff0cc061SDimitry Andric                            InstrToOrigTy &PromotedInsts,
3375ff0cc061SDimitry Andric                            unsigned &CreatedInstsCost,
337639d628a0SDimitry Andric                            SmallVectorImpl<Instruction *> *Exts,
3377ff0cc061SDimitry Andric                            SmallVectorImpl<Instruction *> *Truncs,
3378ff0cc061SDimitry Andric                            const TargetLowering &TLI);
337939d628a0SDimitry Andric   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
338039d628a0SDimitry Andric   /// action to promote the operand of \p Ext instead of using Ext.
338191bc56edSDimitry Andric   /// \return NULL if no promotable action is possible with the current
338291bc56edSDimitry Andric   /// sign extension.
33838f0fd8f6SDimitry Andric   /// \p InsertedInsts keeps track of all the instructions inserted by the
33848f0fd8f6SDimitry Andric   /// other CodeGenPrepare optimizations. This information is important
338591bc56edSDimitry Andric   /// because we do not want to promote these instructions as CodeGenPrepare
338691bc56edSDimitry Andric   /// will reinsert them later. Thus creating an infinite loop: create/remove.
338791bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
33888f0fd8f6SDimitry Andric   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
338991bc56edSDimitry Andric                           const TargetLowering &TLI,
339091bc56edSDimitry Andric                           const InstrToOrigTy &PromotedInsts);
339191bc56edSDimitry Andric };
339291bc56edSDimitry Andric 
339391bc56edSDimitry Andric bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
339439d628a0SDimitry Andric                                         Type *ConsideredExtType,
339539d628a0SDimitry Andric                                         const InstrToOrigTy &PromotedInsts,
339639d628a0SDimitry Andric                                         bool IsSExt) {
339739d628a0SDimitry Andric   // The promotion helper does not know how to deal with vector types yet.
339839d628a0SDimitry Andric   // To be able to fix that, we would need to fix the places where we
339939d628a0SDimitry Andric   // statically extend, e.g., constants and such.
340039d628a0SDimitry Andric   if (Inst->getType()->isVectorTy())
340139d628a0SDimitry Andric     return false;
340239d628a0SDimitry Andric 
340339d628a0SDimitry Andric   // We can always get through zext.
340439d628a0SDimitry Andric   if (isa<ZExtInst>(Inst))
340539d628a0SDimitry Andric     return true;
340639d628a0SDimitry Andric 
340739d628a0SDimitry Andric   // sext(sext) is ok too.
340839d628a0SDimitry Andric   if (IsSExt && isa<SExtInst>(Inst))
340991bc56edSDimitry Andric     return true;
341091bc56edSDimitry Andric 
341191bc56edSDimitry Andric   // We can get through binary operator, if it is legal. In other words, the
341291bc56edSDimitry Andric   // binary operator must have a nuw or nsw flag.
341391bc56edSDimitry Andric   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
341491bc56edSDimitry Andric   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
341539d628a0SDimitry Andric       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
341639d628a0SDimitry Andric        (IsSExt && BinOp->hasNoSignedWrap())))
341791bc56edSDimitry Andric     return true;
341891bc56edSDimitry Andric 
341991bc56edSDimitry Andric   // Check if we can do the following simplification.
342039d628a0SDimitry Andric   // ext(trunc(opnd)) --> ext(opnd)
342191bc56edSDimitry Andric   if (!isa<TruncInst>(Inst))
342291bc56edSDimitry Andric     return false;
342391bc56edSDimitry Andric 
342491bc56edSDimitry Andric   Value *OpndVal = Inst->getOperand(0);
342539d628a0SDimitry Andric   // Check if we can use this operand in the extension.
34267d523365SDimitry Andric   // If the type is larger than the result type of the extension, we cannot.
342739d628a0SDimitry Andric   if (!OpndVal->getType()->isIntegerTy() ||
342839d628a0SDimitry Andric       OpndVal->getType()->getIntegerBitWidth() >
342939d628a0SDimitry Andric           ConsideredExtType->getIntegerBitWidth())
343091bc56edSDimitry Andric     return false;
343191bc56edSDimitry Andric 
343291bc56edSDimitry Andric   // If the operand of the truncate is not an instruction, we will not have
343391bc56edSDimitry Andric   // any information on the dropped bits.
343491bc56edSDimitry Andric   // (Actually we could for constant but it is not worth the extra logic).
343591bc56edSDimitry Andric   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
343691bc56edSDimitry Andric   if (!Opnd)
343791bc56edSDimitry Andric     return false;
343891bc56edSDimitry Andric 
343991bc56edSDimitry Andric   // Check if the source of the type is narrow enough.
344039d628a0SDimitry Andric   // I.e., check that trunc just drops extended bits of the same kind of
344139d628a0SDimitry Andric   // the extension.
344239d628a0SDimitry Andric   // #1 get the type of the operand and check the kind of the extended bits.
344391bc56edSDimitry Andric   const Type *OpndType;
344491bc56edSDimitry Andric   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
34457d523365SDimitry Andric   if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
34467d523365SDimitry Andric     OpndType = It->second.getPointer();
344739d628a0SDimitry Andric   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
344839d628a0SDimitry Andric     OpndType = Opnd->getOperand(0)->getType();
344991bc56edSDimitry Andric   else
345091bc56edSDimitry Andric     return false;
345191bc56edSDimitry Andric 
34527d523365SDimitry Andric   // #2 check that the truncate just drops extended bits.
34537d523365SDimitry Andric   return Inst->getType()->getIntegerBitWidth() >=
34547d523365SDimitry Andric          OpndType->getIntegerBitWidth();
345591bc56edSDimitry Andric }
345691bc56edSDimitry Andric 
345791bc56edSDimitry Andric TypePromotionHelper::Action TypePromotionHelper::getAction(
34588f0fd8f6SDimitry Andric     Instruction *Ext, const SetOfInstrs &InsertedInsts,
345991bc56edSDimitry Andric     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
346039d628a0SDimitry Andric   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
346139d628a0SDimitry Andric          "Unexpected instruction type");
346239d628a0SDimitry Andric   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
346339d628a0SDimitry Andric   Type *ExtTy = Ext->getType();
346439d628a0SDimitry Andric   bool IsSExt = isa<SExtInst>(Ext);
346539d628a0SDimitry Andric   // If the operand of the extension is not an instruction, we cannot
346691bc56edSDimitry Andric   // get through.
346791bc56edSDimitry Andric   // If it, check we can get through.
346839d628a0SDimitry Andric   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
346991bc56edSDimitry Andric     return nullptr;
347091bc56edSDimitry Andric 
347191bc56edSDimitry Andric   // Do not promote if the operand has been added by codegenprepare.
347291bc56edSDimitry Andric   // Otherwise, it means we are undoing an optimization that is likely to be
347391bc56edSDimitry Andric   // redone, thus causing potential infinite loop.
34748f0fd8f6SDimitry Andric   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
347591bc56edSDimitry Andric     return nullptr;
347691bc56edSDimitry Andric 
347791bc56edSDimitry Andric   // SExt or Trunc instructions.
347891bc56edSDimitry Andric   // Return the related handler.
347939d628a0SDimitry Andric   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
348039d628a0SDimitry Andric       isa<ZExtInst>(ExtOpnd))
348139d628a0SDimitry Andric     return promoteOperandForTruncAndAnyExt;
348291bc56edSDimitry Andric 
348391bc56edSDimitry Andric   // Regular instruction.
348491bc56edSDimitry Andric   // Abort early if we will have to insert non-free instructions.
348539d628a0SDimitry Andric   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
348691bc56edSDimitry Andric     return nullptr;
348739d628a0SDimitry Andric   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
348891bc56edSDimitry Andric }
348991bc56edSDimitry Andric 
349039d628a0SDimitry Andric Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
349191bc56edSDimitry Andric     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
3492ff0cc061SDimitry Andric     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
349339d628a0SDimitry Andric     SmallVectorImpl<Instruction *> *Exts,
3494ff0cc061SDimitry Andric     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
349591bc56edSDimitry Andric   // By construction, the operand of SExt is an instruction. Otherwise we cannot
349691bc56edSDimitry Andric   // get through it and this method should not be called.
349791bc56edSDimitry Andric   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
349839d628a0SDimitry Andric   Value *ExtVal = SExt;
3499ff0cc061SDimitry Andric   bool HasMergedNonFreeExt = false;
350039d628a0SDimitry Andric   if (isa<ZExtInst>(SExtOpnd)) {
350139d628a0SDimitry Andric     // Replace s|zext(zext(opnd))
350239d628a0SDimitry Andric     // => zext(opnd).
3503ff0cc061SDimitry Andric     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
350439d628a0SDimitry Andric     Value *ZExt =
350539d628a0SDimitry Andric         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
350639d628a0SDimitry Andric     TPT.replaceAllUsesWith(SExt, ZExt);
350739d628a0SDimitry Andric     TPT.eraseInstruction(SExt);
350839d628a0SDimitry Andric     ExtVal = ZExt;
350939d628a0SDimitry Andric   } else {
351039d628a0SDimitry Andric     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
351139d628a0SDimitry Andric     // => z|sext(opnd).
351291bc56edSDimitry Andric     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
351339d628a0SDimitry Andric   }
3514ff0cc061SDimitry Andric   CreatedInstsCost = 0;
351591bc56edSDimitry Andric 
351691bc56edSDimitry Andric   // Remove dead code.
351791bc56edSDimitry Andric   if (SExtOpnd->use_empty())
351891bc56edSDimitry Andric     TPT.eraseInstruction(SExtOpnd);
351991bc56edSDimitry Andric 
352039d628a0SDimitry Andric   // Check if the extension is still needed.
352139d628a0SDimitry Andric   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
352239d628a0SDimitry Andric   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3523ff0cc061SDimitry Andric     if (ExtInst) {
3524ff0cc061SDimitry Andric       if (Exts)
352539d628a0SDimitry Andric         Exts->push_back(ExtInst);
3526ff0cc061SDimitry Andric       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3527ff0cc061SDimitry Andric     }
352839d628a0SDimitry Andric     return ExtVal;
352939d628a0SDimitry Andric   }
353091bc56edSDimitry Andric 
353139d628a0SDimitry Andric   // At this point we have: ext ty opnd to ty.
353239d628a0SDimitry Andric   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
353339d628a0SDimitry Andric   Value *NextVal = ExtInst->getOperand(0);
353439d628a0SDimitry Andric   TPT.eraseInstruction(ExtInst, NextVal);
353591bc56edSDimitry Andric   return NextVal;
353691bc56edSDimitry Andric }
353791bc56edSDimitry Andric 
353839d628a0SDimitry Andric Value *TypePromotionHelper::promoteOperandForOther(
353939d628a0SDimitry Andric     Instruction *Ext, TypePromotionTransaction &TPT,
3540ff0cc061SDimitry Andric     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
354139d628a0SDimitry Andric     SmallVectorImpl<Instruction *> *Exts,
3542ff0cc061SDimitry Andric     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3543ff0cc061SDimitry Andric     bool IsSExt) {
354439d628a0SDimitry Andric   // By construction, the operand of Ext is an instruction. Otherwise we cannot
354591bc56edSDimitry Andric   // get through it and this method should not be called.
354639d628a0SDimitry Andric   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3547ff0cc061SDimitry Andric   CreatedInstsCost = 0;
354839d628a0SDimitry Andric   if (!ExtOpnd->hasOneUse()) {
354939d628a0SDimitry Andric     // ExtOpnd will be promoted.
355039d628a0SDimitry Andric     // All its uses, but Ext, will need to use a truncated value of the
355191bc56edSDimitry Andric     // promoted version.
355291bc56edSDimitry Andric     // Create the truncate now.
355339d628a0SDimitry Andric     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
355439d628a0SDimitry Andric     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
355539d628a0SDimitry Andric       ITrunc->removeFromParent();
355691bc56edSDimitry Andric       // Insert it just after the definition.
355739d628a0SDimitry Andric       ITrunc->insertAfter(ExtOpnd);
355839d628a0SDimitry Andric       if (Truncs)
355939d628a0SDimitry Andric         Truncs->push_back(ITrunc);
356039d628a0SDimitry Andric     }
356191bc56edSDimitry Andric 
356239d628a0SDimitry Andric     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
35637d523365SDimitry Andric     // Restore the operand of Ext (which has been replaced by the previous call
356491bc56edSDimitry Andric     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
356539d628a0SDimitry Andric     TPT.setOperand(Ext, 0, ExtOpnd);
356691bc56edSDimitry Andric   }
356791bc56edSDimitry Andric 
356891bc56edSDimitry Andric   // Get through the Instruction:
356991bc56edSDimitry Andric   // 1. Update its type.
357039d628a0SDimitry Andric   // 2. Replace the uses of Ext by Inst.
357139d628a0SDimitry Andric   // 3. Extend each operand that needs to be extended.
357291bc56edSDimitry Andric 
357391bc56edSDimitry Andric   // Remember the original type of the instruction before promotion.
357491bc56edSDimitry Andric   // This is useful to know that the high bits are sign extended bits.
357539d628a0SDimitry Andric   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
357639d628a0SDimitry Andric       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
357791bc56edSDimitry Andric   // Step #1.
357839d628a0SDimitry Andric   TPT.mutateType(ExtOpnd, Ext->getType());
357991bc56edSDimitry Andric   // Step #2.
358039d628a0SDimitry Andric   TPT.replaceAllUsesWith(Ext, ExtOpnd);
358191bc56edSDimitry Andric   // Step #3.
358239d628a0SDimitry Andric   Instruction *ExtForOpnd = Ext;
358391bc56edSDimitry Andric 
358439d628a0SDimitry Andric   DEBUG(dbgs() << "Propagate Ext to operands\n");
358539d628a0SDimitry Andric   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
358691bc56edSDimitry Andric        ++OpIdx) {
358739d628a0SDimitry Andric     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
358839d628a0SDimitry Andric     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
358939d628a0SDimitry Andric         !shouldExtOperand(ExtOpnd, OpIdx)) {
359091bc56edSDimitry Andric       DEBUG(dbgs() << "No need to propagate\n");
359191bc56edSDimitry Andric       continue;
359291bc56edSDimitry Andric     }
359339d628a0SDimitry Andric     // Check if we can statically extend the operand.
359439d628a0SDimitry Andric     Value *Opnd = ExtOpnd->getOperand(OpIdx);
359591bc56edSDimitry Andric     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
359639d628a0SDimitry Andric       DEBUG(dbgs() << "Statically extend\n");
359739d628a0SDimitry Andric       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
359839d628a0SDimitry Andric       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
359939d628a0SDimitry Andric                             : Cst->getValue().zext(BitWidth);
360039d628a0SDimitry Andric       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
360191bc56edSDimitry Andric       continue;
360291bc56edSDimitry Andric     }
360391bc56edSDimitry Andric     // UndefValue are typed, so we have to statically sign extend them.
360491bc56edSDimitry Andric     if (isa<UndefValue>(Opnd)) {
360539d628a0SDimitry Andric       DEBUG(dbgs() << "Statically extend\n");
360639d628a0SDimitry Andric       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
360791bc56edSDimitry Andric       continue;
360891bc56edSDimitry Andric     }
360991bc56edSDimitry Andric 
361091bc56edSDimitry Andric     // Otherwise we have to explicity sign extend the operand.
361139d628a0SDimitry Andric     // Check if Ext was reused to extend an operand.
361239d628a0SDimitry Andric     if (!ExtForOpnd) {
361391bc56edSDimitry Andric       // If yes, create a new one.
361439d628a0SDimitry Andric       DEBUG(dbgs() << "More operands to ext\n");
361539d628a0SDimitry Andric       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
361639d628a0SDimitry Andric         : TPT.createZExt(Ext, Opnd, Ext->getType());
361739d628a0SDimitry Andric       if (!isa<Instruction>(ValForExtOpnd)) {
361839d628a0SDimitry Andric         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
361939d628a0SDimitry Andric         continue;
362039d628a0SDimitry Andric       }
362139d628a0SDimitry Andric       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
362291bc56edSDimitry Andric     }
362339d628a0SDimitry Andric     if (Exts)
362439d628a0SDimitry Andric       Exts->push_back(ExtForOpnd);
362539d628a0SDimitry Andric     TPT.setOperand(ExtForOpnd, 0, Opnd);
362691bc56edSDimitry Andric 
362791bc56edSDimitry Andric     // Move the sign extension before the insertion point.
362839d628a0SDimitry Andric     TPT.moveBefore(ExtForOpnd, ExtOpnd);
362939d628a0SDimitry Andric     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3630ff0cc061SDimitry Andric     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
363191bc56edSDimitry Andric     // If more sext are required, new instructions will have to be created.
363239d628a0SDimitry Andric     ExtForOpnd = nullptr;
363391bc56edSDimitry Andric   }
363439d628a0SDimitry Andric   if (ExtForOpnd == Ext) {
363539d628a0SDimitry Andric     DEBUG(dbgs() << "Extension is useless now\n");
363639d628a0SDimitry Andric     TPT.eraseInstruction(Ext);
363791bc56edSDimitry Andric   }
363839d628a0SDimitry Andric   return ExtOpnd;
363991bc56edSDimitry Andric }
364091bc56edSDimitry Andric 
36417d523365SDimitry Andric /// Check whether or not promoting an instruction to a wider type is profitable.
3642ff0cc061SDimitry Andric /// \p NewCost gives the cost of extension instructions created by the
3643ff0cc061SDimitry Andric /// promotion.
3644ff0cc061SDimitry Andric /// \p OldCost gives the cost of extension instructions before the promotion
3645ff0cc061SDimitry Andric /// plus the number of instructions that have been
3646ff0cc061SDimitry Andric /// matched in the addressing mode the promotion.
364791bc56edSDimitry Andric /// \p PromotedOperand is the value that has been promoted.
364891bc56edSDimitry Andric /// \return True if the promotion is profitable, false otherwise.
36497d523365SDimitry Andric bool AddressingModeMatcher::isPromotionProfitable(
3650ff0cc061SDimitry Andric     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3651ff0cc061SDimitry Andric   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3652ff0cc061SDimitry Andric   // The cost of the new extensions is greater than the cost of the
3653ff0cc061SDimitry Andric   // old extension plus what we folded.
365491bc56edSDimitry Andric   // This is not profitable.
3655ff0cc061SDimitry Andric   if (NewCost > OldCost)
365691bc56edSDimitry Andric     return false;
3657ff0cc061SDimitry Andric   if (NewCost < OldCost)
365891bc56edSDimitry Andric     return true;
365991bc56edSDimitry Andric   // The promotion is neutral but it may help folding the sign extension in
366091bc56edSDimitry Andric   // loads for instance.
366191bc56edSDimitry Andric   // Check that we did not create an illegal instruction.
3662875ed548SDimitry Andric   return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
366391bc56edSDimitry Andric }
366491bc56edSDimitry Andric 
36657d523365SDimitry Andric /// Given an instruction or constant expr, see if we can fold the operation
36667d523365SDimitry Andric /// into the addressing mode. If so, update the addressing mode and return
36677d523365SDimitry Andric /// true, otherwise return false without modifying AddrMode.
366891bc56edSDimitry Andric /// If \p MovedAway is not NULL, it contains the information of whether or
366991bc56edSDimitry Andric /// not AddrInst has to be folded into the addressing mode on success.
367091bc56edSDimitry Andric /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
367191bc56edSDimitry Andric /// because it has been moved away.
367291bc56edSDimitry Andric /// Thus AddrInst must not be added in the matched instructions.
367391bc56edSDimitry Andric /// This state can happen when AddrInst is a sext, since it may be moved away.
367491bc56edSDimitry Andric /// Therefore, AddrInst may not be valid when MovedAway is true and it must
367591bc56edSDimitry Andric /// not be referenced anymore.
36767d523365SDimitry Andric bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
367791bc56edSDimitry Andric                                                unsigned Depth,
367891bc56edSDimitry Andric                                                bool *MovedAway) {
367991bc56edSDimitry Andric   // Avoid exponential behavior on extremely deep expression trees.
368091bc56edSDimitry Andric   if (Depth >= 5) return false;
368191bc56edSDimitry Andric 
368291bc56edSDimitry Andric   // By default, all matched instructions stay in place.
368391bc56edSDimitry Andric   if (MovedAway)
368491bc56edSDimitry Andric     *MovedAway = false;
368591bc56edSDimitry Andric 
368691bc56edSDimitry Andric   switch (Opcode) {
368791bc56edSDimitry Andric   case Instruction::PtrToInt:
368891bc56edSDimitry Andric     // PtrToInt is always a noop, as we know that the int type is pointer sized.
36897d523365SDimitry Andric     return matchAddr(AddrInst->getOperand(0), Depth);
3690875ed548SDimitry Andric   case Instruction::IntToPtr: {
3691875ed548SDimitry Andric     auto AS = AddrInst->getType()->getPointerAddressSpace();
3692875ed548SDimitry Andric     auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
369391bc56edSDimitry Andric     // This inttoptr is a no-op if the integer type is pointer sized.
3694875ed548SDimitry Andric     if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
36957d523365SDimitry Andric       return matchAddr(AddrInst->getOperand(0), Depth);
369691bc56edSDimitry Andric     return false;
3697875ed548SDimitry Andric   }
369891bc56edSDimitry Andric   case Instruction::BitCast:
369991bc56edSDimitry Andric     // BitCast is always a noop, and we can handle it as long as it is
370091bc56edSDimitry Andric     // int->int or pointer->pointer (we don't want int<->fp or something).
370191bc56edSDimitry Andric     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
370291bc56edSDimitry Andric          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
370391bc56edSDimitry Andric         // Don't touch identity bitcasts.  These were probably put here by LSR,
370491bc56edSDimitry Andric         // and we don't want to mess around with them.  Assume it knows what it
370591bc56edSDimitry Andric         // is doing.
370691bc56edSDimitry Andric         AddrInst->getOperand(0)->getType() != AddrInst->getType())
37077d523365SDimitry Andric       return matchAddr(AddrInst->getOperand(0), Depth);
370891bc56edSDimitry Andric     return false;
3709ff0cc061SDimitry Andric   case Instruction::AddrSpaceCast: {
3710ff0cc061SDimitry Andric     unsigned SrcAS
3711ff0cc061SDimitry Andric       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3712ff0cc061SDimitry Andric     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3713ff0cc061SDimitry Andric     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
37147d523365SDimitry Andric       return matchAddr(AddrInst->getOperand(0), Depth);
3715ff0cc061SDimitry Andric     return false;
3716ff0cc061SDimitry Andric   }
371791bc56edSDimitry Andric   case Instruction::Add: {
371891bc56edSDimitry Andric     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
371991bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
372091bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
372191bc56edSDimitry Andric     // Start a transaction at this point.
372291bc56edSDimitry Andric     // The LHS may match but not the RHS.
372391bc56edSDimitry Andric     // Therefore, we need a higher level restoration point to undo partially
372491bc56edSDimitry Andric     // matched operation.
372591bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
372691bc56edSDimitry Andric         TPT.getRestorationPoint();
372791bc56edSDimitry Andric 
37287d523365SDimitry Andric     if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
37297d523365SDimitry Andric         matchAddr(AddrInst->getOperand(0), Depth+1))
373091bc56edSDimitry Andric       return true;
373191bc56edSDimitry Andric 
373291bc56edSDimitry Andric     // Restore the old addr mode info.
373391bc56edSDimitry Andric     AddrMode = BackupAddrMode;
373491bc56edSDimitry Andric     AddrModeInsts.resize(OldSize);
373591bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
373691bc56edSDimitry Andric 
373791bc56edSDimitry Andric     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
37387d523365SDimitry Andric     if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
37397d523365SDimitry Andric         matchAddr(AddrInst->getOperand(1), Depth+1))
374091bc56edSDimitry Andric       return true;
374191bc56edSDimitry Andric 
374291bc56edSDimitry Andric     // Otherwise we definitely can't merge the ADD in.
374391bc56edSDimitry Andric     AddrMode = BackupAddrMode;
374491bc56edSDimitry Andric     AddrModeInsts.resize(OldSize);
374591bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
374691bc56edSDimitry Andric     break;
374791bc56edSDimitry Andric   }
374891bc56edSDimitry Andric   //case Instruction::Or:
374991bc56edSDimitry Andric   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
375091bc56edSDimitry Andric   //break;
375191bc56edSDimitry Andric   case Instruction::Mul:
375291bc56edSDimitry Andric   case Instruction::Shl: {
375391bc56edSDimitry Andric     // Can only handle X*C and X << C.
375491bc56edSDimitry Andric     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
375591bc56edSDimitry Andric     if (!RHS)
375691bc56edSDimitry Andric       return false;
375791bc56edSDimitry Andric     int64_t Scale = RHS->getSExtValue();
375891bc56edSDimitry Andric     if (Opcode == Instruction::Shl)
375991bc56edSDimitry Andric       Scale = 1LL << Scale;
376091bc56edSDimitry Andric 
37617d523365SDimitry Andric     return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
376291bc56edSDimitry Andric   }
376391bc56edSDimitry Andric   case Instruction::GetElementPtr: {
376491bc56edSDimitry Andric     // Scan the GEP.  We check it if it contains constant offsets and at most
376591bc56edSDimitry Andric     // one variable offset.
376691bc56edSDimitry Andric     int VariableOperand = -1;
376791bc56edSDimitry Andric     unsigned VariableScale = 0;
376891bc56edSDimitry Andric 
376991bc56edSDimitry Andric     int64_t ConstantOffset = 0;
377091bc56edSDimitry Andric     gep_type_iterator GTI = gep_type_begin(AddrInst);
377191bc56edSDimitry Andric     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3772d88c1a5aSDimitry Andric       if (StructType *STy = GTI.getStructTypeOrNull()) {
3773875ed548SDimitry Andric         const StructLayout *SL = DL.getStructLayout(STy);
377491bc56edSDimitry Andric         unsigned Idx =
377591bc56edSDimitry Andric           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
377691bc56edSDimitry Andric         ConstantOffset += SL->getElementOffset(Idx);
377791bc56edSDimitry Andric       } else {
3778875ed548SDimitry Andric         uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
377991bc56edSDimitry Andric         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
378091bc56edSDimitry Andric           ConstantOffset += CI->getSExtValue()*TypeSize;
378191bc56edSDimitry Andric         } else if (TypeSize) {  // Scales of zero don't do anything.
378291bc56edSDimitry Andric           // We only allow one variable index at the moment.
378391bc56edSDimitry Andric           if (VariableOperand != -1)
378491bc56edSDimitry Andric             return false;
378591bc56edSDimitry Andric 
378691bc56edSDimitry Andric           // Remember the variable index.
378791bc56edSDimitry Andric           VariableOperand = i;
378891bc56edSDimitry Andric           VariableScale = TypeSize;
378991bc56edSDimitry Andric         }
379091bc56edSDimitry Andric       }
379191bc56edSDimitry Andric     }
379291bc56edSDimitry Andric 
379391bc56edSDimitry Andric     // A common case is for the GEP to only do a constant offset.  In this case,
379491bc56edSDimitry Andric     // just add it to the disp field and check validity.
379591bc56edSDimitry Andric     if (VariableOperand == -1) {
379691bc56edSDimitry Andric       AddrMode.BaseOffs += ConstantOffset;
379797bc6c73SDimitry Andric       if (ConstantOffset == 0 ||
3798875ed548SDimitry Andric           TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
379991bc56edSDimitry Andric         // Check to see if we can fold the base pointer in too.
38007d523365SDimitry Andric         if (matchAddr(AddrInst->getOperand(0), Depth+1))
380191bc56edSDimitry Andric           return true;
380291bc56edSDimitry Andric       }
380391bc56edSDimitry Andric       AddrMode.BaseOffs -= ConstantOffset;
380491bc56edSDimitry Andric       return false;
380591bc56edSDimitry Andric     }
380691bc56edSDimitry Andric 
380791bc56edSDimitry Andric     // Save the valid addressing mode in case we can't match.
380891bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
380991bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
381091bc56edSDimitry Andric 
381191bc56edSDimitry Andric     // See if the scale and offset amount is valid for this target.
381291bc56edSDimitry Andric     AddrMode.BaseOffs += ConstantOffset;
381391bc56edSDimitry Andric 
381491bc56edSDimitry Andric     // Match the base operand of the GEP.
38157d523365SDimitry Andric     if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
381691bc56edSDimitry Andric       // If it couldn't be matched, just stuff the value in a register.
381791bc56edSDimitry Andric       if (AddrMode.HasBaseReg) {
381891bc56edSDimitry Andric         AddrMode = BackupAddrMode;
381991bc56edSDimitry Andric         AddrModeInsts.resize(OldSize);
382091bc56edSDimitry Andric         return false;
382191bc56edSDimitry Andric       }
382291bc56edSDimitry Andric       AddrMode.HasBaseReg = true;
382391bc56edSDimitry Andric       AddrMode.BaseReg = AddrInst->getOperand(0);
382491bc56edSDimitry Andric     }
382591bc56edSDimitry Andric 
382691bc56edSDimitry Andric     // Match the remaining variable portion of the GEP.
38277d523365SDimitry Andric     if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
382891bc56edSDimitry Andric                           Depth)) {
382991bc56edSDimitry Andric       // If it couldn't be matched, try stuffing the base into a register
383091bc56edSDimitry Andric       // instead of matching it, and retrying the match of the scale.
383191bc56edSDimitry Andric       AddrMode = BackupAddrMode;
383291bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
383391bc56edSDimitry Andric       if (AddrMode.HasBaseReg)
383491bc56edSDimitry Andric         return false;
383591bc56edSDimitry Andric       AddrMode.HasBaseReg = true;
383691bc56edSDimitry Andric       AddrMode.BaseReg = AddrInst->getOperand(0);
383791bc56edSDimitry Andric       AddrMode.BaseOffs += ConstantOffset;
38387d523365SDimitry Andric       if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
383991bc56edSDimitry Andric                             VariableScale, Depth)) {
384091bc56edSDimitry Andric         // If even that didn't work, bail.
384191bc56edSDimitry Andric         AddrMode = BackupAddrMode;
384291bc56edSDimitry Andric         AddrModeInsts.resize(OldSize);
384391bc56edSDimitry Andric         return false;
384491bc56edSDimitry Andric       }
384591bc56edSDimitry Andric     }
384691bc56edSDimitry Andric 
384791bc56edSDimitry Andric     return true;
384891bc56edSDimitry Andric   }
384939d628a0SDimitry Andric   case Instruction::SExt:
385039d628a0SDimitry Andric   case Instruction::ZExt: {
385139d628a0SDimitry Andric     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
385239d628a0SDimitry Andric     if (!Ext)
385391bc56edSDimitry Andric       return false;
385491bc56edSDimitry Andric 
385539d628a0SDimitry Andric     // Try to move this ext out of the way of the addressing mode.
385691bc56edSDimitry Andric     // Ask for a method for doing so.
385739d628a0SDimitry Andric     TypePromotionHelper::Action TPH =
38588f0fd8f6SDimitry Andric         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
385991bc56edSDimitry Andric     if (!TPH)
386091bc56edSDimitry Andric       return false;
386191bc56edSDimitry Andric 
386291bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
386391bc56edSDimitry Andric         TPT.getRestorationPoint();
3864ff0cc061SDimitry Andric     unsigned CreatedInstsCost = 0;
3865ff0cc061SDimitry Andric     unsigned ExtCost = !TLI.isExtFree(Ext);
386639d628a0SDimitry Andric     Value *PromotedOperand =
3867ff0cc061SDimitry Andric         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
386891bc56edSDimitry Andric     // SExt has been moved away.
386991bc56edSDimitry Andric     // Thus either it will be rematched later in the recursive calls or it is
387091bc56edSDimitry Andric     // gone. Anyway, we must not fold it into the addressing mode at this point.
387191bc56edSDimitry Andric     // E.g.,
387291bc56edSDimitry Andric     // op = add opnd, 1
387339d628a0SDimitry Andric     // idx = ext op
387491bc56edSDimitry Andric     // addr = gep base, idx
387591bc56edSDimitry Andric     // is now:
387639d628a0SDimitry Andric     // promotedOpnd = ext opnd            <- no match here
387791bc56edSDimitry Andric     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
387891bc56edSDimitry Andric     // addr = gep base, op                <- match
387991bc56edSDimitry Andric     if (MovedAway)
388091bc56edSDimitry Andric       *MovedAway = true;
388191bc56edSDimitry Andric 
388291bc56edSDimitry Andric     assert(PromotedOperand &&
388391bc56edSDimitry Andric            "TypePromotionHelper should have filtered out those cases");
388491bc56edSDimitry Andric 
388591bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
388691bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
388791bc56edSDimitry Andric 
38887d523365SDimitry Andric     if (!matchAddr(PromotedOperand, Depth) ||
38897d523365SDimitry Andric         // The total of the new cost is equal to the cost of the created
3890ff0cc061SDimitry Andric         // instructions.
38917d523365SDimitry Andric         // The total of the old cost is equal to the cost of the extension plus
3892ff0cc061SDimitry Andric         // what we have saved in the addressing mode.
38937d523365SDimitry Andric         !isPromotionProfitable(CreatedInstsCost,
3894ff0cc061SDimitry Andric                                ExtCost + (AddrModeInsts.size() - OldSize),
389591bc56edSDimitry Andric                                PromotedOperand)) {
389691bc56edSDimitry Andric       AddrMode = BackupAddrMode;
389791bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
389891bc56edSDimitry Andric       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
389991bc56edSDimitry Andric       TPT.rollback(LastKnownGood);
390091bc56edSDimitry Andric       return false;
390191bc56edSDimitry Andric     }
390291bc56edSDimitry Andric     return true;
390391bc56edSDimitry Andric   }
390491bc56edSDimitry Andric   }
390591bc56edSDimitry Andric   return false;
390691bc56edSDimitry Andric }
390791bc56edSDimitry Andric 
39087d523365SDimitry Andric /// If we can, try to add the value of 'Addr' into the current addressing mode.
39097d523365SDimitry Andric /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
39107d523365SDimitry Andric /// unmodified. This assumes that Addr is either a pointer type or intptr_t
39117d523365SDimitry Andric /// for the target.
391291bc56edSDimitry Andric ///
39137d523365SDimitry Andric bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
391491bc56edSDimitry Andric   // Start a transaction at this point that we will rollback if the matching
391591bc56edSDimitry Andric   // fails.
391691bc56edSDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
391791bc56edSDimitry Andric       TPT.getRestorationPoint();
391891bc56edSDimitry Andric   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
391991bc56edSDimitry Andric     // Fold in immediates if legal for the target.
392091bc56edSDimitry Andric     AddrMode.BaseOffs += CI->getSExtValue();
3921875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
392291bc56edSDimitry Andric       return true;
392391bc56edSDimitry Andric     AddrMode.BaseOffs -= CI->getSExtValue();
392491bc56edSDimitry Andric   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
392591bc56edSDimitry Andric     // If this is a global variable, try to fold it into the addressing mode.
392691bc56edSDimitry Andric     if (!AddrMode.BaseGV) {
392791bc56edSDimitry Andric       AddrMode.BaseGV = GV;
3928875ed548SDimitry Andric       if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
392991bc56edSDimitry Andric         return true;
393091bc56edSDimitry Andric       AddrMode.BaseGV = nullptr;
393191bc56edSDimitry Andric     }
393291bc56edSDimitry Andric   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
393391bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
393491bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
393591bc56edSDimitry Andric 
393691bc56edSDimitry Andric     // Check to see if it is possible to fold this operation.
393791bc56edSDimitry Andric     bool MovedAway = false;
39387d523365SDimitry Andric     if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
39397d523365SDimitry Andric       // This instruction may have been moved away. If so, there is nothing
394091bc56edSDimitry Andric       // to check here.
394191bc56edSDimitry Andric       if (MovedAway)
394291bc56edSDimitry Andric         return true;
394391bc56edSDimitry Andric       // Okay, it's possible to fold this.  Check to see if it is actually
394491bc56edSDimitry Andric       // *profitable* to do so.  We use a simple cost model to avoid increasing
394591bc56edSDimitry Andric       // register pressure too much.
394691bc56edSDimitry Andric       if (I->hasOneUse() ||
39477d523365SDimitry Andric           isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
394891bc56edSDimitry Andric         AddrModeInsts.push_back(I);
394991bc56edSDimitry Andric         return true;
395091bc56edSDimitry Andric       }
395191bc56edSDimitry Andric 
395291bc56edSDimitry Andric       // It isn't profitable to do this, roll back.
395391bc56edSDimitry Andric       //cerr << "NOT FOLDING: " << *I;
395491bc56edSDimitry Andric       AddrMode = BackupAddrMode;
395591bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
395691bc56edSDimitry Andric       TPT.rollback(LastKnownGood);
395791bc56edSDimitry Andric     }
395891bc56edSDimitry Andric   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
39597d523365SDimitry Andric     if (matchOperationAddr(CE, CE->getOpcode(), Depth))
396091bc56edSDimitry Andric       return true;
396191bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
396291bc56edSDimitry Andric   } else if (isa<ConstantPointerNull>(Addr)) {
396391bc56edSDimitry Andric     // Null pointer gets folded without affecting the addressing mode.
396491bc56edSDimitry Andric     return true;
396591bc56edSDimitry Andric   }
396691bc56edSDimitry Andric 
396791bc56edSDimitry Andric   // Worse case, the target should support [reg] addressing modes. :)
396891bc56edSDimitry Andric   if (!AddrMode.HasBaseReg) {
396991bc56edSDimitry Andric     AddrMode.HasBaseReg = true;
397091bc56edSDimitry Andric     AddrMode.BaseReg = Addr;
397191bc56edSDimitry Andric     // Still check for legality in case the target supports [imm] but not [i+r].
3972875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
397391bc56edSDimitry Andric       return true;
397491bc56edSDimitry Andric     AddrMode.HasBaseReg = false;
397591bc56edSDimitry Andric     AddrMode.BaseReg = nullptr;
397691bc56edSDimitry Andric   }
397791bc56edSDimitry Andric 
397891bc56edSDimitry Andric   // If the base register is already taken, see if we can do [r+r].
397991bc56edSDimitry Andric   if (AddrMode.Scale == 0) {
398091bc56edSDimitry Andric     AddrMode.Scale = 1;
398191bc56edSDimitry Andric     AddrMode.ScaledReg = Addr;
3982875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
398391bc56edSDimitry Andric       return true;
398491bc56edSDimitry Andric     AddrMode.Scale = 0;
398591bc56edSDimitry Andric     AddrMode.ScaledReg = nullptr;
398691bc56edSDimitry Andric   }
398791bc56edSDimitry Andric   // Couldn't match.
398891bc56edSDimitry Andric   TPT.rollback(LastKnownGood);
398991bc56edSDimitry Andric   return false;
399091bc56edSDimitry Andric }
399191bc56edSDimitry Andric 
39927d523365SDimitry Andric /// Check to see if all uses of OpVal by the specified inline asm call are due
39937d523365SDimitry Andric /// to memory operands. If so, return true, otherwise return false.
399491bc56edSDimitry Andric static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
39957a7e6055SDimitry Andric                                     const TargetLowering &TLI,
39967a7e6055SDimitry Andric                                     const TargetRegisterInfo &TRI) {
3997db17bf38SDimitry Andric   const Function *F = CI->getFunction();
3998ff0cc061SDimitry Andric   TargetLowering::AsmOperandInfoVector TargetConstraints =
39997a7e6055SDimitry Andric       TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
4000875ed548SDimitry Andric                             ImmutableCallSite(CI));
40017a7e6055SDimitry Andric 
400291bc56edSDimitry Andric   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
400391bc56edSDimitry Andric     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
400491bc56edSDimitry Andric 
400591bc56edSDimitry Andric     // Compute the constraint code and ConstraintType to use.
40067a7e6055SDimitry Andric     TLI.ComputeConstraintToUse(OpInfo, SDValue());
400791bc56edSDimitry Andric 
400891bc56edSDimitry Andric     // If this asm operand is our Value*, and if it isn't an indirect memory
400991bc56edSDimitry Andric     // operand, we can't fold it!
401091bc56edSDimitry Andric     if (OpInfo.CallOperandVal == OpVal &&
401191bc56edSDimitry Andric         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
401291bc56edSDimitry Andric          !OpInfo.isIndirect))
401391bc56edSDimitry Andric       return false;
401491bc56edSDimitry Andric   }
401591bc56edSDimitry Andric 
401691bc56edSDimitry Andric   return true;
401791bc56edSDimitry Andric }
401891bc56edSDimitry Andric 
4019*4dfab2ebSDimitry Andric // Max number of memory uses to look at before aborting the search to conserve
4020*4dfab2ebSDimitry Andric // compile time.
4021*4dfab2ebSDimitry Andric static constexpr int MaxMemoryUsesToScan = 20;
4022*4dfab2ebSDimitry Andric 
40237d523365SDimitry Andric /// Recursively walk all the uses of I until we find a memory use.
40247d523365SDimitry Andric /// If we find an obviously non-foldable instruction, return true.
402591bc56edSDimitry Andric /// Add the ultimately found memory instructions to MemoryUses.
4026ff0cc061SDimitry Andric static bool FindAllMemoryUses(
4027ff0cc061SDimitry Andric     Instruction *I,
402891bc56edSDimitry Andric     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
4029*4dfab2ebSDimitry Andric     SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4030*4dfab2ebSDimitry Andric     const TargetRegisterInfo &TRI, int SeenInsts = 0) {
403191bc56edSDimitry Andric   // If we already considered this instruction, we're done.
403239d628a0SDimitry Andric   if (!ConsideredInsts.insert(I).second)
403391bc56edSDimitry Andric     return false;
403491bc56edSDimitry Andric 
403591bc56edSDimitry Andric   // If this is an obviously unfoldable instruction, bail out.
403691bc56edSDimitry Andric   if (!MightBeFoldableInst(I))
403791bc56edSDimitry Andric     return true;
403891bc56edSDimitry Andric 
40393ca95b02SDimitry Andric   const bool OptSize = I->getFunction()->optForSize();
40403ca95b02SDimitry Andric 
404191bc56edSDimitry Andric   // Loop over all the uses, recursively processing them.
404291bc56edSDimitry Andric   for (Use &U : I->uses()) {
4043*4dfab2ebSDimitry Andric     // Conservatively return true if we're seeing a large number or a deep chain
4044*4dfab2ebSDimitry Andric     // of users. This avoids excessive compilation times in pathological cases.
4045*4dfab2ebSDimitry Andric     if (SeenInsts++ >= MaxMemoryUsesToScan)
4046*4dfab2ebSDimitry Andric       return true;
404791bc56edSDimitry Andric 
4048*4dfab2ebSDimitry Andric     Instruction *UserI = cast<Instruction>(U.getUser());
404991bc56edSDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
405091bc56edSDimitry Andric       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
405191bc56edSDimitry Andric       continue;
405291bc56edSDimitry Andric     }
405391bc56edSDimitry Andric 
405491bc56edSDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
405591bc56edSDimitry Andric       unsigned opNo = U.getOperandNo();
40567a7e6055SDimitry Andric       if (opNo != StoreInst::getPointerOperandIndex())
40577a7e6055SDimitry Andric         return true; // Storing addr, not into addr.
405891bc56edSDimitry Andric       MemoryUses.push_back(std::make_pair(SI, opNo));
405991bc56edSDimitry Andric       continue;
406091bc56edSDimitry Andric     }
406191bc56edSDimitry Andric 
40627a7e6055SDimitry Andric     if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
40637a7e6055SDimitry Andric       unsigned opNo = U.getOperandNo();
40647a7e6055SDimitry Andric       if (opNo != AtomicRMWInst::getPointerOperandIndex())
40657a7e6055SDimitry Andric         return true; // Storing addr, not into addr.
40667a7e6055SDimitry Andric       MemoryUses.push_back(std::make_pair(RMW, opNo));
40677a7e6055SDimitry Andric       continue;
40687a7e6055SDimitry Andric     }
40697a7e6055SDimitry Andric 
40707a7e6055SDimitry Andric     if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
40717a7e6055SDimitry Andric       unsigned opNo = U.getOperandNo();
40727a7e6055SDimitry Andric       if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
40737a7e6055SDimitry Andric         return true; // Storing addr, not into addr.
40747a7e6055SDimitry Andric       MemoryUses.push_back(std::make_pair(CmpX, opNo));
40757a7e6055SDimitry Andric       continue;
40767a7e6055SDimitry Andric     }
40777a7e6055SDimitry Andric 
407891bc56edSDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
40793ca95b02SDimitry Andric       // If this is a cold call, we can sink the addressing calculation into
40803ca95b02SDimitry Andric       // the cold path.  See optimizeCallInst
40813ca95b02SDimitry Andric       if (!OptSize && CI->hasFnAttr(Attribute::Cold))
40823ca95b02SDimitry Andric         continue;
40833ca95b02SDimitry Andric 
408491bc56edSDimitry Andric       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
408591bc56edSDimitry Andric       if (!IA) return true;
408691bc56edSDimitry Andric 
408791bc56edSDimitry Andric       // If this is a memory operand, we're cool, otherwise bail out.
40887a7e6055SDimitry Andric       if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
408991bc56edSDimitry Andric         return true;
409091bc56edSDimitry Andric       continue;
409191bc56edSDimitry Andric     }
409291bc56edSDimitry Andric 
4093*4dfab2ebSDimitry Andric     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4094*4dfab2ebSDimitry Andric                           SeenInsts))
409591bc56edSDimitry Andric       return true;
409691bc56edSDimitry Andric   }
409791bc56edSDimitry Andric 
409891bc56edSDimitry Andric   return false;
409991bc56edSDimitry Andric }
410091bc56edSDimitry Andric 
41017d523365SDimitry Andric /// Return true if Val is already known to be live at the use site that we're
41027d523365SDimitry Andric /// folding it into. If so, there is no cost to include it in the addressing
41037d523365SDimitry Andric /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
41047d523365SDimitry Andric /// instruction already.
41057d523365SDimitry Andric bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
410691bc56edSDimitry Andric                                                    Value *KnownLive2) {
410791bc56edSDimitry Andric   // If Val is either of the known-live values, we know it is live!
410891bc56edSDimitry Andric   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
410991bc56edSDimitry Andric     return true;
411091bc56edSDimitry Andric 
411191bc56edSDimitry Andric   // All values other than instructions and arguments (e.g. constants) are live.
411291bc56edSDimitry Andric   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
411391bc56edSDimitry Andric 
411491bc56edSDimitry Andric   // If Val is a constant sized alloca in the entry block, it is live, this is
411591bc56edSDimitry Andric   // true because it is just a reference to the stack/frame pointer, which is
411691bc56edSDimitry Andric   // live for the whole function.
411791bc56edSDimitry Andric   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
411891bc56edSDimitry Andric     if (AI->isStaticAlloca())
411991bc56edSDimitry Andric       return true;
412091bc56edSDimitry Andric 
412191bc56edSDimitry Andric   // Check to see if this value is already used in the memory instruction's
412291bc56edSDimitry Andric   // block.  If so, it's already live into the block at the very least, so we
412391bc56edSDimitry Andric   // can reasonably fold it.
412491bc56edSDimitry Andric   return Val->isUsedInBasicBlock(MemoryInst->getParent());
412591bc56edSDimitry Andric }
412691bc56edSDimitry Andric 
41277d523365SDimitry Andric /// It is possible for the addressing mode of the machine to fold the specified
41287d523365SDimitry Andric /// instruction into a load or store that ultimately uses it.
41297d523365SDimitry Andric /// However, the specified instruction has multiple uses.
41307d523365SDimitry Andric /// Given this, it may actually increase register pressure to fold it
413191bc56edSDimitry Andric /// into the load. For example, consider this code:
413291bc56edSDimitry Andric ///
413391bc56edSDimitry Andric ///     X = ...
413491bc56edSDimitry Andric ///     Y = X+1
413591bc56edSDimitry Andric ///     use(Y)   -> nonload/store
413691bc56edSDimitry Andric ///     Z = Y+1
413791bc56edSDimitry Andric ///     load Z
413891bc56edSDimitry Andric ///
413991bc56edSDimitry Andric /// In this case, Y has multiple uses, and can be folded into the load of Z
414091bc56edSDimitry Andric /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
414191bc56edSDimitry Andric /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
414291bc56edSDimitry Andric /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
414391bc56edSDimitry Andric /// number of computations either.
414491bc56edSDimitry Andric ///
414591bc56edSDimitry Andric /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
414691bc56edSDimitry Andric /// X was live across 'load Z' for other reasons, we actually *would* want to
414791bc56edSDimitry Andric /// fold the addressing mode in the Z case.  This would make Y die earlier.
414891bc56edSDimitry Andric bool AddressingModeMatcher::
41497d523365SDimitry Andric isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
415091bc56edSDimitry Andric                                      ExtAddrMode &AMAfter) {
415191bc56edSDimitry Andric   if (IgnoreProfitability) return true;
415291bc56edSDimitry Andric 
415391bc56edSDimitry Andric   // AMBefore is the addressing mode before this instruction was folded into it,
415491bc56edSDimitry Andric   // and AMAfter is the addressing mode after the instruction was folded.  Get
415591bc56edSDimitry Andric   // the set of registers referenced by AMAfter and subtract out those
415691bc56edSDimitry Andric   // referenced by AMBefore: this is the set of values which folding in this
415791bc56edSDimitry Andric   // address extends the lifetime of.
415891bc56edSDimitry Andric   //
415991bc56edSDimitry Andric   // Note that there are only two potential values being referenced here,
416091bc56edSDimitry Andric   // BaseReg and ScaleReg (global addresses are always available, as are any
416191bc56edSDimitry Andric   // folded immediates).
416291bc56edSDimitry Andric   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
416391bc56edSDimitry Andric 
416491bc56edSDimitry Andric   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
416591bc56edSDimitry Andric   // lifetime wasn't extended by adding this instruction.
41667d523365SDimitry Andric   if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
416791bc56edSDimitry Andric     BaseReg = nullptr;
41687d523365SDimitry Andric   if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
416991bc56edSDimitry Andric     ScaledReg = nullptr;
417091bc56edSDimitry Andric 
417191bc56edSDimitry Andric   // If folding this instruction (and it's subexprs) didn't extend any live
417291bc56edSDimitry Andric   // ranges, we're ok with it.
417391bc56edSDimitry Andric   if (!BaseReg && !ScaledReg)
417491bc56edSDimitry Andric     return true;
417591bc56edSDimitry Andric 
41763ca95b02SDimitry Andric   // If all uses of this instruction can have the address mode sunk into them,
41773ca95b02SDimitry Andric   // we can remove the addressing mode and effectively trade one live register
41783ca95b02SDimitry Andric   // for another (at worst.)  In this context, folding an addressing mode into
41793ca95b02SDimitry Andric   // the use is just a particularly nice way of sinking it.
418091bc56edSDimitry Andric   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
418191bc56edSDimitry Andric   SmallPtrSet<Instruction*, 16> ConsideredInsts;
41827a7e6055SDimitry Andric   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
418391bc56edSDimitry Andric     return false;  // Has a non-memory, non-foldable use!
418491bc56edSDimitry Andric 
418591bc56edSDimitry Andric   // Now that we know that all uses of this instruction are part of a chain of
418691bc56edSDimitry Andric   // computation involving only operations that could theoretically be folded
41873ca95b02SDimitry Andric   // into a memory use, loop over each of these memory operation uses and see
41883ca95b02SDimitry Andric   // if they could  *actually* fold the instruction.  The assumption is that
41893ca95b02SDimitry Andric   // addressing modes are cheap and that duplicating the computation involved
41903ca95b02SDimitry Andric   // many times is worthwhile, even on a fastpath. For sinking candidates
41913ca95b02SDimitry Andric   // (i.e. cold call sites), this serves as a way to prevent excessive code
41923ca95b02SDimitry Andric   // growth since most architectures have some reasonable small and fast way to
41933ca95b02SDimitry Andric   // compute an effective address.  (i.e LEA on x86)
419491bc56edSDimitry Andric   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
419591bc56edSDimitry Andric   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
419691bc56edSDimitry Andric     Instruction *User = MemoryUses[i].first;
419791bc56edSDimitry Andric     unsigned OpNo = MemoryUses[i].second;
419891bc56edSDimitry Andric 
419991bc56edSDimitry Andric     // Get the access type of this use.  If the use isn't a pointer, we don't
420091bc56edSDimitry Andric     // know what it accesses.
420191bc56edSDimitry Andric     Value *Address = User->getOperand(OpNo);
420297bc6c73SDimitry Andric     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
420397bc6c73SDimitry Andric     if (!AddrTy)
420491bc56edSDimitry Andric       return false;
420597bc6c73SDimitry Andric     Type *AddressAccessTy = AddrTy->getElementType();
420697bc6c73SDimitry Andric     unsigned AS = AddrTy->getAddressSpace();
420791bc56edSDimitry Andric 
420891bc56edSDimitry Andric     // Do a match against the root of this address, ignoring profitability. This
420991bc56edSDimitry Andric     // will tell us if the addressing mode for the memory operation will
421091bc56edSDimitry Andric     // *actually* cover the shared instruction.
421191bc56edSDimitry Andric     ExtAddrMode Result;
421291bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
421391bc56edSDimitry Andric         TPT.getRestorationPoint();
42147a7e6055SDimitry Andric     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
42157a7e6055SDimitry Andric                                   AddressAccessTy, AS,
42168f0fd8f6SDimitry Andric                                   MemoryInst, Result, InsertedInsts,
421791bc56edSDimitry Andric                                   PromotedInsts, TPT);
421891bc56edSDimitry Andric     Matcher.IgnoreProfitability = true;
42197d523365SDimitry Andric     bool Success = Matcher.matchAddr(Address, 0);
422091bc56edSDimitry Andric     (void)Success; assert(Success && "Couldn't select *anything*?");
422191bc56edSDimitry Andric 
422291bc56edSDimitry Andric     // The match was to check the profitability, the changes made are not
422391bc56edSDimitry Andric     // part of the original matcher. Therefore, they should be dropped
422491bc56edSDimitry Andric     // otherwise the original matcher will not present the right state.
422591bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
422691bc56edSDimitry Andric 
422791bc56edSDimitry Andric     // If the match didn't cover I, then it won't be shared by it.
4228d88c1a5aSDimitry Andric     if (!is_contained(MatchedAddrModeInsts, I))
422991bc56edSDimitry Andric       return false;
423091bc56edSDimitry Andric 
423191bc56edSDimitry Andric     MatchedAddrModeInsts.clear();
423291bc56edSDimitry Andric   }
423391bc56edSDimitry Andric 
423491bc56edSDimitry Andric   return true;
423591bc56edSDimitry Andric }
423691bc56edSDimitry Andric 
423791bc56edSDimitry Andric } // end anonymous namespace
423891bc56edSDimitry Andric 
42397d523365SDimitry Andric /// Return true if the specified values are defined in a
424091bc56edSDimitry Andric /// different basic block than BB.
424191bc56edSDimitry Andric static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
424291bc56edSDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(V))
424391bc56edSDimitry Andric     return I->getParent() != BB;
424491bc56edSDimitry Andric   return false;
424591bc56edSDimitry Andric }
424691bc56edSDimitry Andric 
42473ca95b02SDimitry Andric /// Sink addressing mode computation immediate before MemoryInst if doing so
42483ca95b02SDimitry Andric /// can be done without increasing register pressure.  The need for the
42493ca95b02SDimitry Andric /// register pressure constraint means this can end up being an all or nothing
42503ca95b02SDimitry Andric /// decision for all uses of the same addressing computation.
42513ca95b02SDimitry Andric ///
42527d523365SDimitry Andric /// Load and Store Instructions often have addressing modes that can do
42537d523365SDimitry Andric /// significant amounts of computation. As such, instruction selection will try
42547d523365SDimitry Andric /// to get the load or store to do as much computation as possible for the
42557d523365SDimitry Andric /// program. The problem is that isel can only see within a single block. As
42567d523365SDimitry Andric /// such, we sink as much legal addressing mode work into the block as possible.
425791bc56edSDimitry Andric ///
425891bc56edSDimitry Andric /// This method is used to optimize both load/store and inline asms with memory
42593ca95b02SDimitry Andric /// operands.  It's also used to sink addressing computations feeding into cold
42603ca95b02SDimitry Andric /// call sites into their (cold) basic block.
42613ca95b02SDimitry Andric ///
42623ca95b02SDimitry Andric /// The motivation for handling sinking into cold blocks is that doing so can
42633ca95b02SDimitry Andric /// both enable other address mode sinking (by satisfying the register pressure
42643ca95b02SDimitry Andric /// constraint above), and reduce register pressure globally (by removing the
42653ca95b02SDimitry Andric /// addressing mode computation from the fast path entirely.).
42667d523365SDimitry Andric bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
426797bc6c73SDimitry Andric                                         Type *AccessTy, unsigned AddrSpace) {
426891bc56edSDimitry Andric   Value *Repl = Addr;
426991bc56edSDimitry Andric 
427091bc56edSDimitry Andric   // Try to collapse single-value PHI nodes.  This is necessary to undo
427191bc56edSDimitry Andric   // unprofitable PRE transformations.
427291bc56edSDimitry Andric   SmallVector<Value*, 8> worklist;
427391bc56edSDimitry Andric   SmallPtrSet<Value*, 16> Visited;
427491bc56edSDimitry Andric   worklist.push_back(Addr);
427591bc56edSDimitry Andric 
427691bc56edSDimitry Andric   // Use a worklist to iteratively look through PHI nodes, and ensure that
427791bc56edSDimitry Andric   // the addressing mode obtained from the non-PHI roots of the graph
427891bc56edSDimitry Andric   // are equivalent.
4279b40b48b8SDimitry Andric   bool AddrModeFound = false;
4280c4394386SDimitry Andric   bool PhiSeen = false;
428191bc56edSDimitry Andric   SmallVector<Instruction*, 16> AddrModeInsts;
428291bc56edSDimitry Andric   ExtAddrMode AddrMode;
42837a7e6055SDimitry Andric   TypePromotionTransaction TPT(RemovedInsts);
428491bc56edSDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
428591bc56edSDimitry Andric       TPT.getRestorationPoint();
428691bc56edSDimitry Andric   while (!worklist.empty()) {
428791bc56edSDimitry Andric     Value *V = worklist.back();
428891bc56edSDimitry Andric     worklist.pop_back();
428991bc56edSDimitry Andric 
4290b40b48b8SDimitry Andric     // We allow traversing cyclic Phi nodes.
4291b40b48b8SDimitry Andric     // In case of success after this loop we ensure that traversing through
4292b40b48b8SDimitry Andric     // Phi nodes ends up with all cases to compute address of the form
4293b40b48b8SDimitry Andric     //    BaseGV + Base + Scale * Index + Offset
4294b40b48b8SDimitry Andric     // where Scale and Offset are constans and BaseGV, Base and Index
4295b40b48b8SDimitry Andric     // are exactly the same Values in all cases.
4296b40b48b8SDimitry Andric     // It means that BaseGV, Scale and Offset dominate our memory instruction
4297b40b48b8SDimitry Andric     // and have the same value as they had in address computation represented
4298b40b48b8SDimitry Andric     // as Phi. So we can safely sink address computation to memory instruction.
4299b40b48b8SDimitry Andric     if (!Visited.insert(V).second)
4300b40b48b8SDimitry Andric       continue;
430191bc56edSDimitry Andric 
430291bc56edSDimitry Andric     // For a PHI node, push all of its incoming values.
430391bc56edSDimitry Andric     if (PHINode *P = dyn_cast<PHINode>(V)) {
4304ff0cc061SDimitry Andric       for (Value *IncValue : P->incoming_values())
4305ff0cc061SDimitry Andric         worklist.push_back(IncValue);
4306c4394386SDimitry Andric       PhiSeen = true;
430791bc56edSDimitry Andric       continue;
430891bc56edSDimitry Andric     }
430991bc56edSDimitry Andric 
43103ca95b02SDimitry Andric     // For non-PHIs, determine the addressing mode being computed.  Note that
43113ca95b02SDimitry Andric     // the result may differ depending on what other uses our candidate
43123ca95b02SDimitry Andric     // addressing instructions might have.
4313b40b48b8SDimitry Andric     AddrModeInsts.clear();
431491bc56edSDimitry Andric     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4315b40b48b8SDimitry Andric         V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
43168f0fd8f6SDimitry Andric         InsertedInsts, PromotedInsts, TPT);
431791bc56edSDimitry Andric 
4318b40b48b8SDimitry Andric     if (!AddrModeFound) {
4319b40b48b8SDimitry Andric       AddrModeFound = true;
432091bc56edSDimitry Andric       AddrMode = NewAddrMode;
432191bc56edSDimitry Andric       continue;
432291bc56edSDimitry Andric     }
4323b40b48b8SDimitry Andric     if (NewAddrMode == AddrMode)
4324b40b48b8SDimitry Andric       continue;
432591bc56edSDimitry Andric 
4326b40b48b8SDimitry Andric     AddrModeFound = false;
432791bc56edSDimitry Andric     break;
432891bc56edSDimitry Andric   }
432991bc56edSDimitry Andric 
433091bc56edSDimitry Andric   // If the addressing mode couldn't be determined, or if multiple different
433191bc56edSDimitry Andric   // ones were determined, bail out now.
4332b40b48b8SDimitry Andric   if (!AddrModeFound) {
433391bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
433491bc56edSDimitry Andric     return false;
433591bc56edSDimitry Andric   }
433691bc56edSDimitry Andric   TPT.commit();
433791bc56edSDimitry Andric 
433891bc56edSDimitry Andric   // If all the instructions matched are already in this BB, don't do anything.
4339c4394386SDimitry Andric   // If we saw Phi node then it is not local definitely.
4340c4394386SDimitry Andric   if (!PhiSeen && none_of(AddrModeInsts, [&](Value *V) {
4341d88c1a5aSDimitry Andric         return IsNonLocalValue(V, MemoryInst->getParent());
4342d88c1a5aSDimitry Andric                   })) {
434391bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
434491bc56edSDimitry Andric     return false;
434591bc56edSDimitry Andric   }
434691bc56edSDimitry Andric 
434791bc56edSDimitry Andric   // Insert this computation right after this user.  Since our caller is
434891bc56edSDimitry Andric   // scanning from the top of the BB to the bottom, reuse of the expr are
434991bc56edSDimitry Andric   // guaranteed to happen later.
435091bc56edSDimitry Andric   IRBuilder<> Builder(MemoryInst);
435191bc56edSDimitry Andric 
435291bc56edSDimitry Andric   // Now that we determined the addressing expression we want to use and know
435391bc56edSDimitry Andric   // that we have to sink it into this block.  Check to see if we have already
435491bc56edSDimitry Andric   // done this for some other load/store instr in this block.  If so, reuse the
435591bc56edSDimitry Andric   // computation.
435691bc56edSDimitry Andric   Value *&SunkAddr = SunkAddrs[Addr];
435791bc56edSDimitry Andric   if (SunkAddr) {
435891bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
435991bc56edSDimitry Andric                  << *MemoryInst << "\n");
436091bc56edSDimitry Andric     if (SunkAddr->getType() != Addr->getType())
43617a7e6055SDimitry Andric       SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4362ff0cc061SDimitry Andric   } else if (AddrSinkUsingGEPs ||
4363ff0cc061SDimitry Andric              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
43647a7e6055SDimitry Andric               SubtargetInfo->useAA())) {
436591bc56edSDimitry Andric     // By default, we use the GEP-based method when AA is used later. This
436691bc56edSDimitry Andric     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
436791bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
436891bc56edSDimitry Andric                  << *MemoryInst << "\n");
4369875ed548SDimitry Andric     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
437091bc56edSDimitry Andric     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
437191bc56edSDimitry Andric 
437291bc56edSDimitry Andric     // First, find the pointer.
437391bc56edSDimitry Andric     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
437491bc56edSDimitry Andric       ResultPtr = AddrMode.BaseReg;
437591bc56edSDimitry Andric       AddrMode.BaseReg = nullptr;
437691bc56edSDimitry Andric     }
437791bc56edSDimitry Andric 
437891bc56edSDimitry Andric     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
437991bc56edSDimitry Andric       // We can't add more than one pointer together, nor can we scale a
438091bc56edSDimitry Andric       // pointer (both of which seem meaningless).
438191bc56edSDimitry Andric       if (ResultPtr || AddrMode.Scale != 1)
438291bc56edSDimitry Andric         return false;
438391bc56edSDimitry Andric 
438491bc56edSDimitry Andric       ResultPtr = AddrMode.ScaledReg;
438591bc56edSDimitry Andric       AddrMode.Scale = 0;
438691bc56edSDimitry Andric     }
438791bc56edSDimitry Andric 
4388c4394386SDimitry Andric     // It is only safe to sign extend the BaseReg if we know that the math
4389c4394386SDimitry Andric     // required to create it did not overflow before we extend it. Since
4390c4394386SDimitry Andric     // the original IR value was tossed in favor of a constant back when
4391c4394386SDimitry Andric     // the AddrMode was created we need to bail out gracefully if widths
4392c4394386SDimitry Andric     // do not match instead of extending it.
4393c4394386SDimitry Andric     //
4394c4394386SDimitry Andric     // (See below for code to add the scale.)
4395c4394386SDimitry Andric     if (AddrMode.Scale) {
4396c4394386SDimitry Andric       Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4397c4394386SDimitry Andric       if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4398c4394386SDimitry Andric           cast<IntegerType>(ScaledRegTy)->getBitWidth())
4399c4394386SDimitry Andric         return false;
4400c4394386SDimitry Andric     }
4401c4394386SDimitry Andric 
440291bc56edSDimitry Andric     if (AddrMode.BaseGV) {
440391bc56edSDimitry Andric       if (ResultPtr)
440491bc56edSDimitry Andric         return false;
440591bc56edSDimitry Andric 
440691bc56edSDimitry Andric       ResultPtr = AddrMode.BaseGV;
440791bc56edSDimitry Andric     }
440891bc56edSDimitry Andric 
440991bc56edSDimitry Andric     // If the real base value actually came from an inttoptr, then the matcher
441091bc56edSDimitry Andric     // will look through it and provide only the integer value. In that case,
441191bc56edSDimitry Andric     // use it here.
4412a580b014SDimitry Andric     if (!DL->isNonIntegralPointerType(Addr->getType())) {
441391bc56edSDimitry Andric       if (!ResultPtr && AddrMode.BaseReg) {
4414a580b014SDimitry Andric         ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4415a580b014SDimitry Andric                                            "sunkaddr");
441691bc56edSDimitry Andric         AddrMode.BaseReg = nullptr;
441791bc56edSDimitry Andric       } else if (!ResultPtr && AddrMode.Scale == 1) {
4418a580b014SDimitry Andric         ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4419a580b014SDimitry Andric                                            "sunkaddr");
442091bc56edSDimitry Andric         AddrMode.Scale = 0;
442191bc56edSDimitry Andric       }
4422a580b014SDimitry Andric     }
442391bc56edSDimitry Andric 
442491bc56edSDimitry Andric     if (!ResultPtr &&
442591bc56edSDimitry Andric         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
442691bc56edSDimitry Andric       SunkAddr = Constant::getNullValue(Addr->getType());
442791bc56edSDimitry Andric     } else if (!ResultPtr) {
442891bc56edSDimitry Andric       return false;
442991bc56edSDimitry Andric     } else {
443091bc56edSDimitry Andric       Type *I8PtrTy =
443191bc56edSDimitry Andric           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4432ff0cc061SDimitry Andric       Type *I8Ty = Builder.getInt8Ty();
443391bc56edSDimitry Andric 
443491bc56edSDimitry Andric       // Start with the base register. Do this first so that subsequent address
443591bc56edSDimitry Andric       // matching finds it last, which will prevent it from trying to match it
443691bc56edSDimitry Andric       // as the scaled value in case it happens to be a mul. That would be
443791bc56edSDimitry Andric       // problematic if we've sunk a different mul for the scale, because then
443891bc56edSDimitry Andric       // we'd end up sinking both muls.
443991bc56edSDimitry Andric       if (AddrMode.BaseReg) {
444091bc56edSDimitry Andric         Value *V = AddrMode.BaseReg;
444191bc56edSDimitry Andric         if (V->getType() != IntPtrTy)
444291bc56edSDimitry Andric           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
444391bc56edSDimitry Andric 
444491bc56edSDimitry Andric         ResultIndex = V;
444591bc56edSDimitry Andric       }
444691bc56edSDimitry Andric 
444791bc56edSDimitry Andric       // Add the scale value.
444891bc56edSDimitry Andric       if (AddrMode.Scale) {
444991bc56edSDimitry Andric         Value *V = AddrMode.ScaledReg;
445091bc56edSDimitry Andric         if (V->getType() == IntPtrTy) {
445191bc56edSDimitry Andric           // done.
445291bc56edSDimitry Andric         } else {
4453c4394386SDimitry Andric           assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4454c4394386SDimitry Andric                  cast<IntegerType>(V->getType())->getBitWidth() &&
4455c4394386SDimitry Andric                  "We can't transform if ScaledReg is too narrow");
4456c4394386SDimitry Andric           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
445791bc56edSDimitry Andric         }
445891bc56edSDimitry Andric 
445991bc56edSDimitry Andric         if (AddrMode.Scale != 1)
446091bc56edSDimitry Andric           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
446191bc56edSDimitry Andric                                 "sunkaddr");
446291bc56edSDimitry Andric         if (ResultIndex)
446391bc56edSDimitry Andric           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
446491bc56edSDimitry Andric         else
446591bc56edSDimitry Andric           ResultIndex = V;
446691bc56edSDimitry Andric       }
446791bc56edSDimitry Andric 
446891bc56edSDimitry Andric       // Add in the Base Offset if present.
446991bc56edSDimitry Andric       if (AddrMode.BaseOffs) {
447091bc56edSDimitry Andric         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
447191bc56edSDimitry Andric         if (ResultIndex) {
447291bc56edSDimitry Andric           // We need to add this separately from the scale above to help with
447391bc56edSDimitry Andric           // SDAG consecutive load/store merging.
447491bc56edSDimitry Andric           if (ResultPtr->getType() != I8PtrTy)
44757a7e6055SDimitry Andric             ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4476ff0cc061SDimitry Andric           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
447791bc56edSDimitry Andric         }
447891bc56edSDimitry Andric 
447991bc56edSDimitry Andric         ResultIndex = V;
448091bc56edSDimitry Andric       }
448191bc56edSDimitry Andric 
448291bc56edSDimitry Andric       if (!ResultIndex) {
448391bc56edSDimitry Andric         SunkAddr = ResultPtr;
448491bc56edSDimitry Andric       } else {
448591bc56edSDimitry Andric         if (ResultPtr->getType() != I8PtrTy)
44867a7e6055SDimitry Andric           ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4487ff0cc061SDimitry Andric         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
448891bc56edSDimitry Andric       }
448991bc56edSDimitry Andric 
449091bc56edSDimitry Andric       if (SunkAddr->getType() != Addr->getType())
44917a7e6055SDimitry Andric         SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
449291bc56edSDimitry Andric     }
449391bc56edSDimitry Andric   } else {
4494a580b014SDimitry Andric     // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4495a580b014SDimitry Andric     // non-integral pointers, so in that case bail out now.
4496a580b014SDimitry Andric     Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4497a580b014SDimitry Andric     Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4498a580b014SDimitry Andric     PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4499a580b014SDimitry Andric     PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4500a580b014SDimitry Andric     if (DL->isNonIntegralPointerType(Addr->getType()) ||
4501a580b014SDimitry Andric         (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4502a580b014SDimitry Andric         (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4503a580b014SDimitry Andric         (AddrMode.BaseGV &&
4504a580b014SDimitry Andric          DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4505a580b014SDimitry Andric       return false;
4506a580b014SDimitry Andric 
450791bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
450891bc56edSDimitry Andric                  << *MemoryInst << "\n");
4509875ed548SDimitry Andric     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
451091bc56edSDimitry Andric     Value *Result = nullptr;
451191bc56edSDimitry Andric 
451291bc56edSDimitry Andric     // Start with the base register. Do this first so that subsequent address
451391bc56edSDimitry Andric     // matching finds it last, which will prevent it from trying to match it
451491bc56edSDimitry Andric     // as the scaled value in case it happens to be a mul. That would be
451591bc56edSDimitry Andric     // problematic if we've sunk a different mul for the scale, because then
451691bc56edSDimitry Andric     // we'd end up sinking both muls.
451791bc56edSDimitry Andric     if (AddrMode.BaseReg) {
451891bc56edSDimitry Andric       Value *V = AddrMode.BaseReg;
451991bc56edSDimitry Andric       if (V->getType()->isPointerTy())
452091bc56edSDimitry Andric         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
452191bc56edSDimitry Andric       if (V->getType() != IntPtrTy)
452291bc56edSDimitry Andric         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
452391bc56edSDimitry Andric       Result = V;
452491bc56edSDimitry Andric     }
452591bc56edSDimitry Andric 
452691bc56edSDimitry Andric     // Add the scale value.
452791bc56edSDimitry Andric     if (AddrMode.Scale) {
452891bc56edSDimitry Andric       Value *V = AddrMode.ScaledReg;
452991bc56edSDimitry Andric       if (V->getType() == IntPtrTy) {
453091bc56edSDimitry Andric         // done.
453191bc56edSDimitry Andric       } else if (V->getType()->isPointerTy()) {
453291bc56edSDimitry Andric         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
453391bc56edSDimitry Andric       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
453491bc56edSDimitry Andric                  cast<IntegerType>(V->getType())->getBitWidth()) {
453591bc56edSDimitry Andric         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
453691bc56edSDimitry Andric       } else {
453791bc56edSDimitry Andric         // It is only safe to sign extend the BaseReg if we know that the math
453891bc56edSDimitry Andric         // required to create it did not overflow before we extend it. Since
453991bc56edSDimitry Andric         // the original IR value was tossed in favor of a constant back when
454091bc56edSDimitry Andric         // the AddrMode was created we need to bail out gracefully if widths
454191bc56edSDimitry Andric         // do not match instead of extending it.
454291bc56edSDimitry Andric         Instruction *I = dyn_cast_or_null<Instruction>(Result);
454391bc56edSDimitry Andric         if (I && (Result != AddrMode.BaseReg))
454491bc56edSDimitry Andric           I->eraseFromParent();
454591bc56edSDimitry Andric         return false;
454691bc56edSDimitry Andric       }
454791bc56edSDimitry Andric       if (AddrMode.Scale != 1)
454891bc56edSDimitry Andric         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
454991bc56edSDimitry Andric                               "sunkaddr");
455091bc56edSDimitry Andric       if (Result)
455191bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
455291bc56edSDimitry Andric       else
455391bc56edSDimitry Andric         Result = V;
455491bc56edSDimitry Andric     }
455591bc56edSDimitry Andric 
455691bc56edSDimitry Andric     // Add in the BaseGV if present.
455791bc56edSDimitry Andric     if (AddrMode.BaseGV) {
455891bc56edSDimitry Andric       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
455991bc56edSDimitry Andric       if (Result)
456091bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
456191bc56edSDimitry Andric       else
456291bc56edSDimitry Andric         Result = V;
456391bc56edSDimitry Andric     }
456491bc56edSDimitry Andric 
456591bc56edSDimitry Andric     // Add in the Base Offset if present.
456691bc56edSDimitry Andric     if (AddrMode.BaseOffs) {
456791bc56edSDimitry Andric       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
456891bc56edSDimitry Andric       if (Result)
456991bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
457091bc56edSDimitry Andric       else
457191bc56edSDimitry Andric         Result = V;
457291bc56edSDimitry Andric     }
457391bc56edSDimitry Andric 
457491bc56edSDimitry Andric     if (!Result)
457591bc56edSDimitry Andric       SunkAddr = Constant::getNullValue(Addr->getType());
457691bc56edSDimitry Andric     else
457791bc56edSDimitry Andric       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
457891bc56edSDimitry Andric   }
457991bc56edSDimitry Andric 
458091bc56edSDimitry Andric   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
458191bc56edSDimitry Andric 
458291bc56edSDimitry Andric   // If we have no uses, recursively delete the value and all dead instructions
458391bc56edSDimitry Andric   // using it.
458491bc56edSDimitry Andric   if (Repl->use_empty()) {
458591bc56edSDimitry Andric     // This can cause recursive deletion, which can invalidate our iterator.
4586f37b6182SDimitry Andric     // Use a WeakTrackingVH to hold onto it in case this happens.
45873ca95b02SDimitry Andric     Value *CurValue = &*CurInstIterator;
4588f37b6182SDimitry Andric     WeakTrackingVH IterHandle(CurValue);
458991bc56edSDimitry Andric     BasicBlock *BB = CurInstIterator->getParent();
459091bc56edSDimitry Andric 
459191bc56edSDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
459291bc56edSDimitry Andric 
45933ca95b02SDimitry Andric     if (IterHandle != CurValue) {
459491bc56edSDimitry Andric       // If the iterator instruction was recursively deleted, start over at the
459591bc56edSDimitry Andric       // start of the block.
459691bc56edSDimitry Andric       CurInstIterator = BB->begin();
459791bc56edSDimitry Andric       SunkAddrs.clear();
459891bc56edSDimitry Andric     }
459991bc56edSDimitry Andric   }
460091bc56edSDimitry Andric   ++NumMemoryInsts;
460191bc56edSDimitry Andric   return true;
460291bc56edSDimitry Andric }
460391bc56edSDimitry Andric 
46047d523365SDimitry Andric /// If there are any memory operands, use OptimizeMemoryInst to sink their
46057d523365SDimitry Andric /// address computing into the block when possible / profitable.
46067d523365SDimitry Andric bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
460791bc56edSDimitry Andric   bool MadeChange = false;
460891bc56edSDimitry Andric 
4609ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI =
4610db17bf38SDimitry Andric       TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
4611875ed548SDimitry Andric   TargetLowering::AsmOperandInfoVector TargetConstraints =
4612875ed548SDimitry Andric       TLI->ParseConstraints(*DL, TRI, CS);
461391bc56edSDimitry Andric   unsigned ArgNo = 0;
461491bc56edSDimitry Andric   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
461591bc56edSDimitry Andric     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
461691bc56edSDimitry Andric 
461791bc56edSDimitry Andric     // Compute the constraint code and ConstraintType to use.
461891bc56edSDimitry Andric     TLI->ComputeConstraintToUse(OpInfo, SDValue());
461991bc56edSDimitry Andric 
462091bc56edSDimitry Andric     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
462191bc56edSDimitry Andric         OpInfo.isIndirect) {
462291bc56edSDimitry Andric       Value *OpVal = CS->getArgOperand(ArgNo++);
46237d523365SDimitry Andric       MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
462491bc56edSDimitry Andric     } else if (OpInfo.Type == InlineAsm::isInput)
462591bc56edSDimitry Andric       ArgNo++;
462691bc56edSDimitry Andric   }
462791bc56edSDimitry Andric 
462891bc56edSDimitry Andric   return MadeChange;
462991bc56edSDimitry Andric }
463091bc56edSDimitry Andric 
46317a7e6055SDimitry Andric /// \brief Check if all the uses of \p Val are equivalent (or free) zero or
463239d628a0SDimitry Andric /// sign extensions.
46337a7e6055SDimitry Andric static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
46347a7e6055SDimitry Andric   assert(!Val->use_empty() && "Input must have at least one use");
46357a7e6055SDimitry Andric   const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
463639d628a0SDimitry Andric   bool IsSExt = isa<SExtInst>(FirstUser);
463739d628a0SDimitry Andric   Type *ExtTy = FirstUser->getType();
46387a7e6055SDimitry Andric   for (const User *U : Val->users()) {
463939d628a0SDimitry Andric     const Instruction *UI = cast<Instruction>(U);
464039d628a0SDimitry Andric     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
464139d628a0SDimitry Andric       return false;
464239d628a0SDimitry Andric     Type *CurTy = UI->getType();
464339d628a0SDimitry Andric     // Same input and output types: Same instruction after CSE.
464439d628a0SDimitry Andric     if (CurTy == ExtTy)
464539d628a0SDimitry Andric       continue;
464639d628a0SDimitry Andric 
464739d628a0SDimitry Andric     // If IsSExt is true, we are in this situation:
46487a7e6055SDimitry Andric     // a = Val
464939d628a0SDimitry Andric     // b = sext ty1 a to ty2
465039d628a0SDimitry Andric     // c = sext ty1 a to ty3
465139d628a0SDimitry Andric     // Assuming ty2 is shorter than ty3, this could be turned into:
46527a7e6055SDimitry Andric     // a = Val
465339d628a0SDimitry Andric     // b = sext ty1 a to ty2
465439d628a0SDimitry Andric     // c = sext ty2 b to ty3
465539d628a0SDimitry Andric     // However, the last sext is not free.
465639d628a0SDimitry Andric     if (IsSExt)
465739d628a0SDimitry Andric       return false;
465839d628a0SDimitry Andric 
465939d628a0SDimitry Andric     // This is a ZExt, maybe this is free to extend from one type to another.
466039d628a0SDimitry Andric     // In that case, we would not account for a different use.
466139d628a0SDimitry Andric     Type *NarrowTy;
466239d628a0SDimitry Andric     Type *LargeTy;
466339d628a0SDimitry Andric     if (ExtTy->getScalarType()->getIntegerBitWidth() >
466439d628a0SDimitry Andric         CurTy->getScalarType()->getIntegerBitWidth()) {
466539d628a0SDimitry Andric       NarrowTy = CurTy;
466639d628a0SDimitry Andric       LargeTy = ExtTy;
466739d628a0SDimitry Andric     } else {
466839d628a0SDimitry Andric       NarrowTy = ExtTy;
466939d628a0SDimitry Andric       LargeTy = CurTy;
467039d628a0SDimitry Andric     }
467139d628a0SDimitry Andric 
467239d628a0SDimitry Andric     if (!TLI.isZExtFree(NarrowTy, LargeTy))
467339d628a0SDimitry Andric       return false;
467439d628a0SDimitry Andric   }
467539d628a0SDimitry Andric   // All uses are the same or can be derived from one another for free.
467639d628a0SDimitry Andric   return true;
467739d628a0SDimitry Andric }
467839d628a0SDimitry Andric 
46797a7e6055SDimitry Andric /// \brief Try to speculatively promote extensions in \p Exts and continue
46807a7e6055SDimitry Andric /// promoting through newly promoted operands recursively as far as doing so is
46817a7e6055SDimitry Andric /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
46827a7e6055SDimitry Andric /// When some promotion happened, \p TPT contains the proper state to revert
46837a7e6055SDimitry Andric /// them.
468439d628a0SDimitry Andric ///
46857a7e6055SDimitry Andric /// \return true if some promotion happened, false otherwise.
46867a7e6055SDimitry Andric bool CodeGenPrepare::tryToPromoteExts(
46877a7e6055SDimitry Andric     TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
46887a7e6055SDimitry Andric     SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
46897a7e6055SDimitry Andric     unsigned CreatedInstsCost) {
46907a7e6055SDimitry Andric   bool Promoted = false;
46917a7e6055SDimitry Andric 
46927a7e6055SDimitry Andric   // Iterate over all the extensions to try to promote them.
469339d628a0SDimitry Andric   for (auto I : Exts) {
46947a7e6055SDimitry Andric     // Early check if we directly have ext(load).
46957a7e6055SDimitry Andric     if (isa<LoadInst>(I->getOperand(0))) {
46967a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
46977a7e6055SDimitry Andric       continue;
469839d628a0SDimitry Andric     }
46997a7e6055SDimitry Andric 
47007a7e6055SDimitry Andric     // Check whether or not we want to do any promotion.  The reason we have
47017a7e6055SDimitry Andric     // this check inside the for loop is to catch the case where an extension
47027a7e6055SDimitry Andric     // is directly fed by a load because in such case the extension can be moved
47037a7e6055SDimitry Andric     // up without any promotion on its operands.
470439d628a0SDimitry Andric     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
47057a7e6055SDimitry Andric       return false;
47067a7e6055SDimitry Andric 
470739d628a0SDimitry Andric     // Get the action to perform the promotion.
47087a7e6055SDimitry Andric     TypePromotionHelper::Action TPH =
47097a7e6055SDimitry Andric         TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
471039d628a0SDimitry Andric     // Check if we can promote.
47117a7e6055SDimitry Andric     if (!TPH) {
47127a7e6055SDimitry Andric       // Save the current extension as we cannot move up through its operand.
47137a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
471439d628a0SDimitry Andric       continue;
47157a7e6055SDimitry Andric     }
47167a7e6055SDimitry Andric 
471739d628a0SDimitry Andric     // Save the current state.
471839d628a0SDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
471939d628a0SDimitry Andric         TPT.getRestorationPoint();
472039d628a0SDimitry Andric     SmallVector<Instruction *, 4> NewExts;
4721ff0cc061SDimitry Andric     unsigned NewCreatedInstsCost = 0;
4722ff0cc061SDimitry Andric     unsigned ExtCost = !TLI->isExtFree(I);
472339d628a0SDimitry Andric     // Promote.
4724ff0cc061SDimitry Andric     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4725ff0cc061SDimitry Andric                              &NewExts, nullptr, *TLI);
472639d628a0SDimitry Andric     assert(PromotedVal &&
472739d628a0SDimitry Andric            "TypePromotionHelper should have filtered out those cases");
472839d628a0SDimitry Andric 
472939d628a0SDimitry Andric     // We would be able to merge only one extension in a load.
473039d628a0SDimitry Andric     // Therefore, if we have more than 1 new extension we heuristically
473139d628a0SDimitry Andric     // cut this search path, because it means we degrade the code quality.
473239d628a0SDimitry Andric     // With exactly 2, the transformation is neutral, because we will merge
473339d628a0SDimitry Andric     // one extension but leave one. However, we optimistically keep going,
473439d628a0SDimitry Andric     // because the new extension may be removed too.
4735ff0cc061SDimitry Andric     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
47367a7e6055SDimitry Andric     // FIXME: It would be possible to propagate a negative value instead of
47377a7e6055SDimitry Andric     // conservatively ceiling it to 0.
47387a7e6055SDimitry Andric     TotalCreatedInstsCost =
47397a7e6055SDimitry Andric         std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
474039d628a0SDimitry Andric     if (!StressExtLdPromotion &&
4741ff0cc061SDimitry Andric         (TotalCreatedInstsCost > 1 ||
4742875ed548SDimitry Andric          !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
47437a7e6055SDimitry Andric       // This promotion is not profitable, rollback to the previous state, and
47447a7e6055SDimitry Andric       // save the current extension in ProfitablyMovedExts as the latest
47457a7e6055SDimitry Andric       // speculative promotion turned out to be unprofitable.
474639d628a0SDimitry Andric       TPT.rollback(LastKnownGood);
47477a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
47487a7e6055SDimitry Andric       continue;
47497a7e6055SDimitry Andric     }
47507a7e6055SDimitry Andric     // Continue promoting NewExts as far as doing so is profitable.
47517a7e6055SDimitry Andric     SmallVector<Instruction *, 2> NewlyMovedExts;
47527a7e6055SDimitry Andric     (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
47537a7e6055SDimitry Andric     bool NewPromoted = false;
47547a7e6055SDimitry Andric     for (auto ExtInst : NewlyMovedExts) {
47557a7e6055SDimitry Andric       Instruction *MovedExt = cast<Instruction>(ExtInst);
47567a7e6055SDimitry Andric       Value *ExtOperand = MovedExt->getOperand(0);
47577a7e6055SDimitry Andric       // If we have reached to a load, we need this extra profitability check
47587a7e6055SDimitry Andric       // as it could potentially be merged into an ext(load).
47597a7e6055SDimitry Andric       if (isa<LoadInst>(ExtOperand) &&
47607a7e6055SDimitry Andric           !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
47617a7e6055SDimitry Andric             (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
47627a7e6055SDimitry Andric         continue;
47637a7e6055SDimitry Andric 
47647a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(MovedExt);
47657a7e6055SDimitry Andric       NewPromoted = true;
47667a7e6055SDimitry Andric     }
47677a7e6055SDimitry Andric 
47687a7e6055SDimitry Andric     // If none of speculative promotions for NewExts is profitable, rollback
47697a7e6055SDimitry Andric     // and save the current extension (I) as the last profitable extension.
47707a7e6055SDimitry Andric     if (!NewPromoted) {
47717a7e6055SDimitry Andric       TPT.rollback(LastKnownGood);
47727a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
477339d628a0SDimitry Andric       continue;
477439d628a0SDimitry Andric     }
477539d628a0SDimitry Andric     // The promotion is profitable.
47767a7e6055SDimitry Andric     Promoted = true;
477739d628a0SDimitry Andric   }
47787a7e6055SDimitry Andric   return Promoted;
47797a7e6055SDimitry Andric }
47807a7e6055SDimitry Andric 
47817a7e6055SDimitry Andric /// Merging redundant sexts when one is dominating the other.
47827a7e6055SDimitry Andric bool CodeGenPrepare::mergeSExts(Function &F) {
47837a7e6055SDimitry Andric   DominatorTree DT(F);
47847a7e6055SDimitry Andric   bool Changed = false;
47857a7e6055SDimitry Andric   for (auto &Entry : ValToSExtendedUses) {
47867a7e6055SDimitry Andric     SExts &Insts = Entry.second;
47877a7e6055SDimitry Andric     SExts CurPts;
47887a7e6055SDimitry Andric     for (Instruction *Inst : Insts) {
47897a7e6055SDimitry Andric       if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
47907a7e6055SDimitry Andric           Inst->getOperand(0) != Entry.first)
47917a7e6055SDimitry Andric         continue;
47927a7e6055SDimitry Andric       bool inserted = false;
47937a7e6055SDimitry Andric       for (auto &Pt : CurPts) {
47947a7e6055SDimitry Andric         if (DT.dominates(Inst, Pt)) {
47957a7e6055SDimitry Andric           Pt->replaceAllUsesWith(Inst);
47967a7e6055SDimitry Andric           RemovedInsts.insert(Pt);
47977a7e6055SDimitry Andric           Pt->removeFromParent();
47987a7e6055SDimitry Andric           Pt = Inst;
47997a7e6055SDimitry Andric           inserted = true;
48007a7e6055SDimitry Andric           Changed = true;
48017a7e6055SDimitry Andric           break;
48027a7e6055SDimitry Andric         }
48037a7e6055SDimitry Andric         if (!DT.dominates(Pt, Inst))
48047a7e6055SDimitry Andric           // Give up if we need to merge in a common dominator as the
48057a7e6055SDimitry Andric           // expermients show it is not profitable.
48067a7e6055SDimitry Andric           continue;
48077a7e6055SDimitry Andric         Inst->replaceAllUsesWith(Pt);
48087a7e6055SDimitry Andric         RemovedInsts.insert(Inst);
48097a7e6055SDimitry Andric         Inst->removeFromParent();
48107a7e6055SDimitry Andric         inserted = true;
48117a7e6055SDimitry Andric         Changed = true;
48127a7e6055SDimitry Andric         break;
48137a7e6055SDimitry Andric       }
48147a7e6055SDimitry Andric       if (!inserted)
48157a7e6055SDimitry Andric         CurPts.push_back(Inst);
48167a7e6055SDimitry Andric     }
48177a7e6055SDimitry Andric   }
48187a7e6055SDimitry Andric   return Changed;
48197a7e6055SDimitry Andric }
48207a7e6055SDimitry Andric 
48217a7e6055SDimitry Andric /// Return true, if an ext(load) can be formed from an extension in
48227a7e6055SDimitry Andric /// \p MovedExts.
48237a7e6055SDimitry Andric bool CodeGenPrepare::canFormExtLd(
48247a7e6055SDimitry Andric     const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
48257a7e6055SDimitry Andric     Instruction *&Inst, bool HasPromoted) {
48267a7e6055SDimitry Andric   for (auto *MovedExtInst : MovedExts) {
48277a7e6055SDimitry Andric     if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
48287a7e6055SDimitry Andric       LI = cast<LoadInst>(MovedExtInst->getOperand(0));
48297a7e6055SDimitry Andric       Inst = MovedExtInst;
48307a7e6055SDimitry Andric       break;
48317a7e6055SDimitry Andric     }
48327a7e6055SDimitry Andric   }
48337a7e6055SDimitry Andric   if (!LI)
483439d628a0SDimitry Andric     return false;
48357a7e6055SDimitry Andric 
48367a7e6055SDimitry Andric   // If they're already in the same block, there's nothing to do.
48377a7e6055SDimitry Andric   // Make the cheap checks first if we did not promote.
48387a7e6055SDimitry Andric   // If we promoted, we need to check if it is indeed profitable.
48397a7e6055SDimitry Andric   if (!HasPromoted && LI->getParent() == Inst->getParent())
48407a7e6055SDimitry Andric     return false;
48417a7e6055SDimitry Andric 
4842b40b48b8SDimitry Andric   return TLI->isExtLoad(LI, Inst, *DL);
484339d628a0SDimitry Andric }
484439d628a0SDimitry Andric 
48457d523365SDimitry Andric /// Move a zext or sext fed by a load into the same basic block as the load,
48467d523365SDimitry Andric /// unless conditions are unfavorable. This allows SelectionDAG to fold the
48477d523365SDimitry Andric /// extend into the load.
484891bc56edSDimitry Andric ///
48497a7e6055SDimitry Andric /// E.g.,
48507a7e6055SDimitry Andric /// \code
48517a7e6055SDimitry Andric /// %ld = load i32* %addr
48527a7e6055SDimitry Andric /// %add = add nuw i32 %ld, 4
48537a7e6055SDimitry Andric /// %zext = zext i32 %add to i64
48547a7e6055SDimitry Andric // \endcode
48557a7e6055SDimitry Andric /// =>
48567a7e6055SDimitry Andric /// \code
48577a7e6055SDimitry Andric /// %ld = load i32* %addr
48587a7e6055SDimitry Andric /// %zext = zext i32 %ld to i64
48597a7e6055SDimitry Andric /// %add = add nuw i64 %zext, 4
48607a7e6055SDimitry Andric /// \encode
48617a7e6055SDimitry Andric /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
48627a7e6055SDimitry Andric /// allow us to match zext(load i32*) to i64.
48637a7e6055SDimitry Andric ///
48647a7e6055SDimitry Andric /// Also, try to promote the computations used to obtain a sign extended
48657a7e6055SDimitry Andric /// value used into memory accesses.
48667a7e6055SDimitry Andric /// E.g.,
48677a7e6055SDimitry Andric /// \code
48687a7e6055SDimitry Andric /// a = add nsw i32 b, 3
48697a7e6055SDimitry Andric /// d = sext i32 a to i64
48707a7e6055SDimitry Andric /// e = getelementptr ..., i64 d
48717a7e6055SDimitry Andric /// \endcode
48727a7e6055SDimitry Andric /// =>
48737a7e6055SDimitry Andric /// \code
48747a7e6055SDimitry Andric /// f = sext i32 b to i64
48757a7e6055SDimitry Andric /// a = add nsw i64 f, 3
48767a7e6055SDimitry Andric /// e = getelementptr ..., i64 a
48777a7e6055SDimitry Andric /// \endcode
48787a7e6055SDimitry Andric ///
48797a7e6055SDimitry Andric /// \p Inst[in/out] the extension may be modified during the process if some
48807a7e6055SDimitry Andric /// promotions apply.
48817a7e6055SDimitry Andric bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
48827a7e6055SDimitry Andric   // ExtLoad formation and address type promotion infrastructure requires TLI to
48837a7e6055SDimitry Andric   // be effective.
4884d88c1a5aSDimitry Andric   if (!TLI)
4885d88c1a5aSDimitry Andric     return false;
4886d88c1a5aSDimitry Andric 
48877a7e6055SDimitry Andric   bool AllowPromotionWithoutCommonHeader = false;
48887a7e6055SDimitry Andric   /// See if it is an interesting sext operations for the address type
48897a7e6055SDimitry Andric   /// promotion before trying to promote it, e.g., the ones with the right
48907a7e6055SDimitry Andric   /// type and used in memory accesses.
48917a7e6055SDimitry Andric   bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
48927a7e6055SDimitry Andric       *Inst, AllowPromotionWithoutCommonHeader);
48937a7e6055SDimitry Andric   TypePromotionTransaction TPT(RemovedInsts);
489439d628a0SDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
489539d628a0SDimitry Andric       TPT.getRestorationPoint();
489639d628a0SDimitry Andric   SmallVector<Instruction *, 1> Exts;
48977a7e6055SDimitry Andric   SmallVector<Instruction *, 2> SpeculativelyMovedExts;
48987a7e6055SDimitry Andric   Exts.push_back(Inst);
48997a7e6055SDimitry Andric 
49007a7e6055SDimitry Andric   bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
49017a7e6055SDimitry Andric 
490291bc56edSDimitry Andric   // Look for a load being extended.
490339d628a0SDimitry Andric   LoadInst *LI = nullptr;
49047a7e6055SDimitry Andric   Instruction *ExtFedByLoad;
490591bc56edSDimitry Andric 
49067a7e6055SDimitry Andric   // Try to promote a chain of computation if it allows to form an extended
49077a7e6055SDimitry Andric   // load.
49087a7e6055SDimitry Andric   if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
49097a7e6055SDimitry Andric     assert(LI && ExtFedByLoad && "Expect a valid load and extension");
491039d628a0SDimitry Andric     TPT.commit();
49117a7e6055SDimitry Andric     // Move the extend into the same block as the load
49127a7e6055SDimitry Andric     ExtFedByLoad->removeFromParent();
49137a7e6055SDimitry Andric     ExtFedByLoad->insertAfter(LI);
4914d88c1a5aSDimitry Andric     // CGP does not check if the zext would be speculatively executed when moved
49157a7e6055SDimitry Andric     // to the same basic block as the load. Preserving its original location
49167a7e6055SDimitry Andric     // would pessimize the debugging experience, as well as negatively impact
49177a7e6055SDimitry Andric     // the quality of sample pgo. We don't want to use "line 0" as that has a
4918d88c1a5aSDimitry Andric     // size cost in the line-table section and logically the zext can be seen as
49197a7e6055SDimitry Andric     // part of the load. Therefore we conservatively reuse the same debug
49207a7e6055SDimitry Andric     // location for the load and the zext.
49217a7e6055SDimitry Andric     ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
492291bc56edSDimitry Andric     ++NumExtsMoved;
49237a7e6055SDimitry Andric     Inst = ExtFedByLoad;
492491bc56edSDimitry Andric     return true;
492591bc56edSDimitry Andric   }
492691bc56edSDimitry Andric 
49277a7e6055SDimitry Andric   // Continue promoting SExts if known as considerable depending on targets.
49287a7e6055SDimitry Andric   if (ATPConsiderable &&
49297a7e6055SDimitry Andric       performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
49307a7e6055SDimitry Andric                                   HasPromoted, TPT, SpeculativelyMovedExts))
49317a7e6055SDimitry Andric     return true;
49327a7e6055SDimitry Andric 
49337a7e6055SDimitry Andric   TPT.rollback(LastKnownGood);
49347a7e6055SDimitry Andric   return false;
49357a7e6055SDimitry Andric }
49367a7e6055SDimitry Andric 
49377a7e6055SDimitry Andric // Perform address type promotion if doing so is profitable.
49387a7e6055SDimitry Andric // If AllowPromotionWithoutCommonHeader == false, we should find other sext
49397a7e6055SDimitry Andric // instructions that sign extended the same initial value. However, if
49407a7e6055SDimitry Andric // AllowPromotionWithoutCommonHeader == true, we expect promoting the
49417a7e6055SDimitry Andric // extension is just profitable.
49427a7e6055SDimitry Andric bool CodeGenPrepare::performAddressTypePromotion(
49437a7e6055SDimitry Andric     Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
49447a7e6055SDimitry Andric     bool HasPromoted, TypePromotionTransaction &TPT,
49457a7e6055SDimitry Andric     SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
49467a7e6055SDimitry Andric   bool Promoted = false;
49477a7e6055SDimitry Andric   SmallPtrSet<Instruction *, 1> UnhandledExts;
49487a7e6055SDimitry Andric   bool AllSeenFirst = true;
49497a7e6055SDimitry Andric   for (auto I : SpeculativelyMovedExts) {
49507a7e6055SDimitry Andric     Value *HeadOfChain = I->getOperand(0);
49517a7e6055SDimitry Andric     DenseMap<Value *, Instruction *>::iterator AlreadySeen =
49527a7e6055SDimitry Andric         SeenChainsForSExt.find(HeadOfChain);
49537a7e6055SDimitry Andric     // If there is an unhandled SExt which has the same header, try to promote
49547a7e6055SDimitry Andric     // it as well.
49557a7e6055SDimitry Andric     if (AlreadySeen != SeenChainsForSExt.end()) {
49567a7e6055SDimitry Andric       if (AlreadySeen->second != nullptr)
49577a7e6055SDimitry Andric         UnhandledExts.insert(AlreadySeen->second);
49587a7e6055SDimitry Andric       AllSeenFirst = false;
49597a7e6055SDimitry Andric     }
49607a7e6055SDimitry Andric   }
49617a7e6055SDimitry Andric 
49627a7e6055SDimitry Andric   if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
49637a7e6055SDimitry Andric                         SpeculativelyMovedExts.size() == 1)) {
49647a7e6055SDimitry Andric     TPT.commit();
49657a7e6055SDimitry Andric     if (HasPromoted)
49667a7e6055SDimitry Andric       Promoted = true;
49677a7e6055SDimitry Andric     for (auto I : SpeculativelyMovedExts) {
49687a7e6055SDimitry Andric       Value *HeadOfChain = I->getOperand(0);
49697a7e6055SDimitry Andric       SeenChainsForSExt[HeadOfChain] = nullptr;
49707a7e6055SDimitry Andric       ValToSExtendedUses[HeadOfChain].push_back(I);
49717a7e6055SDimitry Andric     }
49727a7e6055SDimitry Andric     // Update Inst as promotion happen.
49737a7e6055SDimitry Andric     Inst = SpeculativelyMovedExts.pop_back_val();
49747a7e6055SDimitry Andric   } else {
49757a7e6055SDimitry Andric     // This is the first chain visited from the header, keep the current chain
49767a7e6055SDimitry Andric     // as unhandled. Defer to promote this until we encounter another SExt
49777a7e6055SDimitry Andric     // chain derived from the same header.
49787a7e6055SDimitry Andric     for (auto I : SpeculativelyMovedExts) {
49797a7e6055SDimitry Andric       Value *HeadOfChain = I->getOperand(0);
49807a7e6055SDimitry Andric       SeenChainsForSExt[HeadOfChain] = Inst;
49817a7e6055SDimitry Andric     }
49827a7e6055SDimitry Andric     return false;
49837a7e6055SDimitry Andric   }
49847a7e6055SDimitry Andric 
49857a7e6055SDimitry Andric   if (!AllSeenFirst && !UnhandledExts.empty())
49867a7e6055SDimitry Andric     for (auto VisitedSExt : UnhandledExts) {
49877a7e6055SDimitry Andric       if (RemovedInsts.count(VisitedSExt))
49887a7e6055SDimitry Andric         continue;
49897a7e6055SDimitry Andric       TypePromotionTransaction TPT(RemovedInsts);
49907a7e6055SDimitry Andric       SmallVector<Instruction *, 1> Exts;
49917a7e6055SDimitry Andric       SmallVector<Instruction *, 2> Chains;
49927a7e6055SDimitry Andric       Exts.push_back(VisitedSExt);
49937a7e6055SDimitry Andric       bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
49947a7e6055SDimitry Andric       TPT.commit();
49957a7e6055SDimitry Andric       if (HasPromoted)
49967a7e6055SDimitry Andric         Promoted = true;
49977a7e6055SDimitry Andric       for (auto I : Chains) {
49987a7e6055SDimitry Andric         Value *HeadOfChain = I->getOperand(0);
49997a7e6055SDimitry Andric         // Mark this as handled.
50007a7e6055SDimitry Andric         SeenChainsForSExt[HeadOfChain] = nullptr;
50017a7e6055SDimitry Andric         ValToSExtendedUses[HeadOfChain].push_back(I);
50027a7e6055SDimitry Andric       }
50037a7e6055SDimitry Andric     }
50047a7e6055SDimitry Andric   return Promoted;
50057a7e6055SDimitry Andric }
50067a7e6055SDimitry Andric 
50077d523365SDimitry Andric bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
500891bc56edSDimitry Andric   BasicBlock *DefBB = I->getParent();
500991bc56edSDimitry Andric 
501091bc56edSDimitry Andric   // If the result of a {s|z}ext and its source are both live out, rewrite all
501191bc56edSDimitry Andric   // other uses of the source with result of extension.
501291bc56edSDimitry Andric   Value *Src = I->getOperand(0);
501391bc56edSDimitry Andric   if (Src->hasOneUse())
501491bc56edSDimitry Andric     return false;
501591bc56edSDimitry Andric 
501691bc56edSDimitry Andric   // Only do this xform if truncating is free.
501791bc56edSDimitry Andric   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
501891bc56edSDimitry Andric     return false;
501991bc56edSDimitry Andric 
502091bc56edSDimitry Andric   // Only safe to perform the optimization if the source is also defined in
502191bc56edSDimitry Andric   // this block.
502291bc56edSDimitry Andric   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
502391bc56edSDimitry Andric     return false;
502491bc56edSDimitry Andric 
502591bc56edSDimitry Andric   bool DefIsLiveOut = false;
502691bc56edSDimitry Andric   for (User *U : I->users()) {
502791bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
502891bc56edSDimitry Andric 
502991bc56edSDimitry Andric     // Figure out which BB this ext is used in.
503091bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
503191bc56edSDimitry Andric     if (UserBB == DefBB) continue;
503291bc56edSDimitry Andric     DefIsLiveOut = true;
503391bc56edSDimitry Andric     break;
503491bc56edSDimitry Andric   }
503591bc56edSDimitry Andric   if (!DefIsLiveOut)
503691bc56edSDimitry Andric     return false;
503791bc56edSDimitry Andric 
503891bc56edSDimitry Andric   // Make sure none of the uses are PHI nodes.
503991bc56edSDimitry Andric   for (User *U : Src->users()) {
504091bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
504191bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
504291bc56edSDimitry Andric     if (UserBB == DefBB) continue;
504391bc56edSDimitry Andric     // Be conservative. We don't want this xform to end up introducing
504491bc56edSDimitry Andric     // reloads just before load / store instructions.
504591bc56edSDimitry Andric     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
504691bc56edSDimitry Andric       return false;
504791bc56edSDimitry Andric   }
504891bc56edSDimitry Andric 
504991bc56edSDimitry Andric   // InsertedTruncs - Only insert one trunc in each block once.
505091bc56edSDimitry Andric   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
505191bc56edSDimitry Andric 
505291bc56edSDimitry Andric   bool MadeChange = false;
505391bc56edSDimitry Andric   for (Use &U : Src->uses()) {
505491bc56edSDimitry Andric     Instruction *User = cast<Instruction>(U.getUser());
505591bc56edSDimitry Andric 
505691bc56edSDimitry Andric     // Figure out which BB this ext is used in.
505791bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
505891bc56edSDimitry Andric     if (UserBB == DefBB) continue;
505991bc56edSDimitry Andric 
506091bc56edSDimitry Andric     // Both src and def are live in this block. Rewrite the use.
506191bc56edSDimitry Andric     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
506291bc56edSDimitry Andric 
506391bc56edSDimitry Andric     if (!InsertedTrunc) {
506491bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
50657d523365SDimitry Andric       assert(InsertPt != UserBB->end());
50667d523365SDimitry Andric       InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
50678f0fd8f6SDimitry Andric       InsertedInsts.insert(InsertedTrunc);
506891bc56edSDimitry Andric     }
506991bc56edSDimitry Andric 
507091bc56edSDimitry Andric     // Replace a use of the {s|z}ext source with a use of the result.
507191bc56edSDimitry Andric     U = InsertedTrunc;
507291bc56edSDimitry Andric     ++NumExtUses;
507391bc56edSDimitry Andric     MadeChange = true;
507491bc56edSDimitry Andric   }
507591bc56edSDimitry Andric 
507691bc56edSDimitry Andric   return MadeChange;
507791bc56edSDimitry Andric }
507891bc56edSDimitry Andric 
50797d523365SDimitry Andric // Find loads whose uses only use some of the loaded value's bits.  Add an "and"
50807d523365SDimitry Andric // just after the load if the target can fold this into one extload instruction,
50817d523365SDimitry Andric // with the hope of eliminating some of the other later "and" instructions using
50827d523365SDimitry Andric // the loaded value.  "and"s that are made trivially redundant by the insertion
50837d523365SDimitry Andric // of the new "and" are removed by this function, while others (e.g. those whose
50847d523365SDimitry Andric // path from the load goes through a phi) are left for isel to potentially
50857d523365SDimitry Andric // remove.
50867d523365SDimitry Andric //
50877d523365SDimitry Andric // For example:
50887d523365SDimitry Andric //
50897d523365SDimitry Andric // b0:
50907d523365SDimitry Andric //   x = load i32
50917d523365SDimitry Andric //   ...
50927d523365SDimitry Andric // b1:
50937d523365SDimitry Andric //   y = and x, 0xff
50947d523365SDimitry Andric //   z = use y
50957d523365SDimitry Andric //
50967d523365SDimitry Andric // becomes:
50977d523365SDimitry Andric //
50987d523365SDimitry Andric // b0:
50997d523365SDimitry Andric //   x = load i32
51007d523365SDimitry Andric //   x' = and x, 0xff
51017d523365SDimitry Andric //   ...
51027d523365SDimitry Andric // b1:
51037d523365SDimitry Andric //   z = use x'
51047d523365SDimitry Andric //
51057d523365SDimitry Andric // whereas:
51067d523365SDimitry Andric //
51077d523365SDimitry Andric // b0:
51087d523365SDimitry Andric //   x1 = load i32
51097d523365SDimitry Andric //   ...
51107d523365SDimitry Andric // b1:
51117d523365SDimitry Andric //   x2 = load i32
51127d523365SDimitry Andric //   ...
51137d523365SDimitry Andric // b2:
51147d523365SDimitry Andric //   x = phi x1, x2
51157d523365SDimitry Andric //   y = and x, 0xff
51167d523365SDimitry Andric //
51177d523365SDimitry Andric // becomes (after a call to optimizeLoadExt for each load):
51187d523365SDimitry Andric //
51197d523365SDimitry Andric // b0:
51207d523365SDimitry Andric //   x1 = load i32
51217d523365SDimitry Andric //   x1' = and x1, 0xff
51227d523365SDimitry Andric //   ...
51237d523365SDimitry Andric // b1:
51247d523365SDimitry Andric //   x2 = load i32
51257d523365SDimitry Andric //   x2' = and x2, 0xff
51267d523365SDimitry Andric //   ...
51277d523365SDimitry Andric // b2:
51287d523365SDimitry Andric //   x = phi x1', x2'
51297d523365SDimitry Andric //   y = and x, 0xff
51307d523365SDimitry Andric //
51317d523365SDimitry Andric 
51327d523365SDimitry Andric bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
51337d523365SDimitry Andric 
51347d523365SDimitry Andric   if (!Load->isSimple() ||
51357d523365SDimitry Andric       !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
51367d523365SDimitry Andric     return false;
51377d523365SDimitry Andric 
51387a7e6055SDimitry Andric   // Skip loads we've already transformed.
51397a7e6055SDimitry Andric   if (Load->hasOneUse() &&
51407a7e6055SDimitry Andric       InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
51417d523365SDimitry Andric     return false;
51427d523365SDimitry Andric 
51437d523365SDimitry Andric   // Look at all uses of Load, looking through phis, to determine how many bits
51447d523365SDimitry Andric   // of the loaded value are needed.
51457d523365SDimitry Andric   SmallVector<Instruction *, 8> WorkList;
51467d523365SDimitry Andric   SmallPtrSet<Instruction *, 16> Visited;
51477d523365SDimitry Andric   SmallVector<Instruction *, 8> AndsToMaybeRemove;
51487d523365SDimitry Andric   for (auto *U : Load->users())
51497d523365SDimitry Andric     WorkList.push_back(cast<Instruction>(U));
51507d523365SDimitry Andric 
51517d523365SDimitry Andric   EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
51527d523365SDimitry Andric   unsigned BitWidth = LoadResultVT.getSizeInBits();
51537d523365SDimitry Andric   APInt DemandBits(BitWidth, 0);
51547d523365SDimitry Andric   APInt WidestAndBits(BitWidth, 0);
51557d523365SDimitry Andric 
51567d523365SDimitry Andric   while (!WorkList.empty()) {
51577d523365SDimitry Andric     Instruction *I = WorkList.back();
51587d523365SDimitry Andric     WorkList.pop_back();
51597d523365SDimitry Andric 
51607d523365SDimitry Andric     // Break use-def graph loops.
51617d523365SDimitry Andric     if (!Visited.insert(I).second)
51627d523365SDimitry Andric       continue;
51637d523365SDimitry Andric 
51647d523365SDimitry Andric     // For a PHI node, push all of its users.
51657d523365SDimitry Andric     if (auto *Phi = dyn_cast<PHINode>(I)) {
51667d523365SDimitry Andric       for (auto *U : Phi->users())
51677d523365SDimitry Andric         WorkList.push_back(cast<Instruction>(U));
51687d523365SDimitry Andric       continue;
51697d523365SDimitry Andric     }
51707d523365SDimitry Andric 
51717d523365SDimitry Andric     switch (I->getOpcode()) {
51727d523365SDimitry Andric     case llvm::Instruction::And: {
51737d523365SDimitry Andric       auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
51747d523365SDimitry Andric       if (!AndC)
51757d523365SDimitry Andric         return false;
51767d523365SDimitry Andric       APInt AndBits = AndC->getValue();
51777d523365SDimitry Andric       DemandBits |= AndBits;
51787d523365SDimitry Andric       // Keep track of the widest and mask we see.
51797d523365SDimitry Andric       if (AndBits.ugt(WidestAndBits))
51807d523365SDimitry Andric         WidestAndBits = AndBits;
51817d523365SDimitry Andric       if (AndBits == WidestAndBits && I->getOperand(0) == Load)
51827d523365SDimitry Andric         AndsToMaybeRemove.push_back(I);
51837d523365SDimitry Andric       break;
51847d523365SDimitry Andric     }
51857d523365SDimitry Andric 
51867d523365SDimitry Andric     case llvm::Instruction::Shl: {
51877d523365SDimitry Andric       auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
51887d523365SDimitry Andric       if (!ShlC)
51897d523365SDimitry Andric         return false;
51907d523365SDimitry Andric       uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
51916bc11b14SDimitry Andric       DemandBits.setLowBits(BitWidth - ShiftAmt);
51927d523365SDimitry Andric       break;
51937d523365SDimitry Andric     }
51947d523365SDimitry Andric 
51957d523365SDimitry Andric     case llvm::Instruction::Trunc: {
51967d523365SDimitry Andric       EVT TruncVT = TLI->getValueType(*DL, I->getType());
51977d523365SDimitry Andric       unsigned TruncBitWidth = TruncVT.getSizeInBits();
51986bc11b14SDimitry Andric       DemandBits.setLowBits(TruncBitWidth);
51997d523365SDimitry Andric       break;
52007d523365SDimitry Andric     }
52017d523365SDimitry Andric 
52027d523365SDimitry Andric     default:
52037d523365SDimitry Andric       return false;
52047d523365SDimitry Andric     }
52057d523365SDimitry Andric   }
52067d523365SDimitry Andric 
52077d523365SDimitry Andric   uint32_t ActiveBits = DemandBits.getActiveBits();
52087d523365SDimitry Andric   // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
52097d523365SDimitry Andric   // target even if isLoadExtLegal says an i1 EXTLOAD is valid.  For example,
52107d523365SDimitry Andric   // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
52117d523365SDimitry Andric   // (and (load x) 1) is not matched as a single instruction, rather as a LDR
52127d523365SDimitry Andric   // followed by an AND.
52137d523365SDimitry Andric   // TODO: Look into removing this restriction by fixing backends to either
52147d523365SDimitry Andric   // return false for isLoadExtLegal for i1 or have them select this pattern to
52157d523365SDimitry Andric   // a single instruction.
52167d523365SDimitry Andric   //
52177d523365SDimitry Andric   // Also avoid hoisting if we didn't see any ands with the exact DemandBits
52187d523365SDimitry Andric   // mask, since these are the only ands that will be removed by isel.
52197a7e6055SDimitry Andric   if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
52207d523365SDimitry Andric       WidestAndBits != DemandBits)
52217d523365SDimitry Andric     return false;
52227d523365SDimitry Andric 
52237d523365SDimitry Andric   LLVMContext &Ctx = Load->getType()->getContext();
52247d523365SDimitry Andric   Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
52257d523365SDimitry Andric   EVT TruncVT = TLI->getValueType(*DL, TruncTy);
52267d523365SDimitry Andric 
52277d523365SDimitry Andric   // Reject cases that won't be matched as extloads.
52287d523365SDimitry Andric   if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
52297d523365SDimitry Andric       !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
52307d523365SDimitry Andric     return false;
52317d523365SDimitry Andric 
52327d523365SDimitry Andric   IRBuilder<> Builder(Load->getNextNode());
52337d523365SDimitry Andric   auto *NewAnd = dyn_cast<Instruction>(
52347d523365SDimitry Andric       Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
52357a7e6055SDimitry Andric   // Mark this instruction as "inserted by CGP", so that other
52367a7e6055SDimitry Andric   // optimizations don't touch it.
52377a7e6055SDimitry Andric   InsertedInsts.insert(NewAnd);
52387d523365SDimitry Andric 
52397d523365SDimitry Andric   // Replace all uses of load with new and (except for the use of load in the
52407d523365SDimitry Andric   // new and itself).
52417d523365SDimitry Andric   Load->replaceAllUsesWith(NewAnd);
52427d523365SDimitry Andric   NewAnd->setOperand(0, Load);
52437d523365SDimitry Andric 
52447d523365SDimitry Andric   // Remove any and instructions that are now redundant.
52457d523365SDimitry Andric   for (auto *And : AndsToMaybeRemove)
52467d523365SDimitry Andric     // Check that the and mask is the same as the one we decided to put on the
52477d523365SDimitry Andric     // new and.
52487d523365SDimitry Andric     if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
52497d523365SDimitry Andric       And->replaceAllUsesWith(NewAnd);
52507d523365SDimitry Andric       if (&*CurInstIterator == And)
52517d523365SDimitry Andric         CurInstIterator = std::next(And->getIterator());
52527d523365SDimitry Andric       And->eraseFromParent();
52537d523365SDimitry Andric       ++NumAndUses;
52547d523365SDimitry Andric     }
52557d523365SDimitry Andric 
52567d523365SDimitry Andric   ++NumAndsAdded;
52577d523365SDimitry Andric   return true;
52587d523365SDimitry Andric }
52597d523365SDimitry Andric 
52607d523365SDimitry Andric /// Check if V (an operand of a select instruction) is an expensive instruction
52617d523365SDimitry Andric /// that is only used once.
52627d523365SDimitry Andric static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
52637d523365SDimitry Andric   auto *I = dyn_cast<Instruction>(V);
52647d523365SDimitry Andric   // If it's safe to speculatively execute, then it should not have side
52657d523365SDimitry Andric   // effects; therefore, it's safe to sink and possibly *not* execute.
52667d523365SDimitry Andric   return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
52677d523365SDimitry Andric          TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
52687d523365SDimitry Andric }
52697d523365SDimitry Andric 
52707d523365SDimitry Andric /// Returns true if a SelectInst should be turned into an explicit branch.
52717d523365SDimitry Andric static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
52723ca95b02SDimitry Andric                                                 const TargetLowering *TLI,
52737d523365SDimitry Andric                                                 SelectInst *SI) {
52743ca95b02SDimitry Andric   // If even a predictable select is cheap, then a branch can't be cheaper.
52753ca95b02SDimitry Andric   if (!TLI->isPredictableSelectExpensive())
52763ca95b02SDimitry Andric     return false;
52773ca95b02SDimitry Andric 
527891bc56edSDimitry Andric   // FIXME: This should use the same heuristics as IfConversion to determine
52793ca95b02SDimitry Andric   // whether a select is better represented as a branch.
52803ca95b02SDimitry Andric 
52813ca95b02SDimitry Andric   // If metadata tells us that the select condition is obviously predictable,
52823ca95b02SDimitry Andric   // then we want to replace the select with a branch.
52833ca95b02SDimitry Andric   uint64_t TrueWeight, FalseWeight;
52843ca95b02SDimitry Andric   if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
52853ca95b02SDimitry Andric     uint64_t Max = std::max(TrueWeight, FalseWeight);
52863ca95b02SDimitry Andric     uint64_t Sum = TrueWeight + FalseWeight;
52873ca95b02SDimitry Andric     if (Sum != 0) {
52883ca95b02SDimitry Andric       auto Probability = BranchProbability::getBranchProbability(Max, Sum);
52893ca95b02SDimitry Andric       if (Probability > TLI->getPredictableBranchThreshold())
52903ca95b02SDimitry Andric         return true;
52913ca95b02SDimitry Andric     }
52923ca95b02SDimitry Andric   }
529391bc56edSDimitry Andric 
529491bc56edSDimitry Andric   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
529591bc56edSDimitry Andric 
52967d523365SDimitry Andric   // If a branch is predictable, an out-of-order CPU can avoid blocking on its
52977d523365SDimitry Andric   // comparison condition. If the compare has more than one use, there's
52987d523365SDimitry Andric   // probably another cmov or setcc around, so it's not worth emitting a branch.
52997d523365SDimitry Andric   if (!Cmp || !Cmp->hasOneUse())
530091bc56edSDimitry Andric     return false;
530191bc56edSDimitry Andric 
53027d523365SDimitry Andric   // If either operand of the select is expensive and only needed on one side
53037d523365SDimitry Andric   // of the select, we should form a branch.
53047d523365SDimitry Andric   if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
53057d523365SDimitry Andric       sinkSelectOperand(TTI, SI->getFalseValue()))
53067d523365SDimitry Andric     return true;
53077d523365SDimitry Andric 
53087d523365SDimitry Andric   return false;
530991bc56edSDimitry Andric }
531091bc56edSDimitry Andric 
5311d88c1a5aSDimitry Andric /// If \p isTrue is true, return the true value of \p SI, otherwise return
5312d88c1a5aSDimitry Andric /// false value of \p SI. If the true/false value of \p SI is defined by any
5313d88c1a5aSDimitry Andric /// select instructions in \p Selects, look through the defining select
5314d88c1a5aSDimitry Andric /// instruction until the true/false value is not defined in \p Selects.
5315d88c1a5aSDimitry Andric static Value *getTrueOrFalseValue(
5316d88c1a5aSDimitry Andric     SelectInst *SI, bool isTrue,
5317d88c1a5aSDimitry Andric     const SmallPtrSet<const Instruction *, 2> &Selects) {
5318d88c1a5aSDimitry Andric   Value *V;
5319d88c1a5aSDimitry Andric 
5320d88c1a5aSDimitry Andric   for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5321d88c1a5aSDimitry Andric        DefSI = dyn_cast<SelectInst>(V)) {
5322d88c1a5aSDimitry Andric     assert(DefSI->getCondition() == SI->getCondition() &&
5323d88c1a5aSDimitry Andric            "The condition of DefSI does not match with SI");
5324d88c1a5aSDimitry Andric     V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5325d88c1a5aSDimitry Andric   }
5326d88c1a5aSDimitry Andric   return V;
5327d88c1a5aSDimitry Andric }
532891bc56edSDimitry Andric 
532991bc56edSDimitry Andric /// If we have a SelectInst that will likely profit from branch prediction,
533091bc56edSDimitry Andric /// turn it into a branch.
53317d523365SDimitry Andric bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5332d88c1a5aSDimitry Andric   // Find all consecutive select instructions that share the same condition.
5333d88c1a5aSDimitry Andric   SmallVector<SelectInst *, 2> ASI;
5334d88c1a5aSDimitry Andric   ASI.push_back(SI);
5335d88c1a5aSDimitry Andric   for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5336d88c1a5aSDimitry Andric        It != SI->getParent()->end(); ++It) {
5337d88c1a5aSDimitry Andric     SelectInst *I = dyn_cast<SelectInst>(&*It);
5338d88c1a5aSDimitry Andric     if (I && SI->getCondition() == I->getCondition()) {
5339d88c1a5aSDimitry Andric       ASI.push_back(I);
5340d88c1a5aSDimitry Andric     } else {
5341d88c1a5aSDimitry Andric       break;
5342d88c1a5aSDimitry Andric     }
5343d88c1a5aSDimitry Andric   }
5344d88c1a5aSDimitry Andric 
5345d88c1a5aSDimitry Andric   SelectInst *LastSI = ASI.back();
5346d88c1a5aSDimitry Andric   // Increment the current iterator to skip all the rest of select instructions
5347d88c1a5aSDimitry Andric   // because they will be either "not lowered" or "all lowered" to branch.
5348d88c1a5aSDimitry Andric   CurInstIterator = std::next(LastSI->getIterator());
5349d88c1a5aSDimitry Andric 
535091bc56edSDimitry Andric   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
535191bc56edSDimitry Andric 
535291bc56edSDimitry Andric   // Can we convert the 'select' to CF ?
53533ca95b02SDimitry Andric   if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
53543ca95b02SDimitry Andric       SI->getMetadata(LLVMContext::MD_unpredictable))
535591bc56edSDimitry Andric     return false;
535691bc56edSDimitry Andric 
535791bc56edSDimitry Andric   TargetLowering::SelectSupportKind SelectKind;
535891bc56edSDimitry Andric   if (VectorCond)
535991bc56edSDimitry Andric     SelectKind = TargetLowering::VectorMaskSelect;
536091bc56edSDimitry Andric   else if (SI->getType()->isVectorTy())
536191bc56edSDimitry Andric     SelectKind = TargetLowering::ScalarCondVectorVal;
536291bc56edSDimitry Andric   else
536391bc56edSDimitry Andric     SelectKind = TargetLowering::ScalarValSelect;
536491bc56edSDimitry Andric 
53653ca95b02SDimitry Andric   if (TLI->isSelectSupported(SelectKind) &&
53663ca95b02SDimitry Andric       !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
536791bc56edSDimitry Andric     return false;
536891bc56edSDimitry Andric 
536991bc56edSDimitry Andric   ModifiedDT = true;
537091bc56edSDimitry Andric 
53717d523365SDimitry Andric   // Transform a sequence like this:
53727d523365SDimitry Andric   //    start:
53737d523365SDimitry Andric   //       %cmp = cmp uge i32 %a, %b
53747d523365SDimitry Andric   //       %sel = select i1 %cmp, i32 %c, i32 %d
53757d523365SDimitry Andric   //
53767d523365SDimitry Andric   // Into:
53777d523365SDimitry Andric   //    start:
53787d523365SDimitry Andric   //       %cmp = cmp uge i32 %a, %b
53797d523365SDimitry Andric   //       br i1 %cmp, label %select.true, label %select.false
53807d523365SDimitry Andric   //    select.true:
53817d523365SDimitry Andric   //       br label %select.end
53827d523365SDimitry Andric   //    select.false:
53837d523365SDimitry Andric   //       br label %select.end
53847d523365SDimitry Andric   //    select.end:
53857d523365SDimitry Andric   //       %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
53867d523365SDimitry Andric   //
53877d523365SDimitry Andric   // In addition, we may sink instructions that produce %c or %d from
53887d523365SDimitry Andric   // the entry block into the destination(s) of the new branch.
53897d523365SDimitry Andric   // If the true or false blocks do not contain a sunken instruction, that
53907d523365SDimitry Andric   // block and its branch may be optimized away. In that case, one side of the
53917d523365SDimitry Andric   // first branch will point directly to select.end, and the corresponding PHI
53927d523365SDimitry Andric   // predecessor block will be the start block.
53937d523365SDimitry Andric 
539491bc56edSDimitry Andric   // First, we split the block containing the select into 2 blocks.
539591bc56edSDimitry Andric   BasicBlock *StartBlock = SI->getParent();
5396d88c1a5aSDimitry Andric   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
53977d523365SDimitry Andric   BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
539891bc56edSDimitry Andric 
53997d523365SDimitry Andric   // Delete the unconditional branch that was just created by the split.
540091bc56edSDimitry Andric   StartBlock->getTerminator()->eraseFromParent();
54017d523365SDimitry Andric 
54027d523365SDimitry Andric   // These are the new basic blocks for the conditional branch.
54037d523365SDimitry Andric   // At least one will become an actual new basic block.
54047d523365SDimitry Andric   BasicBlock *TrueBlock = nullptr;
54057d523365SDimitry Andric   BasicBlock *FalseBlock = nullptr;
5406d88c1a5aSDimitry Andric   BranchInst *TrueBranch = nullptr;
5407d88c1a5aSDimitry Andric   BranchInst *FalseBranch = nullptr;
54087d523365SDimitry Andric 
54097d523365SDimitry Andric   // Sink expensive instructions into the conditional blocks to avoid executing
54107d523365SDimitry Andric   // them speculatively.
5411d88c1a5aSDimitry Andric   for (SelectInst *SI : ASI) {
54127d523365SDimitry Andric     if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5413d88c1a5aSDimitry Andric       if (TrueBlock == nullptr) {
54147d523365SDimitry Andric         TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
54157d523365SDimitry Andric                                        EndBlock->getParent(), EndBlock);
5416d88c1a5aSDimitry Andric         TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5417d88c1a5aSDimitry Andric       }
54187d523365SDimitry Andric       auto *TrueInst = cast<Instruction>(SI->getTrueValue());
54197d523365SDimitry Andric       TrueInst->moveBefore(TrueBranch);
54207d523365SDimitry Andric     }
54217d523365SDimitry Andric     if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5422d88c1a5aSDimitry Andric       if (FalseBlock == nullptr) {
54237d523365SDimitry Andric         FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
54247d523365SDimitry Andric                                         EndBlock->getParent(), EndBlock);
5425d88c1a5aSDimitry Andric         FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5426d88c1a5aSDimitry Andric       }
54277d523365SDimitry Andric       auto *FalseInst = cast<Instruction>(SI->getFalseValue());
54287d523365SDimitry Andric       FalseInst->moveBefore(FalseBranch);
54297d523365SDimitry Andric     }
5430d88c1a5aSDimitry Andric   }
54317d523365SDimitry Andric 
54327d523365SDimitry Andric   // If there was nothing to sink, then arbitrarily choose the 'false' side
54337d523365SDimitry Andric   // for a new input value to the PHI.
54347d523365SDimitry Andric   if (TrueBlock == FalseBlock) {
54357d523365SDimitry Andric     assert(TrueBlock == nullptr &&
54367d523365SDimitry Andric            "Unexpected basic block transform while optimizing select");
54377d523365SDimitry Andric 
54387d523365SDimitry Andric     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
54397d523365SDimitry Andric                                     EndBlock->getParent(), EndBlock);
54407d523365SDimitry Andric     BranchInst::Create(EndBlock, FalseBlock);
54417d523365SDimitry Andric   }
544291bc56edSDimitry Andric 
544391bc56edSDimitry Andric   // Insert the real conditional branch based on the original condition.
54447d523365SDimitry Andric   // If we did not create a new block for one of the 'true' or 'false' paths
54457d523365SDimitry Andric   // of the condition, it means that side of the branch goes to the end block
54467d523365SDimitry Andric   // directly and the path originates from the start block from the point of
54477d523365SDimitry Andric   // view of the new PHI.
5448d88c1a5aSDimitry Andric   BasicBlock *TT, *FT;
54497d523365SDimitry Andric   if (TrueBlock == nullptr) {
5450d88c1a5aSDimitry Andric     TT = EndBlock;
5451d88c1a5aSDimitry Andric     FT = FalseBlock;
54527d523365SDimitry Andric     TrueBlock = StartBlock;
54537d523365SDimitry Andric   } else if (FalseBlock == nullptr) {
5454d88c1a5aSDimitry Andric     TT = TrueBlock;
5455d88c1a5aSDimitry Andric     FT = EndBlock;
54567d523365SDimitry Andric     FalseBlock = StartBlock;
54577d523365SDimitry Andric   } else {
5458d88c1a5aSDimitry Andric     TT = TrueBlock;
5459d88c1a5aSDimitry Andric     FT = FalseBlock;
54607d523365SDimitry Andric   }
5461d88c1a5aSDimitry Andric   IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
546291bc56edSDimitry Andric 
5463d88c1a5aSDimitry Andric   SmallPtrSet<const Instruction *, 2> INS;
5464d88c1a5aSDimitry Andric   INS.insert(ASI.begin(), ASI.end());
5465d88c1a5aSDimitry Andric   // Use reverse iterator because later select may use the value of the
5466d88c1a5aSDimitry Andric   // earlier select, and we need to propagate value through earlier select
5467d88c1a5aSDimitry Andric   // to get the PHI operand.
5468d88c1a5aSDimitry Andric   for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5469d88c1a5aSDimitry Andric     SelectInst *SI = *It;
547091bc56edSDimitry Andric     // The select itself is replaced with a PHI Node.
54717d523365SDimitry Andric     PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
547291bc56edSDimitry Andric     PN->takeName(SI);
5473d88c1a5aSDimitry Andric     PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5474d88c1a5aSDimitry Andric     PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
54757d523365SDimitry Andric 
547691bc56edSDimitry Andric     SI->replaceAllUsesWith(PN);
547791bc56edSDimitry Andric     SI->eraseFromParent();
5478d88c1a5aSDimitry Andric     INS.erase(SI);
5479d88c1a5aSDimitry Andric     ++NumSelectsExpanded;
5480d88c1a5aSDimitry Andric   }
548191bc56edSDimitry Andric 
548291bc56edSDimitry Andric   // Instruct OptimizeBlock to skip to the next block.
548391bc56edSDimitry Andric   CurInstIterator = StartBlock->end();
548491bc56edSDimitry Andric   return true;
548591bc56edSDimitry Andric }
548691bc56edSDimitry Andric 
548791bc56edSDimitry Andric static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
548891bc56edSDimitry Andric   SmallVector<int, 16> Mask(SVI->getShuffleMask());
548991bc56edSDimitry Andric   int SplatElem = -1;
549091bc56edSDimitry Andric   for (unsigned i = 0; i < Mask.size(); ++i) {
549191bc56edSDimitry Andric     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
549291bc56edSDimitry Andric       return false;
549391bc56edSDimitry Andric     SplatElem = Mask[i];
549491bc56edSDimitry Andric   }
549591bc56edSDimitry Andric 
549691bc56edSDimitry Andric   return true;
549791bc56edSDimitry Andric }
549891bc56edSDimitry Andric 
549991bc56edSDimitry Andric /// Some targets have expensive vector shifts if the lanes aren't all the same
550091bc56edSDimitry Andric /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
550191bc56edSDimitry Andric /// it's often worth sinking a shufflevector splat down to its use so that
550291bc56edSDimitry Andric /// codegen can spot all lanes are identical.
55037d523365SDimitry Andric bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
550491bc56edSDimitry Andric   BasicBlock *DefBB = SVI->getParent();
550591bc56edSDimitry Andric 
550691bc56edSDimitry Andric   // Only do this xform if variable vector shifts are particularly expensive.
550791bc56edSDimitry Andric   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
550891bc56edSDimitry Andric     return false;
550991bc56edSDimitry Andric 
551091bc56edSDimitry Andric   // We only expect better codegen by sinking a shuffle if we can recognise a
551191bc56edSDimitry Andric   // constant splat.
551291bc56edSDimitry Andric   if (!isBroadcastShuffle(SVI))
551391bc56edSDimitry Andric     return false;
551491bc56edSDimitry Andric 
551591bc56edSDimitry Andric   // InsertedShuffles - Only insert a shuffle in each block once.
551691bc56edSDimitry Andric   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
551791bc56edSDimitry Andric 
551891bc56edSDimitry Andric   bool MadeChange = false;
551991bc56edSDimitry Andric   for (User *U : SVI->users()) {
552091bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
552191bc56edSDimitry Andric 
552291bc56edSDimitry Andric     // Figure out which BB this ext is used in.
552391bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
552491bc56edSDimitry Andric     if (UserBB == DefBB) continue;
552591bc56edSDimitry Andric 
552691bc56edSDimitry Andric     // For now only apply this when the splat is used by a shift instruction.
552791bc56edSDimitry Andric     if (!UI->isShift()) continue;
552891bc56edSDimitry Andric 
552991bc56edSDimitry Andric     // Everything checks out, sink the shuffle if the user's block doesn't
553091bc56edSDimitry Andric     // already have a copy.
553191bc56edSDimitry Andric     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
553291bc56edSDimitry Andric 
553391bc56edSDimitry Andric     if (!InsertedShuffle) {
553491bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
55357d523365SDimitry Andric       assert(InsertPt != UserBB->end());
55367d523365SDimitry Andric       InsertedShuffle =
55377d523365SDimitry Andric           new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
55387d523365SDimitry Andric                                 SVI->getOperand(2), "", &*InsertPt);
553991bc56edSDimitry Andric     }
554091bc56edSDimitry Andric 
554191bc56edSDimitry Andric     UI->replaceUsesOfWith(SVI, InsertedShuffle);
554291bc56edSDimitry Andric     MadeChange = true;
554391bc56edSDimitry Andric   }
554491bc56edSDimitry Andric 
554591bc56edSDimitry Andric   // If we removed all uses, nuke the shuffle.
554691bc56edSDimitry Andric   if (SVI->use_empty()) {
554791bc56edSDimitry Andric     SVI->eraseFromParent();
554891bc56edSDimitry Andric     MadeChange = true;
554991bc56edSDimitry Andric   }
555091bc56edSDimitry Andric 
555191bc56edSDimitry Andric   return MadeChange;
555291bc56edSDimitry Andric }
555391bc56edSDimitry Andric 
55547d523365SDimitry Andric bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
55557d523365SDimitry Andric   if (!TLI || !DL)
55567d523365SDimitry Andric     return false;
55577d523365SDimitry Andric 
55587d523365SDimitry Andric   Value *Cond = SI->getCondition();
55597d523365SDimitry Andric   Type *OldType = Cond->getType();
55607d523365SDimitry Andric   LLVMContext &Context = Cond->getContext();
55617d523365SDimitry Andric   MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
55627d523365SDimitry Andric   unsigned RegWidth = RegType.getSizeInBits();
55637d523365SDimitry Andric 
55647d523365SDimitry Andric   if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
55657d523365SDimitry Andric     return false;
55667d523365SDimitry Andric 
55677d523365SDimitry Andric   // If the register width is greater than the type width, expand the condition
55687d523365SDimitry Andric   // of the switch instruction and each case constant to the width of the
55697d523365SDimitry Andric   // register. By widening the type of the switch condition, subsequent
55707d523365SDimitry Andric   // comparisons (for case comparisons) will not need to be extended to the
55717d523365SDimitry Andric   // preferred register width, so we will potentially eliminate N-1 extends,
55727d523365SDimitry Andric   // where N is the number of cases in the switch.
55737d523365SDimitry Andric   auto *NewType = Type::getIntNTy(Context, RegWidth);
55747d523365SDimitry Andric 
55757d523365SDimitry Andric   // Zero-extend the switch condition and case constants unless the switch
55767d523365SDimitry Andric   // condition is a function argument that is already being sign-extended.
55777d523365SDimitry Andric   // In that case, we can avoid an unnecessary mask/extension by sign-extending
55787d523365SDimitry Andric   // everything instead.
55797d523365SDimitry Andric   Instruction::CastOps ExtType = Instruction::ZExt;
55807d523365SDimitry Andric   if (auto *Arg = dyn_cast<Argument>(Cond))
55817d523365SDimitry Andric     if (Arg->hasSExtAttr())
55827d523365SDimitry Andric       ExtType = Instruction::SExt;
55837d523365SDimitry Andric 
55847d523365SDimitry Andric   auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
55857d523365SDimitry Andric   ExtInst->insertBefore(SI);
55867d523365SDimitry Andric   SI->setCondition(ExtInst);
55877a7e6055SDimitry Andric   for (auto Case : SI->cases()) {
55887d523365SDimitry Andric     APInt NarrowConst = Case.getCaseValue()->getValue();
55897d523365SDimitry Andric     APInt WideConst = (ExtType == Instruction::ZExt) ?
55907d523365SDimitry Andric                       NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
55917d523365SDimitry Andric     Case.setValue(ConstantInt::get(Context, WideConst));
55927d523365SDimitry Andric   }
55937d523365SDimitry Andric 
55947d523365SDimitry Andric   return true;
55957d523365SDimitry Andric }
55967d523365SDimitry Andric 
5597f9448bf3SDimitry Andric 
559839d628a0SDimitry Andric namespace {
559939d628a0SDimitry Andric /// \brief Helper class to promote a scalar operation to a vector one.
560039d628a0SDimitry Andric /// This class is used to move downward extractelement transition.
560139d628a0SDimitry Andric /// E.g.,
560239d628a0SDimitry Andric /// a = vector_op <2 x i32>
560339d628a0SDimitry Andric /// b = extractelement <2 x i32> a, i32 0
560439d628a0SDimitry Andric /// c = scalar_op b
560539d628a0SDimitry Andric /// store c
560639d628a0SDimitry Andric ///
560739d628a0SDimitry Andric /// =>
560839d628a0SDimitry Andric /// a = vector_op <2 x i32>
560939d628a0SDimitry Andric /// c = vector_op a (equivalent to scalar_op on the related lane)
561039d628a0SDimitry Andric /// * d = extractelement <2 x i32> c, i32 0
561139d628a0SDimitry Andric /// * store d
561239d628a0SDimitry Andric /// Assuming both extractelement and store can be combine, we get rid of the
561339d628a0SDimitry Andric /// transition.
561439d628a0SDimitry Andric class VectorPromoteHelper {
5615875ed548SDimitry Andric   /// DataLayout associated with the current module.
5616875ed548SDimitry Andric   const DataLayout &DL;
5617875ed548SDimitry Andric 
561839d628a0SDimitry Andric   /// Used to perform some checks on the legality of vector operations.
561939d628a0SDimitry Andric   const TargetLowering &TLI;
562039d628a0SDimitry Andric 
562139d628a0SDimitry Andric   /// Used to estimated the cost of the promoted chain.
562239d628a0SDimitry Andric   const TargetTransformInfo &TTI;
562339d628a0SDimitry Andric 
562439d628a0SDimitry Andric   /// The transition being moved downwards.
562539d628a0SDimitry Andric   Instruction *Transition;
562639d628a0SDimitry Andric   /// The sequence of instructions to be promoted.
562739d628a0SDimitry Andric   SmallVector<Instruction *, 4> InstsToBePromoted;
562839d628a0SDimitry Andric   /// Cost of combining a store and an extract.
562939d628a0SDimitry Andric   unsigned StoreExtractCombineCost;
563039d628a0SDimitry Andric   /// Instruction that will be combined with the transition.
563139d628a0SDimitry Andric   Instruction *CombineInst;
563239d628a0SDimitry Andric 
563339d628a0SDimitry Andric   /// \brief The instruction that represents the current end of the transition.
563439d628a0SDimitry Andric   /// Since we are faking the promotion until we reach the end of the chain
563539d628a0SDimitry Andric   /// of computation, we need a way to get the current end of the transition.
563639d628a0SDimitry Andric   Instruction *getEndOfTransition() const {
563739d628a0SDimitry Andric     if (InstsToBePromoted.empty())
563839d628a0SDimitry Andric       return Transition;
563939d628a0SDimitry Andric     return InstsToBePromoted.back();
564039d628a0SDimitry Andric   }
564139d628a0SDimitry Andric 
564239d628a0SDimitry Andric   /// \brief Return the index of the original value in the transition.
564339d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
564439d628a0SDimitry Andric   /// c, is at index 0.
564539d628a0SDimitry Andric   unsigned getTransitionOriginalValueIdx() const {
564639d628a0SDimitry Andric     assert(isa<ExtractElementInst>(Transition) &&
564739d628a0SDimitry Andric            "Other kind of transitions are not supported yet");
564839d628a0SDimitry Andric     return 0;
564939d628a0SDimitry Andric   }
565039d628a0SDimitry Andric 
565139d628a0SDimitry Andric   /// \brief Return the index of the index in the transition.
565239d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
565339d628a0SDimitry Andric   /// is at index 1.
565439d628a0SDimitry Andric   unsigned getTransitionIdx() const {
565539d628a0SDimitry Andric     assert(isa<ExtractElementInst>(Transition) &&
565639d628a0SDimitry Andric            "Other kind of transitions are not supported yet");
565739d628a0SDimitry Andric     return 1;
565839d628a0SDimitry Andric   }
565939d628a0SDimitry Andric 
566039d628a0SDimitry Andric   /// \brief Get the type of the transition.
566139d628a0SDimitry Andric   /// This is the type of the original value.
566239d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
566339d628a0SDimitry Andric   /// transition is <2 x i32>.
566439d628a0SDimitry Andric   Type *getTransitionType() const {
566539d628a0SDimitry Andric     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
566639d628a0SDimitry Andric   }
566739d628a0SDimitry Andric 
566839d628a0SDimitry Andric   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
566939d628a0SDimitry Andric   /// I.e., we have the following sequence:
567039d628a0SDimitry Andric   /// Def = Transition <ty1> a to <ty2>
567139d628a0SDimitry Andric   /// b = ToBePromoted <ty2> Def, ...
567239d628a0SDimitry Andric   /// =>
567339d628a0SDimitry Andric   /// b = ToBePromoted <ty1> a, ...
567439d628a0SDimitry Andric   /// Def = Transition <ty1> ToBePromoted to <ty2>
567539d628a0SDimitry Andric   void promoteImpl(Instruction *ToBePromoted);
567639d628a0SDimitry Andric 
567739d628a0SDimitry Andric   /// \brief Check whether or not it is profitable to promote all the
567839d628a0SDimitry Andric   /// instructions enqueued to be promoted.
567939d628a0SDimitry Andric   bool isProfitableToPromote() {
568039d628a0SDimitry Andric     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
568139d628a0SDimitry Andric     unsigned Index = isa<ConstantInt>(ValIdx)
568239d628a0SDimitry Andric                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
568339d628a0SDimitry Andric                          : -1;
568439d628a0SDimitry Andric     Type *PromotedType = getTransitionType();
568539d628a0SDimitry Andric 
568639d628a0SDimitry Andric     StoreInst *ST = cast<StoreInst>(CombineInst);
568739d628a0SDimitry Andric     unsigned AS = ST->getPointerAddressSpace();
568839d628a0SDimitry Andric     unsigned Align = ST->getAlignment();
568939d628a0SDimitry Andric     // Check if this store is supported.
569039d628a0SDimitry Andric     if (!TLI.allowsMisalignedMemoryAccesses(
5691875ed548SDimitry Andric             TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5692875ed548SDimitry Andric             Align)) {
569339d628a0SDimitry Andric       // If this is not supported, there is no way we can combine
569439d628a0SDimitry Andric       // the extract with the store.
569539d628a0SDimitry Andric       return false;
569639d628a0SDimitry Andric     }
569739d628a0SDimitry Andric 
569839d628a0SDimitry Andric     // The scalar chain of computation has to pay for the transition
569939d628a0SDimitry Andric     // scalar to vector.
570039d628a0SDimitry Andric     // The vector chain has to account for the combining cost.
570139d628a0SDimitry Andric     uint64_t ScalarCost =
570239d628a0SDimitry Andric         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
570339d628a0SDimitry Andric     uint64_t VectorCost = StoreExtractCombineCost;
570439d628a0SDimitry Andric     for (const auto &Inst : InstsToBePromoted) {
570539d628a0SDimitry Andric       // Compute the cost.
570639d628a0SDimitry Andric       // By construction, all instructions being promoted are arithmetic ones.
570739d628a0SDimitry Andric       // Moreover, one argument is a constant that can be viewed as a splat
570839d628a0SDimitry Andric       // constant.
570939d628a0SDimitry Andric       Value *Arg0 = Inst->getOperand(0);
571039d628a0SDimitry Andric       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
571139d628a0SDimitry Andric                             isa<ConstantFP>(Arg0);
571239d628a0SDimitry Andric       TargetTransformInfo::OperandValueKind Arg0OVK =
571339d628a0SDimitry Andric           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
571439d628a0SDimitry Andric                          : TargetTransformInfo::OK_AnyValue;
571539d628a0SDimitry Andric       TargetTransformInfo::OperandValueKind Arg1OVK =
571639d628a0SDimitry Andric           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
571739d628a0SDimitry Andric                           : TargetTransformInfo::OK_AnyValue;
571839d628a0SDimitry Andric       ScalarCost += TTI.getArithmeticInstrCost(
571939d628a0SDimitry Andric           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
572039d628a0SDimitry Andric       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
572139d628a0SDimitry Andric                                                Arg0OVK, Arg1OVK);
572239d628a0SDimitry Andric     }
572339d628a0SDimitry Andric     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
572439d628a0SDimitry Andric                  << ScalarCost << "\nVector: " << VectorCost << '\n');
572539d628a0SDimitry Andric     return ScalarCost > VectorCost;
572639d628a0SDimitry Andric   }
572739d628a0SDimitry Andric 
572839d628a0SDimitry Andric   /// \brief Generate a constant vector with \p Val with the same
572939d628a0SDimitry Andric   /// number of elements as the transition.
573039d628a0SDimitry Andric   /// \p UseSplat defines whether or not \p Val should be replicated
57317d523365SDimitry Andric   /// across the whole vector.
573239d628a0SDimitry Andric   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
573339d628a0SDimitry Andric   /// otherwise we generate a vector with as many undef as possible:
573439d628a0SDimitry Andric   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
573539d628a0SDimitry Andric   /// used at the index of the extract.
573639d628a0SDimitry Andric   Value *getConstantVector(Constant *Val, bool UseSplat) const {
573739d628a0SDimitry Andric     unsigned ExtractIdx = UINT_MAX;
573839d628a0SDimitry Andric     if (!UseSplat) {
573939d628a0SDimitry Andric       // If we cannot determine where the constant must be, we have to
574039d628a0SDimitry Andric       // use a splat constant.
574139d628a0SDimitry Andric       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
574239d628a0SDimitry Andric       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
574339d628a0SDimitry Andric         ExtractIdx = CstVal->getSExtValue();
574439d628a0SDimitry Andric       else
574539d628a0SDimitry Andric         UseSplat = true;
574639d628a0SDimitry Andric     }
574739d628a0SDimitry Andric 
574839d628a0SDimitry Andric     unsigned End = getTransitionType()->getVectorNumElements();
574939d628a0SDimitry Andric     if (UseSplat)
575039d628a0SDimitry Andric       return ConstantVector::getSplat(End, Val);
575139d628a0SDimitry Andric 
575239d628a0SDimitry Andric     SmallVector<Constant *, 4> ConstVec;
575339d628a0SDimitry Andric     UndefValue *UndefVal = UndefValue::get(Val->getType());
575439d628a0SDimitry Andric     for (unsigned Idx = 0; Idx != End; ++Idx) {
575539d628a0SDimitry Andric       if (Idx == ExtractIdx)
575639d628a0SDimitry Andric         ConstVec.push_back(Val);
575739d628a0SDimitry Andric       else
575839d628a0SDimitry Andric         ConstVec.push_back(UndefVal);
575939d628a0SDimitry Andric     }
576039d628a0SDimitry Andric     return ConstantVector::get(ConstVec);
576139d628a0SDimitry Andric   }
576239d628a0SDimitry Andric 
576339d628a0SDimitry Andric   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
576439d628a0SDimitry Andric   /// in \p Use can trigger undefined behavior.
576539d628a0SDimitry Andric   static bool canCauseUndefinedBehavior(const Instruction *Use,
576639d628a0SDimitry Andric                                         unsigned OperandIdx) {
576739d628a0SDimitry Andric     // This is not safe to introduce undef when the operand is on
576839d628a0SDimitry Andric     // the right hand side of a division-like instruction.
576939d628a0SDimitry Andric     if (OperandIdx != 1)
577039d628a0SDimitry Andric       return false;
577139d628a0SDimitry Andric     switch (Use->getOpcode()) {
577239d628a0SDimitry Andric     default:
577339d628a0SDimitry Andric       return false;
577439d628a0SDimitry Andric     case Instruction::SDiv:
577539d628a0SDimitry Andric     case Instruction::UDiv:
577639d628a0SDimitry Andric     case Instruction::SRem:
577739d628a0SDimitry Andric     case Instruction::URem:
577839d628a0SDimitry Andric       return true;
577939d628a0SDimitry Andric     case Instruction::FDiv:
578039d628a0SDimitry Andric     case Instruction::FRem:
578139d628a0SDimitry Andric       return !Use->hasNoNaNs();
578239d628a0SDimitry Andric     }
578339d628a0SDimitry Andric     llvm_unreachable(nullptr);
578439d628a0SDimitry Andric   }
578539d628a0SDimitry Andric 
578639d628a0SDimitry Andric public:
5787875ed548SDimitry Andric   VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5788875ed548SDimitry Andric                       const TargetTransformInfo &TTI, Instruction *Transition,
5789875ed548SDimitry Andric                       unsigned CombineCost)
5790875ed548SDimitry Andric       : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
579139d628a0SDimitry Andric         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
579239d628a0SDimitry Andric     assert(Transition && "Do not know how to promote null");
579339d628a0SDimitry Andric   }
579439d628a0SDimitry Andric 
579539d628a0SDimitry Andric   /// \brief Check if we can promote \p ToBePromoted to \p Type.
579639d628a0SDimitry Andric   bool canPromote(const Instruction *ToBePromoted) const {
579739d628a0SDimitry Andric     // We could support CastInst too.
579839d628a0SDimitry Andric     return isa<BinaryOperator>(ToBePromoted);
579939d628a0SDimitry Andric   }
580039d628a0SDimitry Andric 
580139d628a0SDimitry Andric   /// \brief Check if it is profitable to promote \p ToBePromoted
580239d628a0SDimitry Andric   /// by moving downward the transition through.
580339d628a0SDimitry Andric   bool shouldPromote(const Instruction *ToBePromoted) const {
580439d628a0SDimitry Andric     // Promote only if all the operands can be statically expanded.
580539d628a0SDimitry Andric     // Indeed, we do not want to introduce any new kind of transitions.
580639d628a0SDimitry Andric     for (const Use &U : ToBePromoted->operands()) {
580739d628a0SDimitry Andric       const Value *Val = U.get();
580839d628a0SDimitry Andric       if (Val == getEndOfTransition()) {
580939d628a0SDimitry Andric         // If the use is a division and the transition is on the rhs,
581039d628a0SDimitry Andric         // we cannot promote the operation, otherwise we may create a
581139d628a0SDimitry Andric         // division by zero.
581239d628a0SDimitry Andric         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
581339d628a0SDimitry Andric           return false;
581439d628a0SDimitry Andric         continue;
581539d628a0SDimitry Andric       }
581639d628a0SDimitry Andric       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
581739d628a0SDimitry Andric           !isa<ConstantFP>(Val))
581839d628a0SDimitry Andric         return false;
581939d628a0SDimitry Andric     }
582039d628a0SDimitry Andric     // Check that the resulting operation is legal.
582139d628a0SDimitry Andric     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
582239d628a0SDimitry Andric     if (!ISDOpcode)
582339d628a0SDimitry Andric       return false;
582439d628a0SDimitry Andric     return StressStoreExtract ||
582539d628a0SDimitry Andric            TLI.isOperationLegalOrCustom(
5826875ed548SDimitry Andric                ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
582739d628a0SDimitry Andric   }
582839d628a0SDimitry Andric 
582939d628a0SDimitry Andric   /// \brief Check whether or not \p Use can be combined
583039d628a0SDimitry Andric   /// with the transition.
583139d628a0SDimitry Andric   /// I.e., is it possible to do Use(Transition) => AnotherUse?
583239d628a0SDimitry Andric   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
583339d628a0SDimitry Andric 
583439d628a0SDimitry Andric   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
583539d628a0SDimitry Andric   void enqueueForPromotion(Instruction *ToBePromoted) {
583639d628a0SDimitry Andric     InstsToBePromoted.push_back(ToBePromoted);
583739d628a0SDimitry Andric   }
583839d628a0SDimitry Andric 
583939d628a0SDimitry Andric   /// \brief Set the instruction that will be combined with the transition.
584039d628a0SDimitry Andric   void recordCombineInstruction(Instruction *ToBeCombined) {
584139d628a0SDimitry Andric     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
584239d628a0SDimitry Andric     CombineInst = ToBeCombined;
584339d628a0SDimitry Andric   }
584439d628a0SDimitry Andric 
584539d628a0SDimitry Andric   /// \brief Promote all the instructions enqueued for promotion if it is
584639d628a0SDimitry Andric   /// is profitable.
584739d628a0SDimitry Andric   /// \return True if the promotion happened, false otherwise.
584839d628a0SDimitry Andric   bool promote() {
584939d628a0SDimitry Andric     // Check if there is something to promote.
585039d628a0SDimitry Andric     // Right now, if we do not have anything to combine with,
585139d628a0SDimitry Andric     // we assume the promotion is not profitable.
585239d628a0SDimitry Andric     if (InstsToBePromoted.empty() || !CombineInst)
585339d628a0SDimitry Andric       return false;
585439d628a0SDimitry Andric 
585539d628a0SDimitry Andric     // Check cost.
585639d628a0SDimitry Andric     if (!StressStoreExtract && !isProfitableToPromote())
585739d628a0SDimitry Andric       return false;
585839d628a0SDimitry Andric 
585939d628a0SDimitry Andric     // Promote.
586039d628a0SDimitry Andric     for (auto &ToBePromoted : InstsToBePromoted)
586139d628a0SDimitry Andric       promoteImpl(ToBePromoted);
586239d628a0SDimitry Andric     InstsToBePromoted.clear();
586339d628a0SDimitry Andric     return true;
586439d628a0SDimitry Andric   }
586539d628a0SDimitry Andric };
586639d628a0SDimitry Andric } // End of anonymous namespace.
586739d628a0SDimitry Andric 
586839d628a0SDimitry Andric void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
586939d628a0SDimitry Andric   // At this point, we know that all the operands of ToBePromoted but Def
587039d628a0SDimitry Andric   // can be statically promoted.
587139d628a0SDimitry Andric   // For Def, we need to use its parameter in ToBePromoted:
587239d628a0SDimitry Andric   // b = ToBePromoted ty1 a
587339d628a0SDimitry Andric   // Def = Transition ty1 b to ty2
587439d628a0SDimitry Andric   // Move the transition down.
587539d628a0SDimitry Andric   // 1. Replace all uses of the promoted operation by the transition.
587639d628a0SDimitry Andric   // = ... b => = ... Def.
587739d628a0SDimitry Andric   assert(ToBePromoted->getType() == Transition->getType() &&
587839d628a0SDimitry Andric          "The type of the result of the transition does not match "
587939d628a0SDimitry Andric          "the final type");
588039d628a0SDimitry Andric   ToBePromoted->replaceAllUsesWith(Transition);
588139d628a0SDimitry Andric   // 2. Update the type of the uses.
588239d628a0SDimitry Andric   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
588339d628a0SDimitry Andric   Type *TransitionTy = getTransitionType();
588439d628a0SDimitry Andric   ToBePromoted->mutateType(TransitionTy);
588539d628a0SDimitry Andric   // 3. Update all the operands of the promoted operation with promoted
588639d628a0SDimitry Andric   // operands.
588739d628a0SDimitry Andric   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
588839d628a0SDimitry Andric   for (Use &U : ToBePromoted->operands()) {
588939d628a0SDimitry Andric     Value *Val = U.get();
589039d628a0SDimitry Andric     Value *NewVal = nullptr;
589139d628a0SDimitry Andric     if (Val == Transition)
589239d628a0SDimitry Andric       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
589339d628a0SDimitry Andric     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
589439d628a0SDimitry Andric              isa<ConstantFP>(Val)) {
589539d628a0SDimitry Andric       // Use a splat constant if it is not safe to use undef.
589639d628a0SDimitry Andric       NewVal = getConstantVector(
589739d628a0SDimitry Andric           cast<Constant>(Val),
589839d628a0SDimitry Andric           isa<UndefValue>(Val) ||
589939d628a0SDimitry Andric               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
590039d628a0SDimitry Andric     } else
590139d628a0SDimitry Andric       llvm_unreachable("Did you modified shouldPromote and forgot to update "
590239d628a0SDimitry Andric                        "this?");
590339d628a0SDimitry Andric     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
590439d628a0SDimitry Andric   }
590539d628a0SDimitry Andric   Transition->removeFromParent();
590639d628a0SDimitry Andric   Transition->insertAfter(ToBePromoted);
590739d628a0SDimitry Andric   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
590839d628a0SDimitry Andric }
590939d628a0SDimitry Andric 
591039d628a0SDimitry Andric /// Some targets can do store(extractelement) with one instruction.
591139d628a0SDimitry Andric /// Try to push the extractelement towards the stores when the target
591239d628a0SDimitry Andric /// has this feature and this is profitable.
59137d523365SDimitry Andric bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
591439d628a0SDimitry Andric   unsigned CombineCost = UINT_MAX;
591539d628a0SDimitry Andric   if (DisableStoreExtract || !TLI ||
591639d628a0SDimitry Andric       (!StressStoreExtract &&
591739d628a0SDimitry Andric        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
591839d628a0SDimitry Andric                                        Inst->getOperand(1), CombineCost)))
591939d628a0SDimitry Andric     return false;
592039d628a0SDimitry Andric 
592139d628a0SDimitry Andric   // At this point we know that Inst is a vector to scalar transition.
592239d628a0SDimitry Andric   // Try to move it down the def-use chain, until:
592339d628a0SDimitry Andric   // - We can combine the transition with its single use
592439d628a0SDimitry Andric   //   => we got rid of the transition.
592539d628a0SDimitry Andric   // - We escape the current basic block
592639d628a0SDimitry Andric   //   => we would need to check that we are moving it at a cheaper place and
592739d628a0SDimitry Andric   //      we do not do that for now.
592839d628a0SDimitry Andric   BasicBlock *Parent = Inst->getParent();
592939d628a0SDimitry Andric   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
5930875ed548SDimitry Andric   VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
593139d628a0SDimitry Andric   // If the transition has more than one use, assume this is not going to be
593239d628a0SDimitry Andric   // beneficial.
593339d628a0SDimitry Andric   while (Inst->hasOneUse()) {
593439d628a0SDimitry Andric     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
593539d628a0SDimitry Andric     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
593639d628a0SDimitry Andric 
593739d628a0SDimitry Andric     if (ToBePromoted->getParent() != Parent) {
593839d628a0SDimitry Andric       DEBUG(dbgs() << "Instruction to promote is in a different block ("
593939d628a0SDimitry Andric                    << ToBePromoted->getParent()->getName()
594039d628a0SDimitry Andric                    << ") than the transition (" << Parent->getName() << ").\n");
594139d628a0SDimitry Andric       return false;
594239d628a0SDimitry Andric     }
594339d628a0SDimitry Andric 
594439d628a0SDimitry Andric     if (VPH.canCombine(ToBePromoted)) {
594539d628a0SDimitry Andric       DEBUG(dbgs() << "Assume " << *Inst << '\n'
594639d628a0SDimitry Andric                    << "will be combined with: " << *ToBePromoted << '\n');
594739d628a0SDimitry Andric       VPH.recordCombineInstruction(ToBePromoted);
594839d628a0SDimitry Andric       bool Changed = VPH.promote();
594939d628a0SDimitry Andric       NumStoreExtractExposed += Changed;
595039d628a0SDimitry Andric       return Changed;
595139d628a0SDimitry Andric     }
595239d628a0SDimitry Andric 
595339d628a0SDimitry Andric     DEBUG(dbgs() << "Try promoting.\n");
595439d628a0SDimitry Andric     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
595539d628a0SDimitry Andric       return false;
595639d628a0SDimitry Andric 
595739d628a0SDimitry Andric     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
595839d628a0SDimitry Andric 
595939d628a0SDimitry Andric     VPH.enqueueForPromotion(ToBePromoted);
596039d628a0SDimitry Andric     Inst = ToBePromoted;
596139d628a0SDimitry Andric   }
596239d628a0SDimitry Andric   return false;
596339d628a0SDimitry Andric }
596439d628a0SDimitry Andric 
5965d88c1a5aSDimitry Andric /// For the instruction sequence of store below, F and I values
5966d88c1a5aSDimitry Andric /// are bundled together as an i64 value before being stored into memory.
5967d88c1a5aSDimitry Andric /// Sometimes it is more efficent to generate separate stores for F and I,
5968d88c1a5aSDimitry Andric /// which can remove the bitwise instructions or sink them to colder places.
5969d88c1a5aSDimitry Andric ///
5970d88c1a5aSDimitry Andric ///   (store (or (zext (bitcast F to i32) to i64),
5971d88c1a5aSDimitry Andric ///              (shl (zext I to i64), 32)), addr)  -->
5972d88c1a5aSDimitry Andric ///   (store F, addr) and (store I, addr+4)
5973d88c1a5aSDimitry Andric ///
5974d88c1a5aSDimitry Andric /// Similarly, splitting for other merged store can also be beneficial, like:
5975d88c1a5aSDimitry Andric /// For pair of {i32, i32}, i64 store --> two i32 stores.
5976d88c1a5aSDimitry Andric /// For pair of {i32, i16}, i64 store --> two i32 stores.
5977d88c1a5aSDimitry Andric /// For pair of {i16, i16}, i32 store --> two i16 stores.
5978d88c1a5aSDimitry Andric /// For pair of {i16, i8},  i32 store --> two i16 stores.
5979d88c1a5aSDimitry Andric /// For pair of {i8, i8},   i16 store --> two i8 stores.
5980d88c1a5aSDimitry Andric ///
5981d88c1a5aSDimitry Andric /// We allow each target to determine specifically which kind of splitting is
5982d88c1a5aSDimitry Andric /// supported.
5983d88c1a5aSDimitry Andric ///
5984d88c1a5aSDimitry Andric /// The store patterns are commonly seen from the simple code snippet below
5985d88c1a5aSDimitry Andric /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5986d88c1a5aSDimitry Andric ///   void goo(const std::pair<int, float> &);
5987d88c1a5aSDimitry Andric ///   hoo() {
5988d88c1a5aSDimitry Andric ///     ...
5989d88c1a5aSDimitry Andric ///     goo(std::make_pair(tmp, ftmp));
5990d88c1a5aSDimitry Andric ///     ...
5991d88c1a5aSDimitry Andric ///   }
5992d88c1a5aSDimitry Andric ///
5993d88c1a5aSDimitry Andric /// Although we already have similar splitting in DAG Combine, we duplicate
5994d88c1a5aSDimitry Andric /// it in CodeGenPrepare to catch the case in which pattern is across
5995d88c1a5aSDimitry Andric /// multiple BBs. The logic in DAG Combine is kept to catch case generated
5996d88c1a5aSDimitry Andric /// during code expansion.
5997d88c1a5aSDimitry Andric static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5998d88c1a5aSDimitry Andric                                 const TargetLowering &TLI) {
5999d88c1a5aSDimitry Andric   // Handle simple but common cases only.
6000d88c1a5aSDimitry Andric   Type *StoreType = SI.getValueOperand()->getType();
6001d88c1a5aSDimitry Andric   if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6002d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(StoreType) == 0)
6003d88c1a5aSDimitry Andric     return false;
6004d88c1a5aSDimitry Andric 
6005d88c1a5aSDimitry Andric   unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6006d88c1a5aSDimitry Andric   Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6007d88c1a5aSDimitry Andric   if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6008d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(SplitStoreType))
6009d88c1a5aSDimitry Andric     return false;
6010d88c1a5aSDimitry Andric 
6011d88c1a5aSDimitry Andric   // Match the following patterns:
6012d88c1a5aSDimitry Andric   // (store (or (zext LValue to i64),
6013d88c1a5aSDimitry Andric   //            (shl (zext HValue to i64), 32)), HalfValBitSize)
6014d88c1a5aSDimitry Andric   //  or
6015d88c1a5aSDimitry Andric   // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6016d88c1a5aSDimitry Andric   //            (zext LValue to i64),
6017d88c1a5aSDimitry Andric   // Expect both operands of OR and the first operand of SHL have only
6018d88c1a5aSDimitry Andric   // one use.
6019d88c1a5aSDimitry Andric   Value *LValue, *HValue;
6020d88c1a5aSDimitry Andric   if (!match(SI.getValueOperand(),
6021d88c1a5aSDimitry Andric              m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6022d88c1a5aSDimitry Andric                     m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6023d88c1a5aSDimitry Andric                                    m_SpecificInt(HalfValBitSize))))))
6024d88c1a5aSDimitry Andric     return false;
6025d88c1a5aSDimitry Andric 
6026d88c1a5aSDimitry Andric   // Check LValue and HValue are int with size less or equal than 32.
6027d88c1a5aSDimitry Andric   if (!LValue->getType()->isIntegerTy() ||
6028d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6029d88c1a5aSDimitry Andric       !HValue->getType()->isIntegerTy() ||
6030d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6031d88c1a5aSDimitry Andric     return false;
6032d88c1a5aSDimitry Andric 
6033d88c1a5aSDimitry Andric   // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6034d88c1a5aSDimitry Andric   // as the input of target query.
6035d88c1a5aSDimitry Andric   auto *LBC = dyn_cast<BitCastInst>(LValue);
6036d88c1a5aSDimitry Andric   auto *HBC = dyn_cast<BitCastInst>(HValue);
6037d88c1a5aSDimitry Andric   EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6038d88c1a5aSDimitry Andric                   : EVT::getEVT(LValue->getType());
6039d88c1a5aSDimitry Andric   EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6040d88c1a5aSDimitry Andric                    : EVT::getEVT(HValue->getType());
6041d88c1a5aSDimitry Andric   if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6042d88c1a5aSDimitry Andric     return false;
6043d88c1a5aSDimitry Andric 
6044d88c1a5aSDimitry Andric   // Start to split store.
6045d88c1a5aSDimitry Andric   IRBuilder<> Builder(SI.getContext());
6046d88c1a5aSDimitry Andric   Builder.SetInsertPoint(&SI);
6047d88c1a5aSDimitry Andric 
6048d88c1a5aSDimitry Andric   // If LValue/HValue is a bitcast in another BB, create a new one in current
6049d88c1a5aSDimitry Andric   // BB so it may be merged with the splitted stores by dag combiner.
6050d88c1a5aSDimitry Andric   if (LBC && LBC->getParent() != SI.getParent())
6051d88c1a5aSDimitry Andric     LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6052d88c1a5aSDimitry Andric   if (HBC && HBC->getParent() != SI.getParent())
6053d88c1a5aSDimitry Andric     HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6054d88c1a5aSDimitry Andric 
6055d88c1a5aSDimitry Andric   auto CreateSplitStore = [&](Value *V, bool Upper) {
6056d88c1a5aSDimitry Andric     V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6057d88c1a5aSDimitry Andric     Value *Addr = Builder.CreateBitCast(
6058d88c1a5aSDimitry Andric         SI.getOperand(1),
6059d88c1a5aSDimitry Andric         SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6060d88c1a5aSDimitry Andric     if (Upper)
6061d88c1a5aSDimitry Andric       Addr = Builder.CreateGEP(
6062d88c1a5aSDimitry Andric           SplitStoreType, Addr,
6063d88c1a5aSDimitry Andric           ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6064d88c1a5aSDimitry Andric     Builder.CreateAlignedStore(
6065d88c1a5aSDimitry Andric         V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6066d88c1a5aSDimitry Andric   };
6067d88c1a5aSDimitry Andric 
6068d88c1a5aSDimitry Andric   CreateSplitStore(LValue, false);
6069d88c1a5aSDimitry Andric   CreateSplitStore(HValue, true);
6070d88c1a5aSDimitry Andric 
6071d88c1a5aSDimitry Andric   // Delete the old store.
6072d88c1a5aSDimitry Andric   SI.eraseFromParent();
6073d88c1a5aSDimitry Andric   return true;
6074d88c1a5aSDimitry Andric }
6075d88c1a5aSDimitry Andric 
60767d523365SDimitry Andric bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
60778f0fd8f6SDimitry Andric   // Bail out if we inserted the instruction to prevent optimizations from
60788f0fd8f6SDimitry Andric   // stepping on each other's toes.
60798f0fd8f6SDimitry Andric   if (InsertedInsts.count(I))
60808f0fd8f6SDimitry Andric     return false;
60818f0fd8f6SDimitry Andric 
608291bc56edSDimitry Andric   if (PHINode *P = dyn_cast<PHINode>(I)) {
608391bc56edSDimitry Andric     // It is possible for very late stage optimizations (such as SimplifyCFG)
608491bc56edSDimitry Andric     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
608591bc56edSDimitry Andric     // trivial PHI, go ahead and zap it here.
6086f37b6182SDimitry Andric     if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
608791bc56edSDimitry Andric       P->replaceAllUsesWith(V);
608891bc56edSDimitry Andric       P->eraseFromParent();
608991bc56edSDimitry Andric       ++NumPHIsElim;
609091bc56edSDimitry Andric       return true;
609191bc56edSDimitry Andric     }
609291bc56edSDimitry Andric     return false;
609391bc56edSDimitry Andric   }
609491bc56edSDimitry Andric 
609591bc56edSDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
609691bc56edSDimitry Andric     // If the source of the cast is a constant, then this should have
609791bc56edSDimitry Andric     // already been constant folded.  The only reason NOT to constant fold
609891bc56edSDimitry Andric     // it is if something (e.g. LSR) was careful to place the constant
609991bc56edSDimitry Andric     // evaluation in a block other than then one that uses it (e.g. to hoist
610091bc56edSDimitry Andric     // the address of globals out of a loop).  If this is the case, we don't
610191bc56edSDimitry Andric     // want to forward-subst the cast.
610291bc56edSDimitry Andric     if (isa<Constant>(CI->getOperand(0)))
610391bc56edSDimitry Andric       return false;
610491bc56edSDimitry Andric 
6105875ed548SDimitry Andric     if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
610691bc56edSDimitry Andric       return true;
610791bc56edSDimitry Andric 
610891bc56edSDimitry Andric     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
610991bc56edSDimitry Andric       /// Sink a zext or sext into its user blocks if the target type doesn't
611091bc56edSDimitry Andric       /// fit in one register
6111875ed548SDimitry Andric       if (TLI &&
6112875ed548SDimitry Andric           TLI->getTypeAction(CI->getContext(),
6113875ed548SDimitry Andric                              TLI->getValueType(*DL, CI->getType())) ==
611491bc56edSDimitry Andric               TargetLowering::TypeExpandInteger) {
611591bc56edSDimitry Andric         return SinkCast(CI);
611691bc56edSDimitry Andric       } else {
61177a7e6055SDimitry Andric         bool MadeChange = optimizeExt(I);
61187d523365SDimitry Andric         return MadeChange | optimizeExtUses(I);
611991bc56edSDimitry Andric       }
612091bc56edSDimitry Andric     }
612191bc56edSDimitry Andric     return false;
612291bc56edSDimitry Andric   }
612391bc56edSDimitry Andric 
612491bc56edSDimitry Andric   if (CmpInst *CI = dyn_cast<CmpInst>(I))
612591bc56edSDimitry Andric     if (!TLI || !TLI->hasMultipleConditionRegisters())
61263ca95b02SDimitry Andric       return OptimizeCmpExpression(CI, TLI);
612791bc56edSDimitry Andric 
612891bc56edSDimitry Andric   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6129d88c1a5aSDimitry Andric     LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
613097bc6c73SDimitry Andric     if (TLI) {
61317d523365SDimitry Andric       bool Modified = optimizeLoadExt(LI);
613297bc6c73SDimitry Andric       unsigned AS = LI->getPointerAddressSpace();
61337d523365SDimitry Andric       Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
61347d523365SDimitry Andric       return Modified;
613597bc6c73SDimitry Andric     }
613691bc56edSDimitry Andric     return false;
613791bc56edSDimitry Andric   }
613891bc56edSDimitry Andric 
613991bc56edSDimitry Andric   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6140d88c1a5aSDimitry Andric     if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6141d88c1a5aSDimitry Andric       return true;
6142d88c1a5aSDimitry Andric     SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
614397bc6c73SDimitry Andric     if (TLI) {
614497bc6c73SDimitry Andric       unsigned AS = SI->getPointerAddressSpace();
61457d523365SDimitry Andric       return optimizeMemoryInst(I, SI->getOperand(1),
614697bc6c73SDimitry Andric                                 SI->getOperand(0)->getType(), AS);
614797bc6c73SDimitry Andric     }
614891bc56edSDimitry Andric     return false;
614991bc56edSDimitry Andric   }
615091bc56edSDimitry Andric 
61517a7e6055SDimitry Andric   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
61527a7e6055SDimitry Andric       unsigned AS = RMW->getPointerAddressSpace();
61537a7e6055SDimitry Andric       return optimizeMemoryInst(I, RMW->getPointerOperand(),
61547a7e6055SDimitry Andric                                 RMW->getType(), AS);
61557a7e6055SDimitry Andric   }
61567a7e6055SDimitry Andric 
61577a7e6055SDimitry Andric   if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
61587a7e6055SDimitry Andric       unsigned AS = CmpX->getPointerAddressSpace();
61597a7e6055SDimitry Andric       return optimizeMemoryInst(I, CmpX->getPointerOperand(),
61607a7e6055SDimitry Andric                                 CmpX->getCompareOperand()->getType(), AS);
61617a7e6055SDimitry Andric   }
61627a7e6055SDimitry Andric 
616391bc56edSDimitry Andric   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
616491bc56edSDimitry Andric 
61657a7e6055SDimitry Andric   if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
61667a7e6055SDimitry Andric       EnableAndCmpSinking && TLI)
61677a7e6055SDimitry Andric     return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
61687a7e6055SDimitry Andric 
616991bc56edSDimitry Andric   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
617091bc56edSDimitry Andric                 BinOp->getOpcode() == Instruction::LShr)) {
617191bc56edSDimitry Andric     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
617291bc56edSDimitry Andric     if (TLI && CI && TLI->hasExtractBitsInsn())
6173875ed548SDimitry Andric       return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
617491bc56edSDimitry Andric 
617591bc56edSDimitry Andric     return false;
617691bc56edSDimitry Andric   }
617791bc56edSDimitry Andric 
617891bc56edSDimitry Andric   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
617991bc56edSDimitry Andric     if (GEPI->hasAllZeroIndices()) {
618091bc56edSDimitry Andric       /// The GEP operand must be a pointer, so must its result -> BitCast
618191bc56edSDimitry Andric       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
618291bc56edSDimitry Andric                                         GEPI->getName(), GEPI);
618391bc56edSDimitry Andric       GEPI->replaceAllUsesWith(NC);
618491bc56edSDimitry Andric       GEPI->eraseFromParent();
618591bc56edSDimitry Andric       ++NumGEPsElim;
61867d523365SDimitry Andric       optimizeInst(NC, ModifiedDT);
618791bc56edSDimitry Andric       return true;
618891bc56edSDimitry Andric     }
618991bc56edSDimitry Andric     return false;
619091bc56edSDimitry Andric   }
619191bc56edSDimitry Andric 
619291bc56edSDimitry Andric   if (CallInst *CI = dyn_cast<CallInst>(I))
61937d523365SDimitry Andric     return optimizeCallInst(CI, ModifiedDT);
619491bc56edSDimitry Andric 
619591bc56edSDimitry Andric   if (SelectInst *SI = dyn_cast<SelectInst>(I))
61967d523365SDimitry Andric     return optimizeSelectInst(SI);
619791bc56edSDimitry Andric 
619891bc56edSDimitry Andric   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
61997d523365SDimitry Andric     return optimizeShuffleVectorInst(SVI);
62007d523365SDimitry Andric 
62017d523365SDimitry Andric   if (auto *Switch = dyn_cast<SwitchInst>(I))
62027d523365SDimitry Andric     return optimizeSwitchInst(Switch);
620391bc56edSDimitry Andric 
620439d628a0SDimitry Andric   if (isa<ExtractElementInst>(I))
62057d523365SDimitry Andric     return optimizeExtractElementInst(I);
620639d628a0SDimitry Andric 
620791bc56edSDimitry Andric   return false;
620891bc56edSDimitry Andric }
620991bc56edSDimitry Andric 
62108c24ff90SDimitry Andric /// Given an OR instruction, check to see if this is a bitreverse
62118c24ff90SDimitry Andric /// idiom. If so, insert the new intrinsic and return true.
62128c24ff90SDimitry Andric static bool makeBitReverse(Instruction &I, const DataLayout &DL,
62138c24ff90SDimitry Andric                            const TargetLowering &TLI) {
62148c24ff90SDimitry Andric   if (!I.getType()->isIntegerTy() ||
62158c24ff90SDimitry Andric       !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
62168c24ff90SDimitry Andric                                     TLI.getValueType(DL, I.getType(), true)))
62178c24ff90SDimitry Andric     return false;
62188c24ff90SDimitry Andric 
62198c24ff90SDimitry Andric   SmallVector<Instruction*, 4> Insts;
62203ca95b02SDimitry Andric   if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
62218c24ff90SDimitry Andric     return false;
62228c24ff90SDimitry Andric   Instruction *LastInst = Insts.back();
62238c24ff90SDimitry Andric   I.replaceAllUsesWith(LastInst);
62248c24ff90SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(&I);
62258c24ff90SDimitry Andric   return true;
62268c24ff90SDimitry Andric }
62278c24ff90SDimitry Andric 
622891bc56edSDimitry Andric // In this pass we look for GEP and cast instructions that are used
622991bc56edSDimitry Andric // across basic blocks and rewrite them to improve basic-block-at-a-time
623091bc56edSDimitry Andric // selection.
62317d523365SDimitry Andric bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
623291bc56edSDimitry Andric   SunkAddrs.clear();
623391bc56edSDimitry Andric   bool MadeChange = false;
623491bc56edSDimitry Andric 
623591bc56edSDimitry Andric   CurInstIterator = BB.begin();
623639d628a0SDimitry Andric   while (CurInstIterator != BB.end()) {
62377d523365SDimitry Andric     MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
623839d628a0SDimitry Andric     if (ModifiedDT)
623939d628a0SDimitry Andric       return true;
624039d628a0SDimitry Andric   }
62418c24ff90SDimitry Andric 
62428c24ff90SDimitry Andric   bool MadeBitReverse = true;
62438c24ff90SDimitry Andric   while (TLI && MadeBitReverse) {
62448c24ff90SDimitry Andric     MadeBitReverse = false;
62458c24ff90SDimitry Andric     for (auto &I : reverse(BB)) {
62468c24ff90SDimitry Andric       if (makeBitReverse(I, *DL, *TLI)) {
62478c24ff90SDimitry Andric         MadeBitReverse = MadeChange = true;
62483ca95b02SDimitry Andric         ModifiedDT = true;
62498c24ff90SDimitry Andric         break;
62508c24ff90SDimitry Andric       }
62518c24ff90SDimitry Andric     }
62528c24ff90SDimitry Andric   }
62537d523365SDimitry Andric   MadeChange |= dupRetToEnableTailCallOpts(&BB);
625491bc56edSDimitry Andric 
625591bc56edSDimitry Andric   return MadeChange;
625691bc56edSDimitry Andric }
625791bc56edSDimitry Andric 
625891bc56edSDimitry Andric // llvm.dbg.value is far away from the value then iSel may not be able
625991bc56edSDimitry Andric // handle it properly. iSel will drop llvm.dbg.value if it can not
626091bc56edSDimitry Andric // find a node corresponding to the value.
62617d523365SDimitry Andric bool CodeGenPrepare::placeDbgValues(Function &F) {
626291bc56edSDimitry Andric   bool MadeChange = false;
626339d628a0SDimitry Andric   for (BasicBlock &BB : F) {
626491bc56edSDimitry Andric     Instruction *PrevNonDbgInst = nullptr;
626539d628a0SDimitry Andric     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
62667d523365SDimitry Andric       Instruction *Insn = &*BI++;
626791bc56edSDimitry Andric       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
626891bc56edSDimitry Andric       // Leave dbg.values that refer to an alloca alone. These
626991bc56edSDimitry Andric       // instrinsics describe the address of a variable (= the alloca)
627091bc56edSDimitry Andric       // being taken.  They should not be moved next to the alloca
627191bc56edSDimitry Andric       // (and to the beginning of the scope), but rather stay close to
627291bc56edSDimitry Andric       // where said address is used.
627391bc56edSDimitry Andric       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
627491bc56edSDimitry Andric         PrevNonDbgInst = Insn;
627591bc56edSDimitry Andric         continue;
627691bc56edSDimitry Andric       }
627791bc56edSDimitry Andric 
627891bc56edSDimitry Andric       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
627991bc56edSDimitry Andric       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
62807d523365SDimitry Andric         // If VI is a phi in a block with an EHPad terminator, we can't insert
62817d523365SDimitry Andric         // after it.
62827d523365SDimitry Andric         if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
62837d523365SDimitry Andric           continue;
628491bc56edSDimitry Andric         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
628591bc56edSDimitry Andric         DVI->removeFromParent();
628691bc56edSDimitry Andric         if (isa<PHINode>(VI))
62877d523365SDimitry Andric           DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
628891bc56edSDimitry Andric         else
628991bc56edSDimitry Andric           DVI->insertAfter(VI);
629091bc56edSDimitry Andric         MadeChange = true;
629191bc56edSDimitry Andric         ++NumDbgValueMoved;
629291bc56edSDimitry Andric       }
629391bc56edSDimitry Andric     }
629491bc56edSDimitry Andric   }
629591bc56edSDimitry Andric   return MadeChange;
629691bc56edSDimitry Andric }
629791bc56edSDimitry Andric 
629839d628a0SDimitry Andric /// \brief Scale down both weights to fit into uint32_t.
629939d628a0SDimitry Andric static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
630039d628a0SDimitry Andric   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
630139d628a0SDimitry Andric   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
630239d628a0SDimitry Andric   NewTrue = NewTrue / Scale;
630339d628a0SDimitry Andric   NewFalse = NewFalse / Scale;
630439d628a0SDimitry Andric }
630539d628a0SDimitry Andric 
630639d628a0SDimitry Andric /// \brief Some targets prefer to split a conditional branch like:
630739d628a0SDimitry Andric /// \code
630839d628a0SDimitry Andric ///   %0 = icmp ne i32 %a, 0
630939d628a0SDimitry Andric ///   %1 = icmp ne i32 %b, 0
631039d628a0SDimitry Andric ///   %or.cond = or i1 %0, %1
631139d628a0SDimitry Andric ///   br i1 %or.cond, label %TrueBB, label %FalseBB
631239d628a0SDimitry Andric /// \endcode
631339d628a0SDimitry Andric /// into multiple branch instructions like:
631439d628a0SDimitry Andric /// \code
631539d628a0SDimitry Andric ///   bb1:
631639d628a0SDimitry Andric ///     %0 = icmp ne i32 %a, 0
631739d628a0SDimitry Andric ///     br i1 %0, label %TrueBB, label %bb2
631839d628a0SDimitry Andric ///   bb2:
631939d628a0SDimitry Andric ///     %1 = icmp ne i32 %b, 0
632039d628a0SDimitry Andric ///     br i1 %1, label %TrueBB, label %FalseBB
632139d628a0SDimitry Andric /// \endcode
632239d628a0SDimitry Andric /// This usually allows instruction selection to do even further optimizations
632339d628a0SDimitry Andric /// and combine the compare with the branch instruction. Currently this is
632439d628a0SDimitry Andric /// applied for targets which have "cheap" jump instructions.
632539d628a0SDimitry Andric ///
632639d628a0SDimitry Andric /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
632739d628a0SDimitry Andric ///
632839d628a0SDimitry Andric bool CodeGenPrepare::splitBranchCondition(Function &F) {
6329ff0cc061SDimitry Andric   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
633039d628a0SDimitry Andric     return false;
633139d628a0SDimitry Andric 
633239d628a0SDimitry Andric   bool MadeChange = false;
633339d628a0SDimitry Andric   for (auto &BB : F) {
633439d628a0SDimitry Andric     // Does this BB end with the following?
633539d628a0SDimitry Andric     //   %cond1 = icmp|fcmp|binary instruction ...
633639d628a0SDimitry Andric     //   %cond2 = icmp|fcmp|binary instruction ...
633739d628a0SDimitry Andric     //   %cond.or = or|and i1 %cond1, cond2
633839d628a0SDimitry Andric     //   br i1 %cond.or label %dest1, label %dest2"
633939d628a0SDimitry Andric     BinaryOperator *LogicOp;
634039d628a0SDimitry Andric     BasicBlock *TBB, *FBB;
634139d628a0SDimitry Andric     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
634239d628a0SDimitry Andric       continue;
634339d628a0SDimitry Andric 
63447d523365SDimitry Andric     auto *Br1 = cast<BranchInst>(BB.getTerminator());
63457d523365SDimitry Andric     if (Br1->getMetadata(LLVMContext::MD_unpredictable))
63467d523365SDimitry Andric       continue;
63477d523365SDimitry Andric 
634839d628a0SDimitry Andric     unsigned Opc;
634939d628a0SDimitry Andric     Value *Cond1, *Cond2;
635039d628a0SDimitry Andric     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
635139d628a0SDimitry Andric                              m_OneUse(m_Value(Cond2)))))
635239d628a0SDimitry Andric       Opc = Instruction::And;
635339d628a0SDimitry Andric     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
635439d628a0SDimitry Andric                                  m_OneUse(m_Value(Cond2)))))
635539d628a0SDimitry Andric       Opc = Instruction::Or;
635639d628a0SDimitry Andric     else
635739d628a0SDimitry Andric       continue;
635839d628a0SDimitry Andric 
635939d628a0SDimitry Andric     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
636039d628a0SDimitry Andric         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
636139d628a0SDimitry Andric       continue;
636239d628a0SDimitry Andric 
636339d628a0SDimitry Andric     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
636439d628a0SDimitry Andric 
636539d628a0SDimitry Andric     // Create a new BB.
63663ca95b02SDimitry Andric     auto TmpBB =
63673ca95b02SDimitry Andric         BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
63683ca95b02SDimitry Andric                            BB.getParent(), BB.getNextNode());
636939d628a0SDimitry Andric 
637039d628a0SDimitry Andric     // Update original basic block by using the first condition directly by the
637139d628a0SDimitry Andric     // branch instruction and removing the no longer needed and/or instruction.
637239d628a0SDimitry Andric     Br1->setCondition(Cond1);
637339d628a0SDimitry Andric     LogicOp->eraseFromParent();
637439d628a0SDimitry Andric 
637539d628a0SDimitry Andric     // Depending on the conditon we have to either replace the true or the false
637639d628a0SDimitry Andric     // successor of the original branch instruction.
637739d628a0SDimitry Andric     if (Opc == Instruction::And)
637839d628a0SDimitry Andric       Br1->setSuccessor(0, TmpBB);
637939d628a0SDimitry Andric     else
638039d628a0SDimitry Andric       Br1->setSuccessor(1, TmpBB);
638139d628a0SDimitry Andric 
638239d628a0SDimitry Andric     // Fill in the new basic block.
638339d628a0SDimitry Andric     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
638439d628a0SDimitry Andric     if (auto *I = dyn_cast<Instruction>(Cond2)) {
638539d628a0SDimitry Andric       I->removeFromParent();
638639d628a0SDimitry Andric       I->insertBefore(Br2);
638739d628a0SDimitry Andric     }
638839d628a0SDimitry Andric 
638939d628a0SDimitry Andric     // Update PHI nodes in both successors. The original BB needs to be
6390a580b014SDimitry Andric     // replaced in one successor's PHI nodes, because the branch comes now from
639139d628a0SDimitry Andric     // the newly generated BB (NewBB). In the other successor we need to add one
639239d628a0SDimitry Andric     // incoming edge to the PHI nodes, because both branch instructions target
639339d628a0SDimitry Andric     // now the same successor. Depending on the original branch condition
639439d628a0SDimitry Andric     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6395d88c1a5aSDimitry Andric     // we perform the correct update for the PHI nodes.
639639d628a0SDimitry Andric     // This doesn't change the successor order of the just created branch
639739d628a0SDimitry Andric     // instruction (or any other instruction).
639839d628a0SDimitry Andric     if (Opc == Instruction::Or)
639939d628a0SDimitry Andric       std::swap(TBB, FBB);
640039d628a0SDimitry Andric 
640139d628a0SDimitry Andric     // Replace the old BB with the new BB.
640239d628a0SDimitry Andric     for (auto &I : *TBB) {
640339d628a0SDimitry Andric       PHINode *PN = dyn_cast<PHINode>(&I);
640439d628a0SDimitry Andric       if (!PN)
640539d628a0SDimitry Andric         break;
640639d628a0SDimitry Andric       int i;
640739d628a0SDimitry Andric       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
640839d628a0SDimitry Andric         PN->setIncomingBlock(i, TmpBB);
640939d628a0SDimitry Andric     }
641039d628a0SDimitry Andric 
641139d628a0SDimitry Andric     // Add another incoming edge form the new BB.
641239d628a0SDimitry Andric     for (auto &I : *FBB) {
641339d628a0SDimitry Andric       PHINode *PN = dyn_cast<PHINode>(&I);
641439d628a0SDimitry Andric       if (!PN)
641539d628a0SDimitry Andric         break;
641639d628a0SDimitry Andric       auto *Val = PN->getIncomingValueForBlock(&BB);
641739d628a0SDimitry Andric       PN->addIncoming(Val, TmpBB);
641839d628a0SDimitry Andric     }
641939d628a0SDimitry Andric 
642039d628a0SDimitry Andric     // Update the branch weights (from SelectionDAGBuilder::
642139d628a0SDimitry Andric     // FindMergedConditions).
642239d628a0SDimitry Andric     if (Opc == Instruction::Or) {
642339d628a0SDimitry Andric       // Codegen X | Y as:
642439d628a0SDimitry Andric       // BB1:
642539d628a0SDimitry Andric       //   jmp_if_X TBB
642639d628a0SDimitry Andric       //   jmp TmpBB
642739d628a0SDimitry Andric       // TmpBB:
642839d628a0SDimitry Andric       //   jmp_if_Y TBB
642939d628a0SDimitry Andric       //   jmp FBB
643039d628a0SDimitry Andric       //
643139d628a0SDimitry Andric 
643239d628a0SDimitry Andric       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
643339d628a0SDimitry Andric       // The requirement is that
643439d628a0SDimitry Andric       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
643539d628a0SDimitry Andric       //     = TrueProb for orignal BB.
643639d628a0SDimitry Andric       // Assuming the orignal weights are A and B, one choice is to set BB1's
643739d628a0SDimitry Andric       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
643839d628a0SDimitry Andric       // assumes that
643939d628a0SDimitry Andric       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
644039d628a0SDimitry Andric       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
644139d628a0SDimitry Andric       // TmpBB, but the math is more complicated.
644239d628a0SDimitry Andric       uint64_t TrueWeight, FalseWeight;
64433ca95b02SDimitry Andric       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
644439d628a0SDimitry Andric         uint64_t NewTrueWeight = TrueWeight;
644539d628a0SDimitry Andric         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
644639d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
644739d628a0SDimitry Andric         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
644839d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
644939d628a0SDimitry Andric 
645039d628a0SDimitry Andric         NewTrueWeight = TrueWeight;
645139d628a0SDimitry Andric         NewFalseWeight = 2 * FalseWeight;
645239d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
645339d628a0SDimitry Andric         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
645439d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
645539d628a0SDimitry Andric       }
645639d628a0SDimitry Andric     } else {
645739d628a0SDimitry Andric       // Codegen X & Y as:
645839d628a0SDimitry Andric       // BB1:
645939d628a0SDimitry Andric       //   jmp_if_X TmpBB
646039d628a0SDimitry Andric       //   jmp FBB
646139d628a0SDimitry Andric       // TmpBB:
646239d628a0SDimitry Andric       //   jmp_if_Y TBB
646339d628a0SDimitry Andric       //   jmp FBB
646439d628a0SDimitry Andric       //
646539d628a0SDimitry Andric       //  This requires creation of TmpBB after CurBB.
646639d628a0SDimitry Andric 
646739d628a0SDimitry Andric       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
646839d628a0SDimitry Andric       // The requirement is that
646939d628a0SDimitry Andric       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
647039d628a0SDimitry Andric       //     = FalseProb for orignal BB.
647139d628a0SDimitry Andric       // Assuming the orignal weights are A and B, one choice is to set BB1's
647239d628a0SDimitry Andric       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
647339d628a0SDimitry Andric       // assumes that
647439d628a0SDimitry Andric       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
647539d628a0SDimitry Andric       uint64_t TrueWeight, FalseWeight;
64763ca95b02SDimitry Andric       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
647739d628a0SDimitry Andric         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
647839d628a0SDimitry Andric         uint64_t NewFalseWeight = FalseWeight;
647939d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
648039d628a0SDimitry Andric         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
648139d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
648239d628a0SDimitry Andric 
648339d628a0SDimitry Andric         NewTrueWeight = 2 * TrueWeight;
648439d628a0SDimitry Andric         NewFalseWeight = FalseWeight;
648539d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
648639d628a0SDimitry Andric         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
648739d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
648839d628a0SDimitry Andric       }
648939d628a0SDimitry Andric     }
649039d628a0SDimitry Andric 
649139d628a0SDimitry Andric     // Note: No point in getting fancy here, since the DT info is never
6492ff0cc061SDimitry Andric     // available to CodeGenPrepare.
649339d628a0SDimitry Andric     ModifiedDT = true;
649439d628a0SDimitry Andric 
649539d628a0SDimitry Andric     MadeChange = true;
649639d628a0SDimitry Andric 
649739d628a0SDimitry Andric     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
649839d628a0SDimitry Andric           TmpBB->dump());
649939d628a0SDimitry Andric   }
650039d628a0SDimitry Andric   return MadeChange;
650139d628a0SDimitry Andric }
6502