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;
1665db17bf38SDimitry Andric 
1666edd7eaddSDimitry Andric   unsigned calculateNumBlocks(unsigned Size);
1667f9448bf3SDimitry Andric   void createLoadCmpBlocks();
1668f9448bf3SDimitry Andric   void createResultBlock();
1669f9448bf3SDimitry Andric   void setupResultBlockPHINodes();
1670f9448bf3SDimitry Andric   void setupEndBlockPHINodes();
1671edd7eaddSDimitry Andric   void emitLoadCompareBlock(unsigned Index, unsigned LoadSize,
1672edd7eaddSDimitry Andric                             unsigned GEPIndex);
1673db17bf38SDimitry Andric   Value *getCompareLoadPairs(unsigned Index, unsigned Size,
1674db17bf38SDimitry Andric                              unsigned &NumBytesProcessed, IRBuilder<> &Builder);
1675f9448bf3SDimitry Andric   void emitLoadCompareBlockMultipleLoads(unsigned Index, unsigned Size,
1676f9448bf3SDimitry Andric                                          unsigned &NumBytesProcessed);
1677edd7eaddSDimitry Andric   void emitLoadCompareByteBlock(unsigned Index, unsigned GEPIndex);
1678db17bf38SDimitry Andric   void emitMemCmpResultBlock();
1679db17bf38SDimitry Andric   Value *getMemCmpExpansionZeroCase(unsigned Size);
1680db17bf38SDimitry Andric   Value *getMemCmpEqZeroOneBlock(unsigned Size);
1681f9448bf3SDimitry Andric   unsigned getLoadSize(unsigned Size);
1682f9448bf3SDimitry Andric   unsigned getNumLoads(unsigned Size);
1683f9448bf3SDimitry Andric 
1684f9448bf3SDimitry Andric public:
1685db17bf38SDimitry Andric   MemCmpExpansion(CallInst *CI, uint64_t Size, unsigned MaxLoadSize,
1686db17bf38SDimitry Andric                   unsigned NumLoadsPerBlock, const DataLayout &DL);
1687db17bf38SDimitry Andric   Value *getMemCmpExpansion(uint64_t Size);
1688f9448bf3SDimitry Andric };
1689f9448bf3SDimitry Andric 
1690f9448bf3SDimitry Andric MemCmpExpansion::ResultBlock::ResultBlock()
1691f9448bf3SDimitry Andric     : BB(nullptr), PhiSrc1(nullptr), PhiSrc2(nullptr) {}
1692f9448bf3SDimitry Andric 
1693f9448bf3SDimitry Andric // Initialize the basic block structure required for expansion of memcmp call
1694f9448bf3SDimitry Andric // with given maximum load size and memcmp size parameter.
1695f9448bf3SDimitry Andric // This structure includes:
1696f9448bf3SDimitry Andric // 1. A list of load compare blocks - LoadCmpBlocks.
1697f9448bf3SDimitry Andric // 2. An EndBlock, split from original instruction point, which is the block to
1698f9448bf3SDimitry Andric // return from.
1699f9448bf3SDimitry Andric // 3. ResultBlock, block to branch to for early exit when a
1700f9448bf3SDimitry Andric // LoadCmpBlock finds a difference.
1701db17bf38SDimitry Andric MemCmpExpansion::MemCmpExpansion(CallInst *CI, uint64_t Size,
1702db17bf38SDimitry Andric                                  unsigned MaxLoadSize, unsigned LoadsPerBlock,
1703db17bf38SDimitry Andric                                  const DataLayout &TheDataLayout)
1704db17bf38SDimitry Andric     : CI(CI), MaxLoadSize(MaxLoadSize), NumLoadsPerBlock(LoadsPerBlock),
1705db17bf38SDimitry Andric       DL(TheDataLayout) {
1706f9448bf3SDimitry Andric 
1707db17bf38SDimitry Andric   // A memcmp with zero-comparison with only one block of load and compare does
1708db17bf38SDimitry Andric   // not need to set up any extra blocks. This case could be handled in the DAG,
1709db17bf38SDimitry Andric   // but since we have all of the machinery to flexibly expand any memcpy here,
1710db17bf38SDimitry Andric   // we choose to handle this case too to avoid fragmented lowering.
1711db17bf38SDimitry Andric   IsUsedForZeroCmp = isOnlyUsedInZeroEqualityComparison(CI);
1712db17bf38SDimitry Andric   NumBlocks = calculateNumBlocks(Size);
1713db17bf38SDimitry Andric   if (!IsUsedForZeroCmp || NumBlocks != 1) {
1714f9448bf3SDimitry Andric     BasicBlock *StartBlock = CI->getParent();
1715f9448bf3SDimitry Andric     EndBlock = StartBlock->splitBasicBlock(CI, "endblock");
1716f9448bf3SDimitry Andric     setupEndBlockPHINodes();
1717f9448bf3SDimitry Andric     createResultBlock();
1718f9448bf3SDimitry Andric 
1719f9448bf3SDimitry Andric     // If return value of memcmp is not used in a zero equality, we need to
1720f9448bf3SDimitry Andric     // calculate which source was larger. The calculation requires the
1721f9448bf3SDimitry Andric     // two loaded source values of each load compare block.
1722f9448bf3SDimitry Andric     // These will be saved in the phi nodes created by setupResultBlockPHINodes.
1723f9448bf3SDimitry Andric     if (!IsUsedForZeroCmp)
1724f9448bf3SDimitry Andric       setupResultBlockPHINodes();
1725f9448bf3SDimitry Andric 
1726f9448bf3SDimitry Andric     // Create the number of required load compare basic blocks.
1727f9448bf3SDimitry Andric     createLoadCmpBlocks();
1728f9448bf3SDimitry Andric 
1729f9448bf3SDimitry Andric     // Update the terminator added by splitBasicBlock to branch to the first
1730f9448bf3SDimitry Andric     // LoadCmpBlock.
1731f9448bf3SDimitry Andric     StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]);
1732f9448bf3SDimitry Andric   }
1733f9448bf3SDimitry Andric 
1734db17bf38SDimitry Andric   IRBuilder<> Builder(CI->getContext());
1735db17bf38SDimitry Andric   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1736db17bf38SDimitry Andric }
1737db17bf38SDimitry Andric 
1738f9448bf3SDimitry Andric void MemCmpExpansion::createLoadCmpBlocks() {
1739f9448bf3SDimitry Andric   for (unsigned i = 0; i < NumBlocks; i++) {
1740f9448bf3SDimitry Andric     BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
1741f9448bf3SDimitry Andric                                         EndBlock->getParent(), EndBlock);
1742f9448bf3SDimitry Andric     LoadCmpBlocks.push_back(BB);
1743f9448bf3SDimitry Andric   }
1744f9448bf3SDimitry Andric }
1745f9448bf3SDimitry Andric 
1746f9448bf3SDimitry Andric void MemCmpExpansion::createResultBlock() {
1747f9448bf3SDimitry Andric   ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
1748f9448bf3SDimitry Andric                                    EndBlock->getParent(), EndBlock);
1749f9448bf3SDimitry Andric }
1750f9448bf3SDimitry Andric 
1751f9448bf3SDimitry Andric // This function creates the IR instructions for loading and comparing 1 byte.
1752db17bf38SDimitry Andric // It loads 1 byte from each source of the memcmp parameters with the given
1753f9448bf3SDimitry Andric // GEPIndex. It then subtracts the two loaded values and adds this result to the
1754f9448bf3SDimitry Andric // final phi node for selecting the memcmp result.
1755edd7eaddSDimitry Andric void MemCmpExpansion::emitLoadCompareByteBlock(unsigned Index,
1756edd7eaddSDimitry Andric                                                unsigned GEPIndex) {
1757f9448bf3SDimitry Andric   IRBuilder<> Builder(CI->getContext());
1758f9448bf3SDimitry Andric 
1759f9448bf3SDimitry Andric   Value *Source1 = CI->getArgOperand(0);
1760f9448bf3SDimitry Andric   Value *Source2 = CI->getArgOperand(1);
1761f9448bf3SDimitry Andric 
1762f9448bf3SDimitry Andric   Builder.SetInsertPoint(LoadCmpBlocks[Index]);
1763f9448bf3SDimitry Andric   Type *LoadSizeType = Type::getInt8Ty(CI->getContext());
1764db17bf38SDimitry Andric   // Cast source to LoadSizeType*.
1765f9448bf3SDimitry Andric   if (Source1->getType() != LoadSizeType)
1766f9448bf3SDimitry Andric     Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1767f9448bf3SDimitry Andric   if (Source2->getType() != LoadSizeType)
1768f9448bf3SDimitry Andric     Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1769f9448bf3SDimitry Andric 
1770db17bf38SDimitry Andric   // Get the base address using the GEPIndex.
1771f9448bf3SDimitry Andric   if (GEPIndex != 0) {
1772f9448bf3SDimitry Andric     Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1773f9448bf3SDimitry Andric                                 ConstantInt::get(LoadSizeType, GEPIndex));
1774f9448bf3SDimitry Andric     Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1775f9448bf3SDimitry Andric                                 ConstantInt::get(LoadSizeType, GEPIndex));
1776f9448bf3SDimitry Andric   }
1777f9448bf3SDimitry Andric 
1778f9448bf3SDimitry Andric   Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1779f9448bf3SDimitry Andric   Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1780f9448bf3SDimitry Andric 
1781f9448bf3SDimitry Andric   LoadSrc1 = Builder.CreateZExt(LoadSrc1, Type::getInt32Ty(CI->getContext()));
1782f9448bf3SDimitry Andric   LoadSrc2 = Builder.CreateZExt(LoadSrc2, Type::getInt32Ty(CI->getContext()));
1783f9448bf3SDimitry Andric   Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2);
1784f9448bf3SDimitry Andric 
1785f9448bf3SDimitry Andric   PhiRes->addIncoming(Diff, LoadCmpBlocks[Index]);
1786f9448bf3SDimitry Andric 
1787f9448bf3SDimitry Andric   if (Index < (LoadCmpBlocks.size() - 1)) {
1788db17bf38SDimitry Andric     // Early exit branch if difference found to EndBlock. Otherwise, continue to
1789db17bf38SDimitry Andric     // next LoadCmpBlock,
1790f9448bf3SDimitry Andric     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
1791f9448bf3SDimitry Andric                                     ConstantInt::get(Diff->getType(), 0));
1792f9448bf3SDimitry Andric     BranchInst *CmpBr =
1793f9448bf3SDimitry Andric         BranchInst::Create(EndBlock, LoadCmpBlocks[Index + 1], Cmp);
1794f9448bf3SDimitry Andric     Builder.Insert(CmpBr);
1795f9448bf3SDimitry Andric   } else {
1796db17bf38SDimitry Andric     // The last block has an unconditional branch to EndBlock.
1797f9448bf3SDimitry Andric     BranchInst *CmpBr = BranchInst::Create(EndBlock);
1798f9448bf3SDimitry Andric     Builder.Insert(CmpBr);
1799f9448bf3SDimitry Andric   }
1800f9448bf3SDimitry Andric }
1801f9448bf3SDimitry Andric 
1802f9448bf3SDimitry Andric unsigned MemCmpExpansion::getNumLoads(unsigned Size) {
1803f9448bf3SDimitry Andric   return (Size / MaxLoadSize) + countPopulation(Size % MaxLoadSize);
1804f9448bf3SDimitry Andric }
1805f9448bf3SDimitry Andric 
1806f9448bf3SDimitry Andric unsigned MemCmpExpansion::getLoadSize(unsigned Size) {
1807f9448bf3SDimitry Andric   return MinAlign(PowerOf2Floor(Size), MaxLoadSize);
1808f9448bf3SDimitry Andric }
1809f9448bf3SDimitry Andric 
1810db17bf38SDimitry Andric /// Generate an equality comparison for one or more pairs of loaded values.
1811db17bf38SDimitry Andric /// This is used in the case where the memcmp() call is compared equal or not
1812db17bf38SDimitry Andric /// equal to zero.
1813db17bf38SDimitry Andric Value *MemCmpExpansion::getCompareLoadPairs(unsigned Index, unsigned Size,
1814db17bf38SDimitry Andric                                             unsigned &NumBytesProcessed,
1815db17bf38SDimitry Andric                                             IRBuilder<> &Builder) {
1816f9448bf3SDimitry Andric   std::vector<Value *> XorList, OrList;
1817f9448bf3SDimitry Andric   Value *Diff;
1818f9448bf3SDimitry Andric 
1819f9448bf3SDimitry Andric   unsigned RemainingBytes = Size - NumBytesProcessed;
1820f9448bf3SDimitry Andric   unsigned NumLoadsRemaining = getNumLoads(RemainingBytes);
1821f9448bf3SDimitry Andric   unsigned NumLoads = std::min(NumLoadsRemaining, NumLoadsPerBlock);
1822f9448bf3SDimitry Andric 
1823db17bf38SDimitry Andric   // For a single-block expansion, start inserting before the memcmp call.
1824db17bf38SDimitry Andric   if (LoadCmpBlocks.empty())
1825db17bf38SDimitry Andric     Builder.SetInsertPoint(CI);
1826db17bf38SDimitry Andric   else
1827f9448bf3SDimitry Andric     Builder.SetInsertPoint(LoadCmpBlocks[Index]);
1828f9448bf3SDimitry Andric 
1829db17bf38SDimitry Andric   Value *Cmp = nullptr;
1830f9448bf3SDimitry Andric   for (unsigned i = 0; i < NumLoads; ++i) {
1831f9448bf3SDimitry Andric     unsigned LoadSize = getLoadSize(RemainingBytes);
1832f9448bf3SDimitry Andric     unsigned GEPIndex = NumBytesProcessed / LoadSize;
1833f9448bf3SDimitry Andric     NumBytesProcessed += LoadSize;
1834f9448bf3SDimitry Andric     RemainingBytes -= LoadSize;
1835f9448bf3SDimitry Andric 
1836f9448bf3SDimitry Andric     Type *LoadSizeType = IntegerType::get(CI->getContext(), LoadSize * 8);
1837f9448bf3SDimitry Andric     Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
1838edd7eaddSDimitry Andric     assert(LoadSize <= MaxLoadSize && "Unexpected load type");
1839f9448bf3SDimitry Andric 
1840f9448bf3SDimitry Andric     Value *Source1 = CI->getArgOperand(0);
1841f9448bf3SDimitry Andric     Value *Source2 = CI->getArgOperand(1);
1842f9448bf3SDimitry Andric 
1843db17bf38SDimitry Andric     // Cast source to LoadSizeType*.
1844f9448bf3SDimitry Andric     if (Source1->getType() != LoadSizeType)
1845f9448bf3SDimitry Andric       Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1846f9448bf3SDimitry Andric     if (Source2->getType() != LoadSizeType)
1847f9448bf3SDimitry Andric       Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1848f9448bf3SDimitry Andric 
1849db17bf38SDimitry Andric     // Get the base address using the GEPIndex.
1850f9448bf3SDimitry Andric     if (GEPIndex != 0) {
1851f9448bf3SDimitry Andric       Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1852f9448bf3SDimitry Andric                                   ConstantInt::get(LoadSizeType, GEPIndex));
1853f9448bf3SDimitry Andric       Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1854f9448bf3SDimitry Andric                                   ConstantInt::get(LoadSizeType, GEPIndex));
1855f9448bf3SDimitry Andric     }
1856f9448bf3SDimitry Andric 
1857edd7eaddSDimitry Andric     // Get a constant or load a value for each source address.
1858edd7eaddSDimitry Andric     Value *LoadSrc1 = nullptr;
1859edd7eaddSDimitry Andric     if (auto *Source1C = dyn_cast<Constant>(Source1))
1860edd7eaddSDimitry Andric       LoadSrc1 = ConstantFoldLoadFromConstPtr(Source1C, LoadSizeType, DL);
1861edd7eaddSDimitry Andric     if (!LoadSrc1)
1862edd7eaddSDimitry Andric       LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1863edd7eaddSDimitry Andric 
1864edd7eaddSDimitry Andric     Value *LoadSrc2 = nullptr;
1865edd7eaddSDimitry Andric     if (auto *Source2C = dyn_cast<Constant>(Source2))
1866edd7eaddSDimitry Andric       LoadSrc2 = ConstantFoldLoadFromConstPtr(Source2C, LoadSizeType, DL);
1867edd7eaddSDimitry Andric     if (!LoadSrc2)
1868edd7eaddSDimitry Andric       LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1869edd7eaddSDimitry Andric 
1870db17bf38SDimitry Andric     if (NumLoads != 1) {
1871f9448bf3SDimitry Andric       if (LoadSizeType != MaxLoadType) {
1872edd7eaddSDimitry Andric         LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType);
1873edd7eaddSDimitry Andric         LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType);
1874f9448bf3SDimitry Andric       }
1875db17bf38SDimitry Andric       // If we have multiple loads per block, we need to generate a composite
1876db17bf38SDimitry Andric       // comparison using xor+or.
1877f9448bf3SDimitry Andric       Diff = Builder.CreateXor(LoadSrc1, LoadSrc2);
1878edd7eaddSDimitry Andric       Diff = Builder.CreateZExt(Diff, MaxLoadType);
1879f9448bf3SDimitry Andric       XorList.push_back(Diff);
1880db17bf38SDimitry Andric     } else {
1881db17bf38SDimitry Andric       // If there's only one load per block, we just compare the loaded values.
1882db17bf38SDimitry Andric       Cmp = Builder.CreateICmpNE(LoadSrc1, LoadSrc2);
1883db17bf38SDimitry Andric     }
1884f9448bf3SDimitry Andric   }
1885f9448bf3SDimitry Andric 
1886f9448bf3SDimitry Andric   auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
1887f9448bf3SDimitry Andric     std::vector<Value *> OutList;
1888f9448bf3SDimitry Andric     for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
1889f9448bf3SDimitry Andric       Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
1890f9448bf3SDimitry Andric       OutList.push_back(Or);
1891f9448bf3SDimitry Andric     }
1892f9448bf3SDimitry Andric     if (InList.size() % 2 != 0)
1893f9448bf3SDimitry Andric       OutList.push_back(InList.back());
1894f9448bf3SDimitry Andric     return OutList;
1895f9448bf3SDimitry Andric   };
1896f9448bf3SDimitry Andric 
1897db17bf38SDimitry Andric   if (!Cmp) {
1898db17bf38SDimitry Andric     // Pairwise OR the XOR results.
1899f9448bf3SDimitry Andric     OrList = pairWiseOr(XorList);
1900f9448bf3SDimitry Andric 
1901db17bf38SDimitry Andric     // Pairwise OR the OR results until one result left.
1902f9448bf3SDimitry Andric     while (OrList.size() != 1) {
1903f9448bf3SDimitry Andric       OrList = pairWiseOr(OrList);
1904f9448bf3SDimitry Andric     }
1905db17bf38SDimitry Andric     Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
1906db17bf38SDimitry Andric   }
1907f9448bf3SDimitry Andric 
1908db17bf38SDimitry Andric   return Cmp;
1909db17bf38SDimitry Andric }
1910db17bf38SDimitry Andric 
1911db17bf38SDimitry Andric void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(
1912db17bf38SDimitry Andric     unsigned Index, unsigned Size, unsigned &NumBytesProcessed) {
1913db17bf38SDimitry Andric   IRBuilder<> Builder(CI->getContext());
1914db17bf38SDimitry Andric   Value *Cmp = getCompareLoadPairs(Index, Size, NumBytesProcessed, Builder);
1915db17bf38SDimitry Andric 
1916f9448bf3SDimitry Andric   BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1))
1917f9448bf3SDimitry Andric                            ? EndBlock
1918f9448bf3SDimitry Andric                            : LoadCmpBlocks[Index + 1];
1919db17bf38SDimitry Andric   // Early exit branch if difference found to ResultBlock. Otherwise,
1920db17bf38SDimitry Andric   // continue to next LoadCmpBlock or EndBlock.
1921f9448bf3SDimitry Andric   BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
1922f9448bf3SDimitry Andric   Builder.Insert(CmpBr);
1923f9448bf3SDimitry Andric 
1924f9448bf3SDimitry Andric   // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
1925f9448bf3SDimitry Andric   // since early exit to ResultBlock was not taken (no difference was found in
1926db17bf38SDimitry Andric   // any of the bytes).
1927f9448bf3SDimitry Andric   if (Index == LoadCmpBlocks.size() - 1) {
1928f9448bf3SDimitry Andric     Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
1929f9448bf3SDimitry Andric     PhiRes->addIncoming(Zero, LoadCmpBlocks[Index]);
1930f9448bf3SDimitry Andric   }
1931f9448bf3SDimitry Andric }
1932f9448bf3SDimitry Andric 
1933f9448bf3SDimitry Andric // This function creates the IR intructions for loading and comparing using the
1934f9448bf3SDimitry Andric // given LoadSize. It loads the number of bytes specified by LoadSize from each
1935f9448bf3SDimitry Andric // source of the memcmp parameters. It then does a subtract to see if there was
1936f9448bf3SDimitry Andric // a difference in the loaded values. If a difference is found, it branches
1937f9448bf3SDimitry Andric // with an early exit to the ResultBlock for calculating which source was
1938f9448bf3SDimitry Andric // larger. Otherwise, it falls through to the either the next LoadCmpBlock or
1939f9448bf3SDimitry Andric // the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
1940f9448bf3SDimitry Andric // a special case through emitLoadCompareByteBlock. The special handling can
1941f9448bf3SDimitry Andric // simply subtract the loaded values and add it to the result phi node.
1942edd7eaddSDimitry Andric void MemCmpExpansion::emitLoadCompareBlock(unsigned Index, unsigned LoadSize,
1943edd7eaddSDimitry Andric                                            unsigned GEPIndex) {
1944f9448bf3SDimitry Andric   if (LoadSize == 1) {
1945f9448bf3SDimitry Andric     MemCmpExpansion::emitLoadCompareByteBlock(Index, GEPIndex);
1946f9448bf3SDimitry Andric     return;
1947f9448bf3SDimitry Andric   }
1948f9448bf3SDimitry Andric 
1949f9448bf3SDimitry Andric   IRBuilder<> Builder(CI->getContext());
1950f9448bf3SDimitry Andric 
1951f9448bf3SDimitry Andric   Type *LoadSizeType = IntegerType::get(CI->getContext(), LoadSize * 8);
1952f9448bf3SDimitry Andric   Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
1953edd7eaddSDimitry Andric   assert(LoadSize <= MaxLoadSize && "Unexpected load type");
1954f9448bf3SDimitry Andric 
1955f9448bf3SDimitry Andric   Value *Source1 = CI->getArgOperand(0);
1956f9448bf3SDimitry Andric   Value *Source2 = CI->getArgOperand(1);
1957f9448bf3SDimitry Andric 
1958f9448bf3SDimitry Andric   Builder.SetInsertPoint(LoadCmpBlocks[Index]);
1959db17bf38SDimitry Andric   // Cast source to LoadSizeType*.
1960f9448bf3SDimitry Andric   if (Source1->getType() != LoadSizeType)
1961f9448bf3SDimitry Andric     Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
1962f9448bf3SDimitry Andric   if (Source2->getType() != LoadSizeType)
1963f9448bf3SDimitry Andric     Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
1964f9448bf3SDimitry Andric 
1965db17bf38SDimitry Andric   // Get the base address using the GEPIndex.
1966f9448bf3SDimitry Andric   if (GEPIndex != 0) {
1967f9448bf3SDimitry Andric     Source1 = Builder.CreateGEP(LoadSizeType, Source1,
1968f9448bf3SDimitry Andric                                 ConstantInt::get(LoadSizeType, GEPIndex));
1969f9448bf3SDimitry Andric     Source2 = Builder.CreateGEP(LoadSizeType, Source2,
1970f9448bf3SDimitry Andric                                 ConstantInt::get(LoadSizeType, GEPIndex));
1971f9448bf3SDimitry Andric   }
1972f9448bf3SDimitry Andric 
1973db17bf38SDimitry Andric   // Load LoadSizeType from the base address.
1974f9448bf3SDimitry Andric   Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
1975f9448bf3SDimitry Andric   Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
1976f9448bf3SDimitry Andric 
1977db17bf38SDimitry Andric   if (DL.isLittleEndian()) {
1978f9448bf3SDimitry Andric     Function *F = LoadCmpBlocks[Index]->getParent();
1979f9448bf3SDimitry Andric 
1980f9448bf3SDimitry Andric     Function *Bswap = Intrinsic::getDeclaration(F->getParent(),
1981f9448bf3SDimitry Andric                                                 Intrinsic::bswap, LoadSizeType);
1982f9448bf3SDimitry Andric     LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1);
1983f9448bf3SDimitry Andric     LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2);
1984f9448bf3SDimitry Andric   }
1985f9448bf3SDimitry Andric 
1986f9448bf3SDimitry Andric   if (LoadSizeType != MaxLoadType) {
1987edd7eaddSDimitry Andric     LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType);
1988edd7eaddSDimitry Andric     LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType);
1989f9448bf3SDimitry Andric   }
1990f9448bf3SDimitry Andric 
1991f9448bf3SDimitry Andric   // Add the loaded values to the phi nodes for calculating memcmp result only
1992f9448bf3SDimitry Andric   // if result is not used in a zero equality.
1993f9448bf3SDimitry Andric   if (!IsUsedForZeroCmp) {
1994f9448bf3SDimitry Andric     ResBlock.PhiSrc1->addIncoming(LoadSrc1, LoadCmpBlocks[Index]);
1995f9448bf3SDimitry Andric     ResBlock.PhiSrc2->addIncoming(LoadSrc2, LoadCmpBlocks[Index]);
1996f9448bf3SDimitry Andric   }
1997f9448bf3SDimitry Andric 
1998f9448bf3SDimitry Andric   Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2);
1999f9448bf3SDimitry Andric 
2000f9448bf3SDimitry Andric   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
2001f9448bf3SDimitry Andric                                   ConstantInt::get(Diff->getType(), 0));
2002f9448bf3SDimitry Andric   BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1))
2003f9448bf3SDimitry Andric                            ? EndBlock
2004f9448bf3SDimitry Andric                            : LoadCmpBlocks[Index + 1];
2005db17bf38SDimitry Andric   // Early exit branch if difference found to ResultBlock. Otherwise, continue
2006db17bf38SDimitry Andric   // to next LoadCmpBlock or EndBlock.
2007f9448bf3SDimitry Andric   BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
2008f9448bf3SDimitry Andric   Builder.Insert(CmpBr);
2009f9448bf3SDimitry Andric 
2010f9448bf3SDimitry Andric   // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
2011f9448bf3SDimitry Andric   // since early exit to ResultBlock was not taken (no difference was found in
2012db17bf38SDimitry Andric   // any of the bytes).
2013f9448bf3SDimitry Andric   if (Index == LoadCmpBlocks.size() - 1) {
2014f9448bf3SDimitry Andric     Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
2015f9448bf3SDimitry Andric     PhiRes->addIncoming(Zero, LoadCmpBlocks[Index]);
2016f9448bf3SDimitry Andric   }
2017f9448bf3SDimitry Andric }
2018f9448bf3SDimitry Andric 
2019f9448bf3SDimitry Andric // This function populates the ResultBlock with a sequence to calculate the
2020f9448bf3SDimitry Andric // memcmp result. It compares the two loaded source values and returns -1 if
2021f9448bf3SDimitry Andric // src1 < src2 and 1 if src1 > src2.
2022db17bf38SDimitry Andric void MemCmpExpansion::emitMemCmpResultBlock() {
2023f9448bf3SDimitry Andric   IRBuilder<> Builder(CI->getContext());
2024f9448bf3SDimitry Andric 
2025f9448bf3SDimitry Andric   // Special case: if memcmp result is used in a zero equality, result does not
2026f9448bf3SDimitry Andric   // need to be calculated and can simply return 1.
2027f9448bf3SDimitry Andric   if (IsUsedForZeroCmp) {
2028f9448bf3SDimitry Andric     BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
2029f9448bf3SDimitry Andric     Builder.SetInsertPoint(ResBlock.BB, InsertPt);
2030f9448bf3SDimitry Andric     Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
2031f9448bf3SDimitry Andric     PhiRes->addIncoming(Res, ResBlock.BB);
2032f9448bf3SDimitry Andric     BranchInst *NewBr = BranchInst::Create(EndBlock);
2033f9448bf3SDimitry Andric     Builder.Insert(NewBr);
2034f9448bf3SDimitry Andric     return;
2035f9448bf3SDimitry Andric   }
2036f9448bf3SDimitry Andric   BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
2037f9448bf3SDimitry Andric   Builder.SetInsertPoint(ResBlock.BB, InsertPt);
2038f9448bf3SDimitry Andric 
2039f9448bf3SDimitry Andric   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
2040f9448bf3SDimitry Andric                                   ResBlock.PhiSrc2);
2041f9448bf3SDimitry Andric 
2042f9448bf3SDimitry Andric   Value *Res =
2043f9448bf3SDimitry Andric       Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1),
2044f9448bf3SDimitry Andric                            ConstantInt::get(Builder.getInt32Ty(), 1));
2045f9448bf3SDimitry Andric 
2046f9448bf3SDimitry Andric   BranchInst *NewBr = BranchInst::Create(EndBlock);
2047f9448bf3SDimitry Andric   Builder.Insert(NewBr);
2048f9448bf3SDimitry Andric   PhiRes->addIncoming(Res, ResBlock.BB);
2049f9448bf3SDimitry Andric }
2050f9448bf3SDimitry Andric 
2051edd7eaddSDimitry Andric unsigned MemCmpExpansion::calculateNumBlocks(unsigned Size) {
2052edd7eaddSDimitry Andric   unsigned NumBlocks = 0;
2053db17bf38SDimitry Andric   bool HaveOneByteLoad = false;
2054f9448bf3SDimitry Andric   unsigned RemainingSize = Size;
2055f9448bf3SDimitry Andric   unsigned LoadSize = MaxLoadSize;
2056f9448bf3SDimitry Andric   while (RemainingSize) {
2057f9448bf3SDimitry Andric     if (LoadSize == 1)
2058db17bf38SDimitry Andric       HaveOneByteLoad = true;
2059f9448bf3SDimitry Andric     NumBlocks += RemainingSize / LoadSize;
2060f9448bf3SDimitry Andric     RemainingSize = RemainingSize % LoadSize;
2061f9448bf3SDimitry Andric     LoadSize = LoadSize / 2;
2062f9448bf3SDimitry Andric   }
2063db17bf38SDimitry Andric   NumBlocksNonOneByte = HaveOneByteLoad ? (NumBlocks - 1) : NumBlocks;
2064f9448bf3SDimitry Andric 
2065f9448bf3SDimitry Andric   if (IsUsedForZeroCmp)
2066f9448bf3SDimitry Andric     NumBlocks = NumBlocks / NumLoadsPerBlock +
2067f9448bf3SDimitry Andric                 (NumBlocks % NumLoadsPerBlock != 0 ? 1 : 0);
2068f9448bf3SDimitry Andric 
2069f9448bf3SDimitry Andric   return NumBlocks;
2070f9448bf3SDimitry Andric }
2071f9448bf3SDimitry Andric 
2072f9448bf3SDimitry Andric void MemCmpExpansion::setupResultBlockPHINodes() {
2073f9448bf3SDimitry Andric   IRBuilder<> Builder(CI->getContext());
2074f9448bf3SDimitry Andric   Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
2075f9448bf3SDimitry Andric   Builder.SetInsertPoint(ResBlock.BB);
2076f9448bf3SDimitry Andric   ResBlock.PhiSrc1 =
2077f9448bf3SDimitry Andric       Builder.CreatePHI(MaxLoadType, NumBlocksNonOneByte, "phi.src1");
2078f9448bf3SDimitry Andric   ResBlock.PhiSrc2 =
2079f9448bf3SDimitry Andric       Builder.CreatePHI(MaxLoadType, NumBlocksNonOneByte, "phi.src2");
2080f9448bf3SDimitry Andric }
2081f9448bf3SDimitry Andric 
2082f9448bf3SDimitry Andric void MemCmpExpansion::setupEndBlockPHINodes() {
2083f9448bf3SDimitry Andric   IRBuilder<> Builder(CI->getContext());
2084f9448bf3SDimitry Andric 
2085f9448bf3SDimitry Andric   Builder.SetInsertPoint(&EndBlock->front());
2086f9448bf3SDimitry Andric   PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
2087f9448bf3SDimitry Andric }
2088f9448bf3SDimitry Andric 
2089db17bf38SDimitry Andric Value *MemCmpExpansion::getMemCmpExpansionZeroCase(unsigned Size) {
2090f9448bf3SDimitry Andric   unsigned NumBytesProcessed = 0;
2091db17bf38SDimitry Andric   // This loop populates each of the LoadCmpBlocks with the IR sequence to
2092db17bf38SDimitry Andric   // handle multiple loads per block.
2093db17bf38SDimitry Andric   for (unsigned i = 0; i < NumBlocks; ++i)
2094f9448bf3SDimitry Andric     emitLoadCompareBlockMultipleLoads(i, Size, NumBytesProcessed);
2095db17bf38SDimitry Andric 
2096db17bf38SDimitry Andric   emitMemCmpResultBlock();
2097db17bf38SDimitry Andric   return PhiRes;
2098f9448bf3SDimitry Andric }
2099f9448bf3SDimitry Andric 
2100db17bf38SDimitry Andric /// A memcmp expansion that compares equality with 0 and only has one block of
2101db17bf38SDimitry Andric /// load and compare can bypass the compare, branch, and phi IR that is required
2102db17bf38SDimitry Andric /// in the general case.
2103db17bf38SDimitry Andric Value *MemCmpExpansion::getMemCmpEqZeroOneBlock(unsigned Size) {
2104db17bf38SDimitry Andric   unsigned NumBytesProcessed = 0;
2105db17bf38SDimitry Andric   IRBuilder<> Builder(CI->getContext());
2106db17bf38SDimitry Andric   Value *Cmp = getCompareLoadPairs(0, Size, NumBytesProcessed, Builder);
2107db17bf38SDimitry Andric   return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext()));
2108f9448bf3SDimitry Andric }
2109f9448bf3SDimitry Andric 
2110f9448bf3SDimitry Andric // This function expands the memcmp call into an inline expansion and returns
2111f9448bf3SDimitry Andric // the memcmp result.
2112db17bf38SDimitry Andric Value *MemCmpExpansion::getMemCmpExpansion(uint64_t Size) {
2113db17bf38SDimitry Andric   if (IsUsedForZeroCmp)
2114db17bf38SDimitry Andric     return NumBlocks == 1 ? getMemCmpEqZeroOneBlock(Size) :
2115db17bf38SDimitry Andric                             getMemCmpExpansionZeroCase(Size);
2116f9448bf3SDimitry Andric 
2117db17bf38SDimitry Andric   // This loop calls emitLoadCompareBlock for comparing Size bytes of the two
2118db17bf38SDimitry Andric   // memcmp sources. It starts with loading using the maximum load size set by
2119f9448bf3SDimitry Andric   // the target. It processes any remaining bytes using a load size which is the
2120f9448bf3SDimitry Andric   // next smallest power of 2.
2121edd7eaddSDimitry Andric   unsigned LoadSize = MaxLoadSize;
2122edd7eaddSDimitry Andric   unsigned NumBytesToBeProcessed = Size;
2123db17bf38SDimitry Andric   unsigned Index = 0;
2124f9448bf3SDimitry Andric   while (NumBytesToBeProcessed) {
2125db17bf38SDimitry Andric     // Calculate how many blocks we can create with the current load size.
2126edd7eaddSDimitry Andric     unsigned NumBlocks = NumBytesToBeProcessed / LoadSize;
2127edd7eaddSDimitry Andric     unsigned GEPIndex = (Size - NumBytesToBeProcessed) / LoadSize;
2128f9448bf3SDimitry Andric     NumBytesToBeProcessed = NumBytesToBeProcessed % LoadSize;
2129f9448bf3SDimitry Andric 
2130f9448bf3SDimitry Andric     // For each NumBlocks, populate the instruction sequence for loading and
2131db17bf38SDimitry Andric     // comparing LoadSize bytes.
2132f9448bf3SDimitry Andric     while (NumBlocks--) {
2133db17bf38SDimitry Andric       emitLoadCompareBlock(Index, LoadSize, GEPIndex);
2134f9448bf3SDimitry Andric       Index++;
2135f9448bf3SDimitry Andric       GEPIndex++;
2136f9448bf3SDimitry Andric     }
2137db17bf38SDimitry Andric     // Get the next LoadSize to use.
2138f9448bf3SDimitry Andric     LoadSize = LoadSize / 2;
2139f9448bf3SDimitry Andric   }
2140f9448bf3SDimitry Andric 
2141db17bf38SDimitry Andric   emitMemCmpResultBlock();
2142f9448bf3SDimitry Andric   return PhiRes;
2143f9448bf3SDimitry Andric }
2144f9448bf3SDimitry Andric 
2145f9448bf3SDimitry Andric // This function checks to see if an expansion of memcmp can be generated.
2146f9448bf3SDimitry Andric // It checks for constant compare size that is less than the max inline size.
2147f9448bf3SDimitry Andric // If an expansion cannot occur, returns false to leave as a library call.
2148db17bf38SDimitry Andric // Otherwise, the library call is replaced with a new IR instruction sequence.
2149f9448bf3SDimitry Andric /// We want to transform:
2150f9448bf3SDimitry Andric /// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
2151f9448bf3SDimitry Andric /// To:
2152f9448bf3SDimitry Andric /// loadbb:
2153f9448bf3SDimitry Andric ///  %0 = bitcast i32* %buffer2 to i8*
2154f9448bf3SDimitry Andric ///  %1 = bitcast i32* %buffer1 to i8*
2155f9448bf3SDimitry Andric ///  %2 = bitcast i8* %1 to i64*
2156f9448bf3SDimitry Andric ///  %3 = bitcast i8* %0 to i64*
2157f9448bf3SDimitry Andric ///  %4 = load i64, i64* %2
2158f9448bf3SDimitry Andric ///  %5 = load i64, i64* %3
2159f9448bf3SDimitry Andric ///  %6 = call i64 @llvm.bswap.i64(i64 %4)
2160f9448bf3SDimitry Andric ///  %7 = call i64 @llvm.bswap.i64(i64 %5)
2161f9448bf3SDimitry Andric ///  %8 = sub i64 %6, %7
2162f9448bf3SDimitry Andric ///  %9 = icmp ne i64 %8, 0
2163f9448bf3SDimitry Andric ///  br i1 %9, label %res_block, label %loadbb1
2164f9448bf3SDimitry Andric /// res_block:                                        ; preds = %loadbb2,
2165f9448bf3SDimitry Andric /// %loadbb1, %loadbb
2166f9448bf3SDimitry Andric ///  %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
2167f9448bf3SDimitry Andric ///  %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
2168f9448bf3SDimitry Andric ///  %10 = icmp ult i64 %phi.src1, %phi.src2
2169f9448bf3SDimitry Andric ///  %11 = select i1 %10, i32 -1, i32 1
2170f9448bf3SDimitry Andric ///  br label %endblock
2171f9448bf3SDimitry Andric /// loadbb1:                                          ; preds = %loadbb
2172f9448bf3SDimitry Andric ///  %12 = bitcast i32* %buffer2 to i8*
2173f9448bf3SDimitry Andric ///  %13 = bitcast i32* %buffer1 to i8*
2174f9448bf3SDimitry Andric ///  %14 = bitcast i8* %13 to i32*
2175f9448bf3SDimitry Andric ///  %15 = bitcast i8* %12 to i32*
2176f9448bf3SDimitry Andric ///  %16 = getelementptr i32, i32* %14, i32 2
2177f9448bf3SDimitry Andric ///  %17 = getelementptr i32, i32* %15, i32 2
2178f9448bf3SDimitry Andric ///  %18 = load i32, i32* %16
2179f9448bf3SDimitry Andric ///  %19 = load i32, i32* %17
2180f9448bf3SDimitry Andric ///  %20 = call i32 @llvm.bswap.i32(i32 %18)
2181f9448bf3SDimitry Andric ///  %21 = call i32 @llvm.bswap.i32(i32 %19)
2182f9448bf3SDimitry Andric ///  %22 = zext i32 %20 to i64
2183f9448bf3SDimitry Andric ///  %23 = zext i32 %21 to i64
2184f9448bf3SDimitry Andric ///  %24 = sub i64 %22, %23
2185f9448bf3SDimitry Andric ///  %25 = icmp ne i64 %24, 0
2186f9448bf3SDimitry Andric ///  br i1 %25, label %res_block, label %loadbb2
2187f9448bf3SDimitry Andric /// loadbb2:                                          ; preds = %loadbb1
2188f9448bf3SDimitry Andric ///  %26 = bitcast i32* %buffer2 to i8*
2189f9448bf3SDimitry Andric ///  %27 = bitcast i32* %buffer1 to i8*
2190f9448bf3SDimitry Andric ///  %28 = bitcast i8* %27 to i16*
2191f9448bf3SDimitry Andric ///  %29 = bitcast i8* %26 to i16*
2192f9448bf3SDimitry Andric ///  %30 = getelementptr i16, i16* %28, i16 6
2193f9448bf3SDimitry Andric ///  %31 = getelementptr i16, i16* %29, i16 6
2194f9448bf3SDimitry Andric ///  %32 = load i16, i16* %30
2195f9448bf3SDimitry Andric ///  %33 = load i16, i16* %31
2196f9448bf3SDimitry Andric ///  %34 = call i16 @llvm.bswap.i16(i16 %32)
2197f9448bf3SDimitry Andric ///  %35 = call i16 @llvm.bswap.i16(i16 %33)
2198f9448bf3SDimitry Andric ///  %36 = zext i16 %34 to i64
2199f9448bf3SDimitry Andric ///  %37 = zext i16 %35 to i64
2200f9448bf3SDimitry Andric ///  %38 = sub i64 %36, %37
2201f9448bf3SDimitry Andric ///  %39 = icmp ne i64 %38, 0
2202f9448bf3SDimitry Andric ///  br i1 %39, label %res_block, label %loadbb3
2203f9448bf3SDimitry Andric /// loadbb3:                                          ; preds = %loadbb2
2204f9448bf3SDimitry Andric ///  %40 = bitcast i32* %buffer2 to i8*
2205f9448bf3SDimitry Andric ///  %41 = bitcast i32* %buffer1 to i8*
2206f9448bf3SDimitry Andric ///  %42 = getelementptr i8, i8* %41, i8 14
2207f9448bf3SDimitry Andric ///  %43 = getelementptr i8, i8* %40, i8 14
2208f9448bf3SDimitry Andric ///  %44 = load i8, i8* %42
2209f9448bf3SDimitry Andric ///  %45 = load i8, i8* %43
2210f9448bf3SDimitry Andric ///  %46 = zext i8 %44 to i32
2211f9448bf3SDimitry Andric ///  %47 = zext i8 %45 to i32
2212f9448bf3SDimitry Andric ///  %48 = sub i32 %46, %47
2213f9448bf3SDimitry Andric ///  br label %endblock
2214f9448bf3SDimitry Andric /// endblock:                                         ; preds = %res_block,
2215f9448bf3SDimitry Andric /// %loadbb3
2216f9448bf3SDimitry Andric ///  %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
2217f9448bf3SDimitry Andric ///  ret i32 %phi.res
2218f9448bf3SDimitry Andric static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
2219f9448bf3SDimitry Andric                          const TargetLowering *TLI, const DataLayout *DL) {
2220f9448bf3SDimitry Andric   NumMemCmpCalls++;
2221f9448bf3SDimitry Andric   IRBuilder<> Builder(CI->getContext());
2222f9448bf3SDimitry Andric 
2223db17bf38SDimitry Andric   // TTI call to check if target would like to expand memcmp. Also, get the
2224db17bf38SDimitry Andric   // MaxLoadSize.
2225f9448bf3SDimitry Andric   unsigned MaxLoadSize;
2226f9448bf3SDimitry Andric   if (!TTI->expandMemCmp(CI, MaxLoadSize))
2227f9448bf3SDimitry Andric     return false;
2228f9448bf3SDimitry Andric 
2229db17bf38SDimitry Andric   // Early exit from expansion if -Oz.
2230db17bf38SDimitry Andric   if (CI->getFunction()->optForMinSize())
2231f9448bf3SDimitry Andric     return false;
2232f9448bf3SDimitry Andric 
2233db17bf38SDimitry Andric   // Early exit from expansion if size is not a constant.
2234f9448bf3SDimitry Andric   ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2235f9448bf3SDimitry Andric   if (!SizeCast) {
2236f9448bf3SDimitry Andric     NumMemCmpNotConstant++;
2237f9448bf3SDimitry Andric     return false;
2238f9448bf3SDimitry Andric   }
2239f9448bf3SDimitry Andric 
2240db17bf38SDimitry Andric   // Early exit from expansion if size greater than max bytes to load.
2241f9448bf3SDimitry Andric   uint64_t SizeVal = SizeCast->getZExtValue();
2242f9448bf3SDimitry Andric   unsigned NumLoads = 0;
2243f9448bf3SDimitry Andric   unsigned RemainingSize = SizeVal;
2244f9448bf3SDimitry Andric   unsigned LoadSize = MaxLoadSize;
2245f9448bf3SDimitry Andric   while (RemainingSize) {
2246f9448bf3SDimitry Andric     NumLoads += RemainingSize / LoadSize;
2247f9448bf3SDimitry Andric     RemainingSize = RemainingSize % LoadSize;
2248f9448bf3SDimitry Andric     LoadSize = LoadSize / 2;
2249f9448bf3SDimitry Andric   }
2250f9448bf3SDimitry Andric 
2251db17bf38SDimitry Andric   if (NumLoads > TLI->getMaxExpandSizeMemcmp(CI->getFunction()->optForSize())) {
2252f9448bf3SDimitry Andric     NumMemCmpGreaterThanMax++;
2253f9448bf3SDimitry Andric     return false;
2254f9448bf3SDimitry Andric   }
2255f9448bf3SDimitry Andric 
2256f9448bf3SDimitry Andric   NumMemCmpInlined++;
2257f9448bf3SDimitry Andric 
2258db17bf38SDimitry Andric   // MemCmpHelper object creates and sets up basic blocks required for
2259db17bf38SDimitry Andric   // expanding memcmp with size SizeVal.
2260f9448bf3SDimitry Andric   unsigned NumLoadsPerBlock = MemCmpNumLoadsPerBlock;
2261db17bf38SDimitry Andric   MemCmpExpansion MemCmpHelper(CI, SizeVal, MaxLoadSize, NumLoadsPerBlock, *DL);
2262f9448bf3SDimitry Andric 
2263db17bf38SDimitry Andric   Value *Res = MemCmpHelper.getMemCmpExpansion(SizeVal);
2264f9448bf3SDimitry Andric 
2265db17bf38SDimitry Andric   // Replace call with result of expansion and erase call.
2266f9448bf3SDimitry Andric   CI->replaceAllUsesWith(Res);
2267f9448bf3SDimitry Andric   CI->eraseFromParent();
2268f9448bf3SDimitry Andric 
2269f9448bf3SDimitry Andric   return true;
2270f9448bf3SDimitry Andric }
2271f9448bf3SDimitry Andric 
22727d523365SDimitry Andric bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
227391bc56edSDimitry Andric   BasicBlock *BB = CI->getParent();
227491bc56edSDimitry Andric 
227591bc56edSDimitry Andric   // Lower inline assembly if we can.
227691bc56edSDimitry Andric   // If we found an inline asm expession, and if the target knows how to
227791bc56edSDimitry Andric   // lower it to normal LLVM code, do so now.
227891bc56edSDimitry Andric   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
227991bc56edSDimitry Andric     if (TLI->ExpandInlineAsm(CI)) {
228091bc56edSDimitry Andric       // Avoid invalidating the iterator.
228191bc56edSDimitry Andric       CurInstIterator = BB->begin();
228291bc56edSDimitry Andric       // Avoid processing instructions out of order, which could cause
228391bc56edSDimitry Andric       // reuse before a value is defined.
228491bc56edSDimitry Andric       SunkAddrs.clear();
228591bc56edSDimitry Andric       return true;
228691bc56edSDimitry Andric     }
228791bc56edSDimitry Andric     // Sink address computing for memory operands into the block.
22887d523365SDimitry Andric     if (optimizeInlineAsmInst(CI))
228991bc56edSDimitry Andric       return true;
229091bc56edSDimitry Andric   }
229191bc56edSDimitry Andric 
2292ff0cc061SDimitry Andric   // Align the pointer arguments to this call if the target thinks it's a good
2293ff0cc061SDimitry Andric   // idea
2294ff0cc061SDimitry Andric   unsigned MinSize, PrefAlign;
2295875ed548SDimitry Andric   if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2296ff0cc061SDimitry Andric     for (auto &Arg : CI->arg_operands()) {
2297ff0cc061SDimitry Andric       // We want to align both objects whose address is used directly and
2298ff0cc061SDimitry Andric       // objects whose address is used in casts and GEPs, though it only makes
2299ff0cc061SDimitry Andric       // sense for GEPs if the offset is a multiple of the desired alignment and
2300ff0cc061SDimitry Andric       // if size - offset meets the size threshold.
2301ff0cc061SDimitry Andric       if (!Arg->getType()->isPointerTy())
2302ff0cc061SDimitry Andric         continue;
2303875ed548SDimitry Andric       APInt Offset(DL->getPointerSizeInBits(
2304875ed548SDimitry Andric                        cast<PointerType>(Arg->getType())->getAddressSpace()),
2305875ed548SDimitry Andric                    0);
2306875ed548SDimitry Andric       Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2307ff0cc061SDimitry Andric       uint64_t Offset2 = Offset.getLimitedValue();
2308ff0cc061SDimitry Andric       if ((Offset2 & (PrefAlign-1)) != 0)
2309ff0cc061SDimitry Andric         continue;
2310ff0cc061SDimitry Andric       AllocaInst *AI;
2311875ed548SDimitry Andric       if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2312875ed548SDimitry Andric           DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2313ff0cc061SDimitry Andric         AI->setAlignment(PrefAlign);
2314ff0cc061SDimitry Andric       // Global variables can only be aligned if they are defined in this
2315ff0cc061SDimitry Andric       // object (i.e. they are uniquely initialized in this object), and
2316ff0cc061SDimitry Andric       // over-aligning global variables that have an explicit section is
2317ff0cc061SDimitry Andric       // forbidden.
2318ff0cc061SDimitry Andric       GlobalVariable *GV;
2319*cdd9644cSDimitry Andric       if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
23203ca95b02SDimitry Andric           GV->getPointerAlignment(*DL) < PrefAlign &&
23213ca95b02SDimitry Andric           DL->getTypeAllocSize(GV->getValueType()) >=
2322875ed548SDimitry Andric               MinSize + Offset2)
2323ff0cc061SDimitry Andric         GV->setAlignment(PrefAlign);
2324ff0cc061SDimitry Andric     }
2325ff0cc061SDimitry Andric     // If this is a memcpy (or similar) then we may be able to improve the
2326ff0cc061SDimitry Andric     // alignment
2327ff0cc061SDimitry Andric     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2328875ed548SDimitry Andric       unsigned Align = getKnownAlignment(MI->getDest(), *DL);
2329ff0cc061SDimitry Andric       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
2330875ed548SDimitry Andric         Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
2331ff0cc061SDimitry Andric       if (Align > MI->getAlignment())
2332ff0cc061SDimitry Andric         MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
2333ff0cc061SDimitry Andric     }
2334ff0cc061SDimitry Andric   }
2335ff0cc061SDimitry Andric 
23363ca95b02SDimitry Andric   // If we have a cold call site, try to sink addressing computation into the
23373ca95b02SDimitry Andric   // cold block.  This interacts with our handling for loads and stores to
23383ca95b02SDimitry Andric   // ensure that we can fold all uses of a potential addressing computation
23393ca95b02SDimitry Andric   // into their uses.  TODO: generalize this to work over profiling data
23403ca95b02SDimitry Andric   if (!OptSize && CI->hasFnAttr(Attribute::Cold))
23413ca95b02SDimitry Andric     for (auto &Arg : CI->arg_operands()) {
23423ca95b02SDimitry Andric       if (!Arg->getType()->isPointerTy())
23433ca95b02SDimitry Andric         continue;
23443ca95b02SDimitry Andric       unsigned AS = Arg->getType()->getPointerAddressSpace();
23453ca95b02SDimitry Andric       return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
23463ca95b02SDimitry Andric     }
23473ca95b02SDimitry Andric 
234891bc56edSDimitry Andric   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
234939d628a0SDimitry Andric   if (II) {
235039d628a0SDimitry Andric     switch (II->getIntrinsicID()) {
235139d628a0SDimitry Andric     default: break;
235239d628a0SDimitry Andric     case Intrinsic::objectsize: {
235339d628a0SDimitry Andric       // Lower all uses of llvm.objectsize.*
2354d88c1a5aSDimitry Andric       ConstantInt *RetVal =
2355d88c1a5aSDimitry Andric           lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
235691bc56edSDimitry Andric       // Substituting this can cause recursive simplifications, which can
2357f37b6182SDimitry Andric       // invalidate our iterator.  Use a WeakTrackingVH to hold onto it in case
2358f37b6182SDimitry Andric       // this
235991bc56edSDimitry Andric       // happens.
23603ca95b02SDimitry Andric       Value *CurValue = &*CurInstIterator;
2361f37b6182SDimitry Andric       WeakTrackingVH IterHandle(CurValue);
236291bc56edSDimitry Andric 
23633ca95b02SDimitry Andric       replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
236491bc56edSDimitry Andric 
236591bc56edSDimitry Andric       // If the iterator instruction was recursively deleted, start over at the
236691bc56edSDimitry Andric       // start of the block.
23673ca95b02SDimitry Andric       if (IterHandle != CurValue) {
236891bc56edSDimitry Andric         CurInstIterator = BB->begin();
236991bc56edSDimitry Andric         SunkAddrs.clear();
237091bc56edSDimitry Andric       }
237191bc56edSDimitry Andric       return true;
237291bc56edSDimitry Andric     }
2373ff0cc061SDimitry Andric     case Intrinsic::aarch64_stlxr:
2374ff0cc061SDimitry Andric     case Intrinsic::aarch64_stxr: {
2375ff0cc061SDimitry Andric       ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2376ff0cc061SDimitry Andric       if (!ExtVal || !ExtVal->hasOneUse() ||
2377ff0cc061SDimitry Andric           ExtVal->getParent() == CI->getParent())
2378ff0cc061SDimitry Andric         return false;
2379ff0cc061SDimitry Andric       // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2380ff0cc061SDimitry Andric       ExtVal->moveBefore(CI);
23818f0fd8f6SDimitry Andric       // Mark this instruction as "inserted by CGP", so that other
23828f0fd8f6SDimitry Andric       // optimizations don't touch it.
23838f0fd8f6SDimitry Andric       InsertedInsts.insert(ExtVal);
2384ff0cc061SDimitry Andric       return true;
2385ff0cc061SDimitry Andric     }
23867d523365SDimitry Andric     case Intrinsic::invariant_group_barrier:
23877d523365SDimitry Andric       II->replaceAllUsesWith(II->getArgOperand(0));
23887d523365SDimitry Andric       II->eraseFromParent();
23897d523365SDimitry Andric       return true;
23907d523365SDimitry Andric 
23917d523365SDimitry Andric     case Intrinsic::cttz:
23927d523365SDimitry Andric     case Intrinsic::ctlz:
23937d523365SDimitry Andric       // If counting zeros is expensive, try to avoid it.
23947d523365SDimitry Andric       return despeculateCountZeros(II, TLI, DL, ModifiedDT);
239539d628a0SDimitry Andric     }
239691bc56edSDimitry Andric 
239739d628a0SDimitry Andric     if (TLI) {
239891bc56edSDimitry Andric       SmallVector<Value*, 2> PtrOps;
239991bc56edSDimitry Andric       Type *AccessTy;
24007a7e6055SDimitry Andric       if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
24017a7e6055SDimitry Andric         while (!PtrOps.empty()) {
24027a7e6055SDimitry Andric           Value *PtrVal = PtrOps.pop_back_val();
24037a7e6055SDimitry Andric           unsigned AS = PtrVal->getType()->getPointerAddressSpace();
24047a7e6055SDimitry Andric           if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
240591bc56edSDimitry Andric             return true;
240691bc56edSDimitry Andric         }
240739d628a0SDimitry Andric     }
24087a7e6055SDimitry Andric   }
240991bc56edSDimitry Andric 
241091bc56edSDimitry Andric   // From here on out we're working with named functions.
241191bc56edSDimitry Andric   if (!CI->getCalledFunction()) return false;
241291bc56edSDimitry Andric 
241391bc56edSDimitry Andric   // Lower all default uses of _chk calls.  This is very similar
241491bc56edSDimitry Andric   // to what InstCombineCalls does, but here we are only lowering calls
241539d628a0SDimitry Andric   // to fortified library functions (e.g. __memcpy_chk) that have the default
241639d628a0SDimitry Andric   // "don't know" as the objectsize.  Anything else should be left alone.
2417ff0cc061SDimitry Andric   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
241839d628a0SDimitry Andric   if (Value *V = Simplifier.optimizeCall(CI)) {
241939d628a0SDimitry Andric     CI->replaceAllUsesWith(V);
242039d628a0SDimitry Andric     CI->eraseFromParent();
242139d628a0SDimitry Andric     return true;
242239d628a0SDimitry Andric   }
2423f9448bf3SDimitry Andric 
2424f9448bf3SDimitry Andric   LibFunc Func;
2425db17bf38SDimitry Andric   if (TLInfo->getLibFunc(ImmutableCallSite(CI), Func) &&
2426db17bf38SDimitry Andric       Func == LibFunc_memcmp && expandMemCmp(CI, TTI, TLI, DL)) {
2427f9448bf3SDimitry Andric     ModifiedDT = true;
2428f9448bf3SDimitry Andric     return true;
2429f9448bf3SDimitry Andric   }
243039d628a0SDimitry Andric   return false;
243191bc56edSDimitry Andric }
243291bc56edSDimitry Andric 
24337d523365SDimitry Andric /// Look for opportunities to duplicate return instructions to the predecessor
24347d523365SDimitry Andric /// to enable tail call optimizations. The case it is currently looking for is:
243591bc56edSDimitry Andric /// @code
243691bc56edSDimitry Andric /// bb0:
243791bc56edSDimitry Andric ///   %tmp0 = tail call i32 @f0()
243891bc56edSDimitry Andric ///   br label %return
243991bc56edSDimitry Andric /// bb1:
244091bc56edSDimitry Andric ///   %tmp1 = tail call i32 @f1()
244191bc56edSDimitry Andric ///   br label %return
244291bc56edSDimitry Andric /// bb2:
244391bc56edSDimitry Andric ///   %tmp2 = tail call i32 @f2()
244491bc56edSDimitry Andric ///   br label %return
244591bc56edSDimitry Andric /// return:
244691bc56edSDimitry Andric ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
244791bc56edSDimitry Andric ///   ret i32 %retval
244891bc56edSDimitry Andric /// @endcode
244991bc56edSDimitry Andric ///
245091bc56edSDimitry Andric /// =>
245191bc56edSDimitry Andric ///
245291bc56edSDimitry Andric /// @code
245391bc56edSDimitry Andric /// bb0:
245491bc56edSDimitry Andric ///   %tmp0 = tail call i32 @f0()
245591bc56edSDimitry Andric ///   ret i32 %tmp0
245691bc56edSDimitry Andric /// bb1:
245791bc56edSDimitry Andric ///   %tmp1 = tail call i32 @f1()
245891bc56edSDimitry Andric ///   ret i32 %tmp1
245991bc56edSDimitry Andric /// bb2:
246091bc56edSDimitry Andric ///   %tmp2 = tail call i32 @f2()
246191bc56edSDimitry Andric ///   ret i32 %tmp2
246291bc56edSDimitry Andric /// @endcode
24637d523365SDimitry Andric bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
246491bc56edSDimitry Andric   if (!TLI)
246591bc56edSDimitry Andric     return false;
246691bc56edSDimitry Andric 
2467d88c1a5aSDimitry Andric   ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2468d88c1a5aSDimitry Andric   if (!RetI)
246991bc56edSDimitry Andric     return false;
247091bc56edSDimitry Andric 
247191bc56edSDimitry Andric   PHINode *PN = nullptr;
247291bc56edSDimitry Andric   BitCastInst *BCI = nullptr;
2473d88c1a5aSDimitry Andric   Value *V = RetI->getReturnValue();
247491bc56edSDimitry Andric   if (V) {
247591bc56edSDimitry Andric     BCI = dyn_cast<BitCastInst>(V);
247691bc56edSDimitry Andric     if (BCI)
247791bc56edSDimitry Andric       V = BCI->getOperand(0);
247891bc56edSDimitry Andric 
247991bc56edSDimitry Andric     PN = dyn_cast<PHINode>(V);
248091bc56edSDimitry Andric     if (!PN)
248191bc56edSDimitry Andric       return false;
248291bc56edSDimitry Andric   }
248391bc56edSDimitry Andric 
248491bc56edSDimitry Andric   if (PN && PN->getParent() != BB)
248591bc56edSDimitry Andric     return false;
248691bc56edSDimitry Andric 
248791bc56edSDimitry Andric   // Make sure there are no instructions between the PHI and return, or that the
248891bc56edSDimitry Andric   // return is the first instruction in the block.
248991bc56edSDimitry Andric   if (PN) {
249091bc56edSDimitry Andric     BasicBlock::iterator BI = BB->begin();
249191bc56edSDimitry Andric     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
249291bc56edSDimitry Andric     if (&*BI == BCI)
249391bc56edSDimitry Andric       // Also skip over the bitcast.
249491bc56edSDimitry Andric       ++BI;
2495d88c1a5aSDimitry Andric     if (&*BI != RetI)
249691bc56edSDimitry Andric       return false;
249791bc56edSDimitry Andric   } else {
249891bc56edSDimitry Andric     BasicBlock::iterator BI = BB->begin();
249991bc56edSDimitry Andric     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2500d88c1a5aSDimitry Andric     if (&*BI != RetI)
250191bc56edSDimitry Andric       return false;
250291bc56edSDimitry Andric   }
250391bc56edSDimitry Andric 
250491bc56edSDimitry Andric   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
250591bc56edSDimitry Andric   /// call.
2506d88c1a5aSDimitry Andric   const Function *F = BB->getParent();
250791bc56edSDimitry Andric   SmallVector<CallInst*, 4> TailCalls;
250891bc56edSDimitry Andric   if (PN) {
250991bc56edSDimitry Andric     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
251091bc56edSDimitry Andric       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
251191bc56edSDimitry Andric       // Make sure the phi value is indeed produced by the tail call.
251291bc56edSDimitry Andric       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
2513d88c1a5aSDimitry Andric           TLI->mayBeEmittedAsTailCall(CI) &&
2514d88c1a5aSDimitry Andric           attributesPermitTailCall(F, CI, RetI, *TLI))
251591bc56edSDimitry Andric         TailCalls.push_back(CI);
251691bc56edSDimitry Andric     }
251791bc56edSDimitry Andric   } else {
251891bc56edSDimitry Andric     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
251991bc56edSDimitry Andric     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
252039d628a0SDimitry Andric       if (!VisitedBBs.insert(*PI).second)
252191bc56edSDimitry Andric         continue;
252291bc56edSDimitry Andric 
252391bc56edSDimitry Andric       BasicBlock::InstListType &InstList = (*PI)->getInstList();
252491bc56edSDimitry Andric       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
252591bc56edSDimitry Andric       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
252691bc56edSDimitry Andric       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
252791bc56edSDimitry Andric       if (RI == RE)
252891bc56edSDimitry Andric         continue;
252991bc56edSDimitry Andric 
253091bc56edSDimitry Andric       CallInst *CI = dyn_cast<CallInst>(&*RI);
2531d88c1a5aSDimitry Andric       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2532d88c1a5aSDimitry Andric           attributesPermitTailCall(F, CI, RetI, *TLI))
253391bc56edSDimitry Andric         TailCalls.push_back(CI);
253491bc56edSDimitry Andric     }
253591bc56edSDimitry Andric   }
253691bc56edSDimitry Andric 
253791bc56edSDimitry Andric   bool Changed = false;
253891bc56edSDimitry Andric   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
253991bc56edSDimitry Andric     CallInst *CI = TailCalls[i];
254091bc56edSDimitry Andric     CallSite CS(CI);
254191bc56edSDimitry Andric 
254291bc56edSDimitry Andric     // Conservatively require the attributes of the call to match those of the
254391bc56edSDimitry Andric     // return. Ignore noalias because it doesn't affect the call sequence.
25447a7e6055SDimitry Andric     AttributeList CalleeAttrs = CS.getAttributes();
25457a7e6055SDimitry Andric     if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
25467a7e6055SDimitry Andric             .removeAttribute(Attribute::NoAlias) !=
25477a7e6055SDimitry Andric         AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
25487a7e6055SDimitry Andric             .removeAttribute(Attribute::NoAlias))
254991bc56edSDimitry Andric       continue;
255091bc56edSDimitry Andric 
255191bc56edSDimitry Andric     // Make sure the call instruction is followed by an unconditional branch to
255291bc56edSDimitry Andric     // the return block.
255391bc56edSDimitry Andric     BasicBlock *CallBB = CI->getParent();
255491bc56edSDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
255591bc56edSDimitry Andric     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
255691bc56edSDimitry Andric       continue;
255791bc56edSDimitry Andric 
255891bc56edSDimitry Andric     // Duplicate the return into CallBB.
2559d88c1a5aSDimitry Andric     (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
256091bc56edSDimitry Andric     ModifiedDT = Changed = true;
256191bc56edSDimitry Andric     ++NumRetsDup;
256291bc56edSDimitry Andric   }
256391bc56edSDimitry Andric 
256491bc56edSDimitry Andric   // If we eliminated all predecessors of the block, delete the block now.
256591bc56edSDimitry Andric   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
256691bc56edSDimitry Andric     BB->eraseFromParent();
256791bc56edSDimitry Andric 
256891bc56edSDimitry Andric   return Changed;
256991bc56edSDimitry Andric }
257091bc56edSDimitry Andric 
257191bc56edSDimitry Andric //===----------------------------------------------------------------------===//
257291bc56edSDimitry Andric // Memory Optimization
257391bc56edSDimitry Andric //===----------------------------------------------------------------------===//
257491bc56edSDimitry Andric 
257591bc56edSDimitry Andric namespace {
257691bc56edSDimitry Andric 
25777d523365SDimitry Andric /// This is an extended version of TargetLowering::AddrMode
257891bc56edSDimitry Andric /// which holds actual Value*'s for register values.
257991bc56edSDimitry Andric struct ExtAddrMode : public TargetLowering::AddrMode {
258091bc56edSDimitry Andric   Value *BaseReg;
258191bc56edSDimitry Andric   Value *ScaledReg;
258291bc56edSDimitry Andric   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
258391bc56edSDimitry Andric   void print(raw_ostream &OS) const;
258491bc56edSDimitry Andric   void dump() const;
258591bc56edSDimitry Andric 
258691bc56edSDimitry Andric   bool operator==(const ExtAddrMode& O) const {
258791bc56edSDimitry Andric     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
258891bc56edSDimitry Andric            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
258991bc56edSDimitry Andric            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
259091bc56edSDimitry Andric   }
259191bc56edSDimitry Andric };
259291bc56edSDimitry Andric 
259391bc56edSDimitry Andric #ifndef NDEBUG
259491bc56edSDimitry Andric static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
259591bc56edSDimitry Andric   AM.print(OS);
259691bc56edSDimitry Andric   return OS;
259791bc56edSDimitry Andric }
259891bc56edSDimitry Andric #endif
259991bc56edSDimitry Andric 
260091bc56edSDimitry Andric void ExtAddrMode::print(raw_ostream &OS) const {
260191bc56edSDimitry Andric   bool NeedPlus = false;
260291bc56edSDimitry Andric   OS << "[";
260391bc56edSDimitry Andric   if (BaseGV) {
260491bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
260591bc56edSDimitry Andric        << "GV:";
260691bc56edSDimitry Andric     BaseGV->printAsOperand(OS, /*PrintType=*/false);
260791bc56edSDimitry Andric     NeedPlus = true;
260891bc56edSDimitry Andric   }
260991bc56edSDimitry Andric 
261091bc56edSDimitry Andric   if (BaseOffs) {
261191bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
261291bc56edSDimitry Andric        << BaseOffs;
261391bc56edSDimitry Andric     NeedPlus = true;
261491bc56edSDimitry Andric   }
261591bc56edSDimitry Andric 
261691bc56edSDimitry Andric   if (BaseReg) {
261791bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
261891bc56edSDimitry Andric        << "Base:";
261991bc56edSDimitry Andric     BaseReg->printAsOperand(OS, /*PrintType=*/false);
262091bc56edSDimitry Andric     NeedPlus = true;
262191bc56edSDimitry Andric   }
262291bc56edSDimitry Andric   if (Scale) {
262391bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
262491bc56edSDimitry Andric        << Scale << "*";
262591bc56edSDimitry Andric     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
262691bc56edSDimitry Andric   }
262791bc56edSDimitry Andric 
262891bc56edSDimitry Andric   OS << ']';
262991bc56edSDimitry Andric }
263091bc56edSDimitry Andric 
263191bc56edSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
26323ca95b02SDimitry Andric LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
263391bc56edSDimitry Andric   print(dbgs());
263491bc56edSDimitry Andric   dbgs() << '\n';
263591bc56edSDimitry Andric }
263691bc56edSDimitry Andric #endif
263791bc56edSDimitry Andric 
263891bc56edSDimitry Andric /// \brief This class provides transaction based operation on the IR.
263991bc56edSDimitry Andric /// Every change made through this class is recorded in the internal state and
264091bc56edSDimitry Andric /// can be undone (rollback) until commit is called.
264191bc56edSDimitry Andric class TypePromotionTransaction {
264291bc56edSDimitry Andric 
264391bc56edSDimitry Andric   /// \brief This represents the common interface of the individual transaction.
264491bc56edSDimitry Andric   /// Each class implements the logic for doing one specific modification on
264591bc56edSDimitry Andric   /// the IR via the TypePromotionTransaction.
264691bc56edSDimitry Andric   class TypePromotionAction {
264791bc56edSDimitry Andric   protected:
264891bc56edSDimitry Andric     /// The Instruction modified.
264991bc56edSDimitry Andric     Instruction *Inst;
265091bc56edSDimitry Andric 
265191bc56edSDimitry Andric   public:
265291bc56edSDimitry Andric     /// \brief Constructor of the action.
265391bc56edSDimitry Andric     /// The constructor performs the related action on the IR.
265491bc56edSDimitry Andric     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
265591bc56edSDimitry Andric 
265691bc56edSDimitry Andric     virtual ~TypePromotionAction() {}
265791bc56edSDimitry Andric 
265891bc56edSDimitry Andric     /// \brief Undo the modification done by this action.
265991bc56edSDimitry Andric     /// When this method is called, the IR must be in the same state as it was
266091bc56edSDimitry Andric     /// before this action was applied.
266191bc56edSDimitry Andric     /// \pre Undoing the action works if and only if the IR is in the exact same
266291bc56edSDimitry Andric     /// state as it was directly after this action was applied.
266391bc56edSDimitry Andric     virtual void undo() = 0;
266491bc56edSDimitry Andric 
266591bc56edSDimitry Andric     /// \brief Advocate every change made by this action.
266691bc56edSDimitry Andric     /// When the results on the IR of the action are to be kept, it is important
266791bc56edSDimitry Andric     /// to call this function, otherwise hidden information may be kept forever.
266891bc56edSDimitry Andric     virtual void commit() {
266991bc56edSDimitry Andric       // Nothing to be done, this action is not doing anything.
267091bc56edSDimitry Andric     }
267191bc56edSDimitry Andric   };
267291bc56edSDimitry Andric 
267391bc56edSDimitry Andric   /// \brief Utility to remember the position of an instruction.
267491bc56edSDimitry Andric   class InsertionHandler {
267591bc56edSDimitry Andric     /// Position of an instruction.
267691bc56edSDimitry Andric     /// Either an instruction:
267791bc56edSDimitry Andric     /// - Is the first in a basic block: BB is used.
267891bc56edSDimitry Andric     /// - Has a previous instructon: PrevInst is used.
267991bc56edSDimitry Andric     union {
268091bc56edSDimitry Andric       Instruction *PrevInst;
268191bc56edSDimitry Andric       BasicBlock *BB;
268291bc56edSDimitry Andric     } Point;
268391bc56edSDimitry Andric     /// Remember whether or not the instruction had a previous instruction.
268491bc56edSDimitry Andric     bool HasPrevInstruction;
268591bc56edSDimitry Andric 
268691bc56edSDimitry Andric   public:
268791bc56edSDimitry Andric     /// \brief Record the position of \p Inst.
268891bc56edSDimitry Andric     InsertionHandler(Instruction *Inst) {
26897d523365SDimitry Andric       BasicBlock::iterator It = Inst->getIterator();
269091bc56edSDimitry Andric       HasPrevInstruction = (It != (Inst->getParent()->begin()));
269191bc56edSDimitry Andric       if (HasPrevInstruction)
26927d523365SDimitry Andric         Point.PrevInst = &*--It;
269391bc56edSDimitry Andric       else
269491bc56edSDimitry Andric         Point.BB = Inst->getParent();
269591bc56edSDimitry Andric     }
269691bc56edSDimitry Andric 
269791bc56edSDimitry Andric     /// \brief Insert \p Inst at the recorded position.
269891bc56edSDimitry Andric     void insert(Instruction *Inst) {
269991bc56edSDimitry Andric       if (HasPrevInstruction) {
270091bc56edSDimitry Andric         if (Inst->getParent())
270191bc56edSDimitry Andric           Inst->removeFromParent();
270291bc56edSDimitry Andric         Inst->insertAfter(Point.PrevInst);
270391bc56edSDimitry Andric       } else {
27047d523365SDimitry Andric         Instruction *Position = &*Point.BB->getFirstInsertionPt();
270591bc56edSDimitry Andric         if (Inst->getParent())
270691bc56edSDimitry Andric           Inst->moveBefore(Position);
270791bc56edSDimitry Andric         else
270891bc56edSDimitry Andric           Inst->insertBefore(Position);
270991bc56edSDimitry Andric       }
271091bc56edSDimitry Andric     }
271191bc56edSDimitry Andric   };
271291bc56edSDimitry Andric 
271391bc56edSDimitry Andric   /// \brief Move an instruction before another.
271491bc56edSDimitry Andric   class InstructionMoveBefore : public TypePromotionAction {
271591bc56edSDimitry Andric     /// Original position of the instruction.
271691bc56edSDimitry Andric     InsertionHandler Position;
271791bc56edSDimitry Andric 
271891bc56edSDimitry Andric   public:
271991bc56edSDimitry Andric     /// \brief Move \p Inst before \p Before.
272091bc56edSDimitry Andric     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
272191bc56edSDimitry Andric         : TypePromotionAction(Inst), Position(Inst) {
272291bc56edSDimitry Andric       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
272391bc56edSDimitry Andric       Inst->moveBefore(Before);
272491bc56edSDimitry Andric     }
272591bc56edSDimitry Andric 
272691bc56edSDimitry Andric     /// \brief Move the instruction back to its original position.
272791bc56edSDimitry Andric     void undo() override {
272891bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
272991bc56edSDimitry Andric       Position.insert(Inst);
273091bc56edSDimitry Andric     }
273191bc56edSDimitry Andric   };
273291bc56edSDimitry Andric 
273391bc56edSDimitry Andric   /// \brief Set the operand of an instruction with a new value.
273491bc56edSDimitry Andric   class OperandSetter : public TypePromotionAction {
273591bc56edSDimitry Andric     /// Original operand of the instruction.
273691bc56edSDimitry Andric     Value *Origin;
273791bc56edSDimitry Andric     /// Index of the modified instruction.
273891bc56edSDimitry Andric     unsigned Idx;
273991bc56edSDimitry Andric 
274091bc56edSDimitry Andric   public:
274191bc56edSDimitry Andric     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
274291bc56edSDimitry Andric     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
274391bc56edSDimitry Andric         : TypePromotionAction(Inst), Idx(Idx) {
274491bc56edSDimitry Andric       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
274591bc56edSDimitry Andric                    << "for:" << *Inst << "\n"
274691bc56edSDimitry Andric                    << "with:" << *NewVal << "\n");
274791bc56edSDimitry Andric       Origin = Inst->getOperand(Idx);
274891bc56edSDimitry Andric       Inst->setOperand(Idx, NewVal);
274991bc56edSDimitry Andric     }
275091bc56edSDimitry Andric 
275191bc56edSDimitry Andric     /// \brief Restore the original value of the instruction.
275291bc56edSDimitry Andric     void undo() override {
275391bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
275491bc56edSDimitry Andric                    << "for: " << *Inst << "\n"
275591bc56edSDimitry Andric                    << "with: " << *Origin << "\n");
275691bc56edSDimitry Andric       Inst->setOperand(Idx, Origin);
275791bc56edSDimitry Andric     }
275891bc56edSDimitry Andric   };
275991bc56edSDimitry Andric 
276091bc56edSDimitry Andric   /// \brief Hide the operands of an instruction.
276191bc56edSDimitry Andric   /// Do as if this instruction was not using any of its operands.
276291bc56edSDimitry Andric   class OperandsHider : public TypePromotionAction {
276391bc56edSDimitry Andric     /// The list of original operands.
276491bc56edSDimitry Andric     SmallVector<Value *, 4> OriginalValues;
276591bc56edSDimitry Andric 
276691bc56edSDimitry Andric   public:
276791bc56edSDimitry Andric     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
276891bc56edSDimitry Andric     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
276991bc56edSDimitry Andric       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
277091bc56edSDimitry Andric       unsigned NumOpnds = Inst->getNumOperands();
277191bc56edSDimitry Andric       OriginalValues.reserve(NumOpnds);
277291bc56edSDimitry Andric       for (unsigned It = 0; It < NumOpnds; ++It) {
277391bc56edSDimitry Andric         // Save the current operand.
277491bc56edSDimitry Andric         Value *Val = Inst->getOperand(It);
277591bc56edSDimitry Andric         OriginalValues.push_back(Val);
277691bc56edSDimitry Andric         // Set a dummy one.
27777d523365SDimitry Andric         // We could use OperandSetter here, but that would imply an overhead
277891bc56edSDimitry Andric         // that we are not willing to pay.
277991bc56edSDimitry Andric         Inst->setOperand(It, UndefValue::get(Val->getType()));
278091bc56edSDimitry Andric       }
278191bc56edSDimitry Andric     }
278291bc56edSDimitry Andric 
278391bc56edSDimitry Andric     /// \brief Restore the original list of uses.
278491bc56edSDimitry Andric     void undo() override {
278591bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
278691bc56edSDimitry Andric       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
278791bc56edSDimitry Andric         Inst->setOperand(It, OriginalValues[It]);
278891bc56edSDimitry Andric     }
278991bc56edSDimitry Andric   };
279091bc56edSDimitry Andric 
279191bc56edSDimitry Andric   /// \brief Build a truncate instruction.
279291bc56edSDimitry Andric   class TruncBuilder : public TypePromotionAction {
279339d628a0SDimitry Andric     Value *Val;
279491bc56edSDimitry Andric   public:
279591bc56edSDimitry Andric     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
279691bc56edSDimitry Andric     /// result.
279791bc56edSDimitry Andric     /// trunc Opnd to Ty.
279891bc56edSDimitry Andric     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
279991bc56edSDimitry Andric       IRBuilder<> Builder(Opnd);
280039d628a0SDimitry Andric       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
280139d628a0SDimitry Andric       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
280291bc56edSDimitry Andric     }
280391bc56edSDimitry Andric 
280439d628a0SDimitry Andric     /// \brief Get the built value.
280539d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
280691bc56edSDimitry Andric 
280791bc56edSDimitry Andric     /// \brief Remove the built instruction.
280891bc56edSDimitry Andric     void undo() override {
280939d628a0SDimitry Andric       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
281039d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
281139d628a0SDimitry Andric         IVal->eraseFromParent();
281291bc56edSDimitry Andric     }
281391bc56edSDimitry Andric   };
281491bc56edSDimitry Andric 
281591bc56edSDimitry Andric   /// \brief Build a sign extension instruction.
281691bc56edSDimitry Andric   class SExtBuilder : public TypePromotionAction {
281739d628a0SDimitry Andric     Value *Val;
281891bc56edSDimitry Andric   public:
281991bc56edSDimitry Andric     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
282091bc56edSDimitry Andric     /// result.
282191bc56edSDimitry Andric     /// sext Opnd to Ty.
282291bc56edSDimitry Andric     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
282339d628a0SDimitry Andric         : TypePromotionAction(InsertPt) {
282491bc56edSDimitry Andric       IRBuilder<> Builder(InsertPt);
282539d628a0SDimitry Andric       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
282639d628a0SDimitry Andric       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
282791bc56edSDimitry Andric     }
282891bc56edSDimitry Andric 
282939d628a0SDimitry Andric     /// \brief Get the built value.
283039d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
283191bc56edSDimitry Andric 
283291bc56edSDimitry Andric     /// \brief Remove the built instruction.
283391bc56edSDimitry Andric     void undo() override {
283439d628a0SDimitry Andric       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
283539d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
283639d628a0SDimitry Andric         IVal->eraseFromParent();
283739d628a0SDimitry Andric     }
283839d628a0SDimitry Andric   };
283939d628a0SDimitry Andric 
284039d628a0SDimitry Andric   /// \brief Build a zero extension instruction.
284139d628a0SDimitry Andric   class ZExtBuilder : public TypePromotionAction {
284239d628a0SDimitry Andric     Value *Val;
284339d628a0SDimitry Andric   public:
284439d628a0SDimitry Andric     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
284539d628a0SDimitry Andric     /// result.
284639d628a0SDimitry Andric     /// zext Opnd to Ty.
284739d628a0SDimitry Andric     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
284839d628a0SDimitry Andric         : TypePromotionAction(InsertPt) {
284939d628a0SDimitry Andric       IRBuilder<> Builder(InsertPt);
285039d628a0SDimitry Andric       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
285139d628a0SDimitry Andric       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
285239d628a0SDimitry Andric     }
285339d628a0SDimitry Andric 
285439d628a0SDimitry Andric     /// \brief Get the built value.
285539d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
285639d628a0SDimitry Andric 
285739d628a0SDimitry Andric     /// \brief Remove the built instruction.
285839d628a0SDimitry Andric     void undo() override {
285939d628a0SDimitry Andric       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
286039d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
286139d628a0SDimitry Andric         IVal->eraseFromParent();
286291bc56edSDimitry Andric     }
286391bc56edSDimitry Andric   };
286491bc56edSDimitry Andric 
286591bc56edSDimitry Andric   /// \brief Mutate an instruction to another type.
286691bc56edSDimitry Andric   class TypeMutator : public TypePromotionAction {
286791bc56edSDimitry Andric     /// Record the original type.
286891bc56edSDimitry Andric     Type *OrigTy;
286991bc56edSDimitry Andric 
287091bc56edSDimitry Andric   public:
287191bc56edSDimitry Andric     /// \brief Mutate the type of \p Inst into \p NewTy.
287291bc56edSDimitry Andric     TypeMutator(Instruction *Inst, Type *NewTy)
287391bc56edSDimitry Andric         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
287491bc56edSDimitry Andric       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
287591bc56edSDimitry Andric                    << "\n");
287691bc56edSDimitry Andric       Inst->mutateType(NewTy);
287791bc56edSDimitry Andric     }
287891bc56edSDimitry Andric 
287991bc56edSDimitry Andric     /// \brief Mutate the instruction back to its original type.
288091bc56edSDimitry Andric     void undo() override {
288191bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
288291bc56edSDimitry Andric                    << "\n");
288391bc56edSDimitry Andric       Inst->mutateType(OrigTy);
288491bc56edSDimitry Andric     }
288591bc56edSDimitry Andric   };
288691bc56edSDimitry Andric 
288791bc56edSDimitry Andric   /// \brief Replace the uses of an instruction by another instruction.
288891bc56edSDimitry Andric   class UsesReplacer : public TypePromotionAction {
288991bc56edSDimitry Andric     /// Helper structure to keep track of the replaced uses.
289091bc56edSDimitry Andric     struct InstructionAndIdx {
289191bc56edSDimitry Andric       /// The instruction using the instruction.
289291bc56edSDimitry Andric       Instruction *Inst;
289391bc56edSDimitry Andric       /// The index where this instruction is used for Inst.
289491bc56edSDimitry Andric       unsigned Idx;
289591bc56edSDimitry Andric       InstructionAndIdx(Instruction *Inst, unsigned Idx)
289691bc56edSDimitry Andric           : Inst(Inst), Idx(Idx) {}
289791bc56edSDimitry Andric     };
289891bc56edSDimitry Andric 
289991bc56edSDimitry Andric     /// Keep track of the original uses (pair Instruction, Index).
290091bc56edSDimitry Andric     SmallVector<InstructionAndIdx, 4> OriginalUses;
290191bc56edSDimitry Andric     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
290291bc56edSDimitry Andric 
290391bc56edSDimitry Andric   public:
290491bc56edSDimitry Andric     /// \brief Replace all the use of \p Inst by \p New.
290591bc56edSDimitry Andric     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
290691bc56edSDimitry Andric       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
290791bc56edSDimitry Andric                    << "\n");
290891bc56edSDimitry Andric       // Record the original uses.
290991bc56edSDimitry Andric       for (Use &U : Inst->uses()) {
291091bc56edSDimitry Andric         Instruction *UserI = cast<Instruction>(U.getUser());
291191bc56edSDimitry Andric         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
291291bc56edSDimitry Andric       }
291391bc56edSDimitry Andric       // Now, we can replace the uses.
291491bc56edSDimitry Andric       Inst->replaceAllUsesWith(New);
291591bc56edSDimitry Andric     }
291691bc56edSDimitry Andric 
291791bc56edSDimitry Andric     /// \brief Reassign the original uses of Inst to Inst.
291891bc56edSDimitry Andric     void undo() override {
291991bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
292091bc56edSDimitry Andric       for (use_iterator UseIt = OriginalUses.begin(),
292191bc56edSDimitry Andric                         EndIt = OriginalUses.end();
292291bc56edSDimitry Andric            UseIt != EndIt; ++UseIt) {
292391bc56edSDimitry Andric         UseIt->Inst->setOperand(UseIt->Idx, Inst);
292491bc56edSDimitry Andric       }
292591bc56edSDimitry Andric     }
292691bc56edSDimitry Andric   };
292791bc56edSDimitry Andric 
292891bc56edSDimitry Andric   /// \brief Remove an instruction from the IR.
292991bc56edSDimitry Andric   class InstructionRemover : public TypePromotionAction {
293091bc56edSDimitry Andric     /// Original position of the instruction.
293191bc56edSDimitry Andric     InsertionHandler Inserter;
293291bc56edSDimitry Andric     /// Helper structure to hide all the link to the instruction. In other
293391bc56edSDimitry Andric     /// words, this helps to do as if the instruction was removed.
293491bc56edSDimitry Andric     OperandsHider Hider;
293591bc56edSDimitry Andric     /// Keep track of the uses replaced, if any.
293691bc56edSDimitry Andric     UsesReplacer *Replacer;
29377a7e6055SDimitry Andric     /// Keep track of instructions removed.
29387a7e6055SDimitry Andric     SetOfInstrs &RemovedInsts;
293991bc56edSDimitry Andric 
294091bc56edSDimitry Andric   public:
294191bc56edSDimitry Andric     /// \brief Remove all reference of \p Inst and optinally replace all its
294291bc56edSDimitry Andric     /// uses with New.
29437a7e6055SDimitry Andric     /// \p RemovedInsts Keep track of the instructions removed by this Action.
294491bc56edSDimitry Andric     /// \pre If !Inst->use_empty(), then New != nullptr
29457a7e6055SDimitry Andric     InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
29467a7e6055SDimitry Andric                        Value *New = nullptr)
294791bc56edSDimitry Andric         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
29487a7e6055SDimitry Andric           Replacer(nullptr), RemovedInsts(RemovedInsts) {
294991bc56edSDimitry Andric       if (New)
295091bc56edSDimitry Andric         Replacer = new UsesReplacer(Inst, New);
295191bc56edSDimitry Andric       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
29527a7e6055SDimitry Andric       RemovedInsts.insert(Inst);
29537a7e6055SDimitry Andric       /// The instructions removed here will be freed after completing
29547a7e6055SDimitry Andric       /// optimizeBlock() for all blocks as we need to keep track of the
29557a7e6055SDimitry Andric       /// removed instructions during promotion.
295691bc56edSDimitry Andric       Inst->removeFromParent();
295791bc56edSDimitry Andric     }
295891bc56edSDimitry Andric 
2959ff0cc061SDimitry Andric     ~InstructionRemover() override { delete Replacer; }
296091bc56edSDimitry Andric 
296191bc56edSDimitry Andric     /// \brief Resurrect the instruction and reassign it to the proper uses if
296291bc56edSDimitry Andric     /// new value was provided when build this action.
296391bc56edSDimitry Andric     void undo() override {
296491bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
296591bc56edSDimitry Andric       Inserter.insert(Inst);
296691bc56edSDimitry Andric       if (Replacer)
296791bc56edSDimitry Andric         Replacer->undo();
296891bc56edSDimitry Andric       Hider.undo();
29697a7e6055SDimitry Andric       RemovedInsts.erase(Inst);
297091bc56edSDimitry Andric     }
297191bc56edSDimitry Andric   };
297291bc56edSDimitry Andric 
297391bc56edSDimitry Andric public:
297491bc56edSDimitry Andric   /// Restoration point.
297591bc56edSDimitry Andric   /// The restoration point is a pointer to an action instead of an iterator
297691bc56edSDimitry Andric   /// because the iterator may be invalidated but not the pointer.
297791bc56edSDimitry Andric   typedef const TypePromotionAction *ConstRestorationPt;
29787a7e6055SDimitry Andric 
29797a7e6055SDimitry Andric   TypePromotionTransaction(SetOfInstrs &RemovedInsts)
29807a7e6055SDimitry Andric       : RemovedInsts(RemovedInsts) {}
29817a7e6055SDimitry Andric 
298291bc56edSDimitry Andric   /// Advocate every changes made in that transaction.
298391bc56edSDimitry Andric   void commit();
298491bc56edSDimitry Andric   /// Undo all the changes made after the given point.
298591bc56edSDimitry Andric   void rollback(ConstRestorationPt Point);
298691bc56edSDimitry Andric   /// Get the current restoration point.
298791bc56edSDimitry Andric   ConstRestorationPt getRestorationPoint() const;
298891bc56edSDimitry Andric 
298991bc56edSDimitry Andric   /// \name API for IR modification with state keeping to support rollback.
299091bc56edSDimitry Andric   /// @{
299191bc56edSDimitry Andric   /// Same as Instruction::setOperand.
299291bc56edSDimitry Andric   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
299391bc56edSDimitry Andric   /// Same as Instruction::eraseFromParent.
299491bc56edSDimitry Andric   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
299591bc56edSDimitry Andric   /// Same as Value::replaceAllUsesWith.
299691bc56edSDimitry Andric   void replaceAllUsesWith(Instruction *Inst, Value *New);
299791bc56edSDimitry Andric   /// Same as Value::mutateType.
299891bc56edSDimitry Andric   void mutateType(Instruction *Inst, Type *NewTy);
299991bc56edSDimitry Andric   /// Same as IRBuilder::createTrunc.
300039d628a0SDimitry Andric   Value *createTrunc(Instruction *Opnd, Type *Ty);
300191bc56edSDimitry Andric   /// Same as IRBuilder::createSExt.
300239d628a0SDimitry Andric   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
300339d628a0SDimitry Andric   /// Same as IRBuilder::createZExt.
300439d628a0SDimitry Andric   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
300591bc56edSDimitry Andric   /// Same as Instruction::moveBefore.
300691bc56edSDimitry Andric   void moveBefore(Instruction *Inst, Instruction *Before);
300791bc56edSDimitry Andric   /// @}
300891bc56edSDimitry Andric 
300991bc56edSDimitry Andric private:
301091bc56edSDimitry Andric   /// The ordered list of actions made so far.
301191bc56edSDimitry Andric   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
301291bc56edSDimitry Andric   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
30137a7e6055SDimitry Andric   SetOfInstrs &RemovedInsts;
301491bc56edSDimitry Andric };
301591bc56edSDimitry Andric 
301691bc56edSDimitry Andric void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
301791bc56edSDimitry Andric                                           Value *NewVal) {
301891bc56edSDimitry Andric   Actions.push_back(
301991bc56edSDimitry Andric       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
302091bc56edSDimitry Andric }
302191bc56edSDimitry Andric 
302291bc56edSDimitry Andric void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
302391bc56edSDimitry Andric                                                 Value *NewVal) {
302491bc56edSDimitry Andric   Actions.push_back(
30257a7e6055SDimitry Andric       make_unique<TypePromotionTransaction::InstructionRemover>(Inst,
30267a7e6055SDimitry Andric                                                          RemovedInsts, NewVal));
302791bc56edSDimitry Andric }
302891bc56edSDimitry Andric 
302991bc56edSDimitry Andric void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
303091bc56edSDimitry Andric                                                   Value *New) {
303191bc56edSDimitry Andric   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
303291bc56edSDimitry Andric }
303391bc56edSDimitry Andric 
303491bc56edSDimitry Andric void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
303591bc56edSDimitry Andric   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
303691bc56edSDimitry Andric }
303791bc56edSDimitry Andric 
303839d628a0SDimitry Andric Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
303991bc56edSDimitry Andric                                              Type *Ty) {
304091bc56edSDimitry Andric   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
304139d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
304291bc56edSDimitry Andric   Actions.push_back(std::move(Ptr));
304339d628a0SDimitry Andric   return Val;
304491bc56edSDimitry Andric }
304591bc56edSDimitry Andric 
304639d628a0SDimitry Andric Value *TypePromotionTransaction::createSExt(Instruction *Inst,
304791bc56edSDimitry Andric                                             Value *Opnd, Type *Ty) {
304891bc56edSDimitry Andric   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
304939d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
305091bc56edSDimitry Andric   Actions.push_back(std::move(Ptr));
305139d628a0SDimitry Andric   return Val;
305239d628a0SDimitry Andric }
305339d628a0SDimitry Andric 
305439d628a0SDimitry Andric Value *TypePromotionTransaction::createZExt(Instruction *Inst,
305539d628a0SDimitry Andric                                             Value *Opnd, Type *Ty) {
305639d628a0SDimitry Andric   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
305739d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
305839d628a0SDimitry Andric   Actions.push_back(std::move(Ptr));
305939d628a0SDimitry Andric   return Val;
306091bc56edSDimitry Andric }
306191bc56edSDimitry Andric 
306291bc56edSDimitry Andric void TypePromotionTransaction::moveBefore(Instruction *Inst,
306391bc56edSDimitry Andric                                           Instruction *Before) {
306491bc56edSDimitry Andric   Actions.push_back(
306591bc56edSDimitry Andric       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
306691bc56edSDimitry Andric }
306791bc56edSDimitry Andric 
306891bc56edSDimitry Andric TypePromotionTransaction::ConstRestorationPt
306991bc56edSDimitry Andric TypePromotionTransaction::getRestorationPoint() const {
307091bc56edSDimitry Andric   return !Actions.empty() ? Actions.back().get() : nullptr;
307191bc56edSDimitry Andric }
307291bc56edSDimitry Andric 
307391bc56edSDimitry Andric void TypePromotionTransaction::commit() {
307491bc56edSDimitry Andric   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
307591bc56edSDimitry Andric        ++It)
307691bc56edSDimitry Andric     (*It)->commit();
307791bc56edSDimitry Andric   Actions.clear();
307891bc56edSDimitry Andric }
307991bc56edSDimitry Andric 
308091bc56edSDimitry Andric void TypePromotionTransaction::rollback(
308191bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt Point) {
308291bc56edSDimitry Andric   while (!Actions.empty() && Point != Actions.back().get()) {
308391bc56edSDimitry Andric     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
308491bc56edSDimitry Andric     Curr->undo();
308591bc56edSDimitry Andric   }
308691bc56edSDimitry Andric }
308791bc56edSDimitry Andric 
308891bc56edSDimitry Andric /// \brief A helper class for matching addressing modes.
308991bc56edSDimitry Andric ///
309091bc56edSDimitry Andric /// This encapsulates the logic for matching the target-legal addressing modes.
309191bc56edSDimitry Andric class AddressingModeMatcher {
309291bc56edSDimitry Andric   SmallVectorImpl<Instruction*> &AddrModeInsts;
309391bc56edSDimitry Andric   const TargetLowering &TLI;
30947a7e6055SDimitry Andric   const TargetRegisterInfo &TRI;
3095875ed548SDimitry Andric   const DataLayout &DL;
309691bc56edSDimitry Andric 
309791bc56edSDimitry Andric   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
309891bc56edSDimitry Andric   /// the memory instruction that we're computing this address for.
309991bc56edSDimitry Andric   Type *AccessTy;
310097bc6c73SDimitry Andric   unsigned AddrSpace;
310191bc56edSDimitry Andric   Instruction *MemoryInst;
310291bc56edSDimitry Andric 
31037d523365SDimitry Andric   /// This is the addressing mode that we're building up. This is
310491bc56edSDimitry Andric   /// part of the return value of this addressing mode matching stuff.
310591bc56edSDimitry Andric   ExtAddrMode &AddrMode;
310691bc56edSDimitry Andric 
31078f0fd8f6SDimitry Andric   /// The instructions inserted by other CodeGenPrepare optimizations.
31088f0fd8f6SDimitry Andric   const SetOfInstrs &InsertedInsts;
310991bc56edSDimitry Andric   /// A map from the instructions to their type before promotion.
311091bc56edSDimitry Andric   InstrToOrigTy &PromotedInsts;
311191bc56edSDimitry Andric   /// The ongoing transaction where every action should be registered.
311291bc56edSDimitry Andric   TypePromotionTransaction &TPT;
311391bc56edSDimitry Andric 
31147d523365SDimitry Andric   /// This is set to true when we should not do profitability checks.
31157d523365SDimitry Andric   /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
311691bc56edSDimitry Andric   bool IgnoreProfitability;
311791bc56edSDimitry Andric 
311891bc56edSDimitry Andric   AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
31197a7e6055SDimitry Andric                         const TargetLowering &TLI,
31207a7e6055SDimitry Andric                         const TargetRegisterInfo &TRI,
31217a7e6055SDimitry Andric                         Type *AT, unsigned AS,
312297bc6c73SDimitry Andric                         Instruction *MI, ExtAddrMode &AM,
31238f0fd8f6SDimitry Andric                         const SetOfInstrs &InsertedInsts,
312491bc56edSDimitry Andric                         InstrToOrigTy &PromotedInsts,
312591bc56edSDimitry Andric                         TypePromotionTransaction &TPT)
31267a7e6055SDimitry Andric       : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3127875ed548SDimitry Andric         DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3128875ed548SDimitry Andric         MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
3129875ed548SDimitry Andric         PromotedInsts(PromotedInsts), TPT(TPT) {
313091bc56edSDimitry Andric     IgnoreProfitability = false;
313191bc56edSDimitry Andric   }
313291bc56edSDimitry Andric public:
313391bc56edSDimitry Andric 
31347d523365SDimitry Andric   /// Find the maximal addressing mode that a load/store of V can fold,
313591bc56edSDimitry Andric   /// give an access type of AccessTy.  This returns a list of involved
313691bc56edSDimitry Andric   /// instructions in AddrModeInsts.
31378f0fd8f6SDimitry Andric   /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
313891bc56edSDimitry Andric   /// optimizations.
313991bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
314091bc56edSDimitry Andric   /// \p The ongoing transaction where every action should be registered.
314197bc6c73SDimitry Andric   static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
314291bc56edSDimitry Andric                            Instruction *MemoryInst,
314391bc56edSDimitry Andric                            SmallVectorImpl<Instruction*> &AddrModeInsts,
31447a7e6055SDimitry Andric                            const TargetLowering &TLI,
31457a7e6055SDimitry Andric                            const TargetRegisterInfo &TRI,
31468f0fd8f6SDimitry Andric                            const SetOfInstrs &InsertedInsts,
314791bc56edSDimitry Andric                            InstrToOrigTy &PromotedInsts,
314891bc56edSDimitry Andric                            TypePromotionTransaction &TPT) {
314991bc56edSDimitry Andric     ExtAddrMode Result;
315091bc56edSDimitry Andric 
31517a7e6055SDimitry Andric     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
31527a7e6055SDimitry Andric                                          AccessTy, AS,
31538f0fd8f6SDimitry Andric                                          MemoryInst, Result, InsertedInsts,
31547d523365SDimitry Andric                                          PromotedInsts, TPT).matchAddr(V, 0);
315591bc56edSDimitry Andric     (void)Success; assert(Success && "Couldn't select *anything*?");
315691bc56edSDimitry Andric     return Result;
315791bc56edSDimitry Andric   }
315891bc56edSDimitry Andric private:
31597d523365SDimitry Andric   bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
31607d523365SDimitry Andric   bool matchAddr(Value *V, unsigned Depth);
31617d523365SDimitry Andric   bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
316291bc56edSDimitry Andric                           bool *MovedAway = nullptr);
31637d523365SDimitry Andric   bool isProfitableToFoldIntoAddressingMode(Instruction *I,
316491bc56edSDimitry Andric                                             ExtAddrMode &AMBefore,
316591bc56edSDimitry Andric                                             ExtAddrMode &AMAfter);
31667d523365SDimitry Andric   bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
31677d523365SDimitry Andric   bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
316891bc56edSDimitry Andric                              Value *PromotedOperand) const;
316991bc56edSDimitry Andric };
317091bc56edSDimitry Andric 
31717d523365SDimitry Andric /// Try adding ScaleReg*Scale to the current addressing mode.
317291bc56edSDimitry Andric /// Return true and update AddrMode if this addr mode is legal for the target,
317391bc56edSDimitry Andric /// false if not.
31747d523365SDimitry Andric bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
317591bc56edSDimitry Andric                                              unsigned Depth) {
317691bc56edSDimitry Andric   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
317791bc56edSDimitry Andric   // mode.  Just process that directly.
317891bc56edSDimitry Andric   if (Scale == 1)
31797d523365SDimitry Andric     return matchAddr(ScaleReg, Depth);
318091bc56edSDimitry Andric 
318191bc56edSDimitry Andric   // If the scale is 0, it takes nothing to add this.
318291bc56edSDimitry Andric   if (Scale == 0)
318391bc56edSDimitry Andric     return true;
318491bc56edSDimitry Andric 
318591bc56edSDimitry Andric   // If we already have a scale of this value, we can add to it, otherwise, we
318691bc56edSDimitry Andric   // need an available scale field.
318791bc56edSDimitry Andric   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
318891bc56edSDimitry Andric     return false;
318991bc56edSDimitry Andric 
319091bc56edSDimitry Andric   ExtAddrMode TestAddrMode = AddrMode;
319191bc56edSDimitry Andric 
319291bc56edSDimitry Andric   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
319391bc56edSDimitry Andric   // [A+B + A*7] -> [B+A*8].
319491bc56edSDimitry Andric   TestAddrMode.Scale += Scale;
319591bc56edSDimitry Andric   TestAddrMode.ScaledReg = ScaleReg;
319691bc56edSDimitry Andric 
319791bc56edSDimitry Andric   // If the new address isn't legal, bail out.
3198875ed548SDimitry Andric   if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
319991bc56edSDimitry Andric     return false;
320091bc56edSDimitry Andric 
320191bc56edSDimitry Andric   // It was legal, so commit it.
320291bc56edSDimitry Andric   AddrMode = TestAddrMode;
320391bc56edSDimitry Andric 
320491bc56edSDimitry Andric   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
320591bc56edSDimitry Andric   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
320691bc56edSDimitry Andric   // X*Scale + C*Scale to addr mode.
320791bc56edSDimitry Andric   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
320891bc56edSDimitry Andric   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
320991bc56edSDimitry Andric       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
321091bc56edSDimitry Andric     TestAddrMode.ScaledReg = AddLHS;
321191bc56edSDimitry Andric     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
321291bc56edSDimitry Andric 
321391bc56edSDimitry Andric     // If this addressing mode is legal, commit it and remember that we folded
321491bc56edSDimitry Andric     // this instruction.
3215875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
321691bc56edSDimitry Andric       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
321791bc56edSDimitry Andric       AddrMode = TestAddrMode;
321891bc56edSDimitry Andric       return true;
321991bc56edSDimitry Andric     }
322091bc56edSDimitry Andric   }
322191bc56edSDimitry Andric 
322291bc56edSDimitry Andric   // Otherwise, not (x+c)*scale, just return what we have.
322391bc56edSDimitry Andric   return true;
322491bc56edSDimitry Andric }
322591bc56edSDimitry Andric 
32267d523365SDimitry Andric /// This is a little filter, which returns true if an addressing computation
32277d523365SDimitry Andric /// involving I might be folded into a load/store accessing it.
32287d523365SDimitry Andric /// This doesn't need to be perfect, but needs to accept at least
322991bc56edSDimitry Andric /// the set of instructions that MatchOperationAddr can.
323091bc56edSDimitry Andric static bool MightBeFoldableInst(Instruction *I) {
323191bc56edSDimitry Andric   switch (I->getOpcode()) {
323291bc56edSDimitry Andric   case Instruction::BitCast:
323391bc56edSDimitry Andric   case Instruction::AddrSpaceCast:
323491bc56edSDimitry Andric     // Don't touch identity bitcasts.
323591bc56edSDimitry Andric     if (I->getType() == I->getOperand(0)->getType())
323691bc56edSDimitry Andric       return false;
323791bc56edSDimitry Andric     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
323891bc56edSDimitry Andric   case Instruction::PtrToInt:
323991bc56edSDimitry Andric     // PtrToInt is always a noop, as we know that the int type is pointer sized.
324091bc56edSDimitry Andric     return true;
324191bc56edSDimitry Andric   case Instruction::IntToPtr:
324291bc56edSDimitry Andric     // We know the input is intptr_t, so this is foldable.
324391bc56edSDimitry Andric     return true;
324491bc56edSDimitry Andric   case Instruction::Add:
324591bc56edSDimitry Andric     return true;
324691bc56edSDimitry Andric   case Instruction::Mul:
324791bc56edSDimitry Andric   case Instruction::Shl:
324891bc56edSDimitry Andric     // Can only handle X*C and X << C.
324991bc56edSDimitry Andric     return isa<ConstantInt>(I->getOperand(1));
325091bc56edSDimitry Andric   case Instruction::GetElementPtr:
325191bc56edSDimitry Andric     return true;
325291bc56edSDimitry Andric   default:
325391bc56edSDimitry Andric     return false;
325491bc56edSDimitry Andric   }
325591bc56edSDimitry Andric }
325691bc56edSDimitry Andric 
325739d628a0SDimitry Andric /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
325839d628a0SDimitry Andric /// \note \p Val is assumed to be the product of some type promotion.
325939d628a0SDimitry Andric /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
326039d628a0SDimitry Andric /// to be legal, as the non-promoted value would have had the same state.
3261875ed548SDimitry Andric static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3262875ed548SDimitry Andric                                        const DataLayout &DL, Value *Val) {
326339d628a0SDimitry Andric   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
326439d628a0SDimitry Andric   if (!PromotedInst)
326539d628a0SDimitry Andric     return false;
326639d628a0SDimitry Andric   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
326739d628a0SDimitry Andric   // If the ISDOpcode is undefined, it was undefined before the promotion.
326839d628a0SDimitry Andric   if (!ISDOpcode)
326939d628a0SDimitry Andric     return true;
327039d628a0SDimitry Andric   // Otherwise, check if the promoted instruction is legal or not.
327139d628a0SDimitry Andric   return TLI.isOperationLegalOrCustom(
3272875ed548SDimitry Andric       ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
327339d628a0SDimitry Andric }
327439d628a0SDimitry Andric 
327591bc56edSDimitry Andric /// \brief Hepler class to perform type promotion.
327691bc56edSDimitry Andric class TypePromotionHelper {
327739d628a0SDimitry Andric   /// \brief Utility function to check whether or not a sign or zero extension
327839d628a0SDimitry Andric   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
327939d628a0SDimitry Andric   /// either using the operands of \p Inst or promoting \p Inst.
328039d628a0SDimitry Andric   /// The type of the extension is defined by \p IsSExt.
328191bc56edSDimitry Andric   /// In other words, check if:
328239d628a0SDimitry Andric   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
328391bc56edSDimitry Andric   /// #1 Promotion applies:
328439d628a0SDimitry Andric   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
328591bc56edSDimitry Andric   /// #2 Operand reuses:
328639d628a0SDimitry Andric   /// ext opnd1 to ConsideredExtType.
328791bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
328839d628a0SDimitry Andric   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
328939d628a0SDimitry Andric                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
329091bc56edSDimitry Andric 
329191bc56edSDimitry Andric   /// \brief Utility function to determine if \p OpIdx should be promoted when
329291bc56edSDimitry Andric   /// promoting \p Inst.
329339d628a0SDimitry Andric   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
32947d523365SDimitry Andric     return !(isa<SelectInst>(Inst) && OpIdx == 0);
329591bc56edSDimitry Andric   }
329691bc56edSDimitry Andric 
329739d628a0SDimitry Andric   /// \brief Utility function to promote the operand of \p Ext when this
329839d628a0SDimitry Andric   /// operand is a promotable trunc or sext or zext.
329991bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
3300ff0cc061SDimitry Andric   /// \p CreatedInstsCost[out] contains the cost of all instructions
330139d628a0SDimitry Andric   /// created to promote the operand of Ext.
330239d628a0SDimitry Andric   /// Newly added extensions are inserted in \p Exts.
330339d628a0SDimitry Andric   /// Newly added truncates are inserted in \p Truncs.
330491bc56edSDimitry Andric   /// Should never be called directly.
330539d628a0SDimitry Andric   /// \return The promoted value which is used instead of Ext.
330639d628a0SDimitry Andric   static Value *promoteOperandForTruncAndAnyExt(
330739d628a0SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
3308ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
330939d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
3310ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
331191bc56edSDimitry Andric 
331239d628a0SDimitry Andric   /// \brief Utility function to promote the operand of \p Ext when this
331391bc56edSDimitry Andric   /// operand is promotable and is not a supported trunc or sext.
331491bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
3315ff0cc061SDimitry Andric   /// \p CreatedInstsCost[out] contains the cost of all the instructions
331639d628a0SDimitry Andric   /// created to promote the operand of Ext.
331739d628a0SDimitry Andric   /// Newly added extensions are inserted in \p Exts.
331839d628a0SDimitry Andric   /// Newly added truncates are inserted in \p Truncs.
331991bc56edSDimitry Andric   /// Should never be called directly.
332039d628a0SDimitry Andric   /// \return The promoted value which is used instead of Ext.
3321ff0cc061SDimitry Andric   static Value *promoteOperandForOther(Instruction *Ext,
3322ff0cc061SDimitry Andric                                        TypePromotionTransaction &TPT,
3323ff0cc061SDimitry Andric                                        InstrToOrigTy &PromotedInsts,
3324ff0cc061SDimitry Andric                                        unsigned &CreatedInstsCost,
332539d628a0SDimitry Andric                                        SmallVectorImpl<Instruction *> *Exts,
3326ff0cc061SDimitry Andric                                        SmallVectorImpl<Instruction *> *Truncs,
3327ff0cc061SDimitry Andric                                        const TargetLowering &TLI, bool IsSExt);
332839d628a0SDimitry Andric 
332939d628a0SDimitry Andric   /// \see promoteOperandForOther.
3330ff0cc061SDimitry Andric   static Value *signExtendOperandForOther(
3331ff0cc061SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
3332ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
333339d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
3334ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3335ff0cc061SDimitry Andric     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3336ff0cc061SDimitry Andric                                   Exts, Truncs, TLI, true);
333739d628a0SDimitry Andric   }
333839d628a0SDimitry Andric 
333939d628a0SDimitry Andric   /// \see promoteOperandForOther.
3340ff0cc061SDimitry Andric   static Value *zeroExtendOperandForOther(
3341ff0cc061SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
3342ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
334339d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
3344ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3345ff0cc061SDimitry Andric     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3346ff0cc061SDimitry Andric                                   Exts, Truncs, TLI, false);
334739d628a0SDimitry Andric   }
334891bc56edSDimitry Andric 
334991bc56edSDimitry Andric public:
335039d628a0SDimitry Andric   /// Type for the utility function that promotes the operand of Ext.
335139d628a0SDimitry Andric   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
3352ff0cc061SDimitry Andric                            InstrToOrigTy &PromotedInsts,
3353ff0cc061SDimitry Andric                            unsigned &CreatedInstsCost,
335439d628a0SDimitry Andric                            SmallVectorImpl<Instruction *> *Exts,
3355ff0cc061SDimitry Andric                            SmallVectorImpl<Instruction *> *Truncs,
3356ff0cc061SDimitry Andric                            const TargetLowering &TLI);
335739d628a0SDimitry Andric   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
335839d628a0SDimitry Andric   /// action to promote the operand of \p Ext instead of using Ext.
335991bc56edSDimitry Andric   /// \return NULL if no promotable action is possible with the current
336091bc56edSDimitry Andric   /// sign extension.
33618f0fd8f6SDimitry Andric   /// \p InsertedInsts keeps track of all the instructions inserted by the
33628f0fd8f6SDimitry Andric   /// other CodeGenPrepare optimizations. This information is important
336391bc56edSDimitry Andric   /// because we do not want to promote these instructions as CodeGenPrepare
336491bc56edSDimitry Andric   /// will reinsert them later. Thus creating an infinite loop: create/remove.
336591bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
33668f0fd8f6SDimitry Andric   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
336791bc56edSDimitry Andric                           const TargetLowering &TLI,
336891bc56edSDimitry Andric                           const InstrToOrigTy &PromotedInsts);
336991bc56edSDimitry Andric };
337091bc56edSDimitry Andric 
337191bc56edSDimitry Andric bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
337239d628a0SDimitry Andric                                         Type *ConsideredExtType,
337339d628a0SDimitry Andric                                         const InstrToOrigTy &PromotedInsts,
337439d628a0SDimitry Andric                                         bool IsSExt) {
337539d628a0SDimitry Andric   // The promotion helper does not know how to deal with vector types yet.
337639d628a0SDimitry Andric   // To be able to fix that, we would need to fix the places where we
337739d628a0SDimitry Andric   // statically extend, e.g., constants and such.
337839d628a0SDimitry Andric   if (Inst->getType()->isVectorTy())
337939d628a0SDimitry Andric     return false;
338039d628a0SDimitry Andric 
338139d628a0SDimitry Andric   // We can always get through zext.
338239d628a0SDimitry Andric   if (isa<ZExtInst>(Inst))
338339d628a0SDimitry Andric     return true;
338439d628a0SDimitry Andric 
338539d628a0SDimitry Andric   // sext(sext) is ok too.
338639d628a0SDimitry Andric   if (IsSExt && isa<SExtInst>(Inst))
338791bc56edSDimitry Andric     return true;
338891bc56edSDimitry Andric 
338991bc56edSDimitry Andric   // We can get through binary operator, if it is legal. In other words, the
339091bc56edSDimitry Andric   // binary operator must have a nuw or nsw flag.
339191bc56edSDimitry Andric   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
339291bc56edSDimitry Andric   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
339339d628a0SDimitry Andric       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
339439d628a0SDimitry Andric        (IsSExt && BinOp->hasNoSignedWrap())))
339591bc56edSDimitry Andric     return true;
339691bc56edSDimitry Andric 
339791bc56edSDimitry Andric   // Check if we can do the following simplification.
339839d628a0SDimitry Andric   // ext(trunc(opnd)) --> ext(opnd)
339991bc56edSDimitry Andric   if (!isa<TruncInst>(Inst))
340091bc56edSDimitry Andric     return false;
340191bc56edSDimitry Andric 
340291bc56edSDimitry Andric   Value *OpndVal = Inst->getOperand(0);
340339d628a0SDimitry Andric   // Check if we can use this operand in the extension.
34047d523365SDimitry Andric   // If the type is larger than the result type of the extension, we cannot.
340539d628a0SDimitry Andric   if (!OpndVal->getType()->isIntegerTy() ||
340639d628a0SDimitry Andric       OpndVal->getType()->getIntegerBitWidth() >
340739d628a0SDimitry Andric           ConsideredExtType->getIntegerBitWidth())
340891bc56edSDimitry Andric     return false;
340991bc56edSDimitry Andric 
341091bc56edSDimitry Andric   // If the operand of the truncate is not an instruction, we will not have
341191bc56edSDimitry Andric   // any information on the dropped bits.
341291bc56edSDimitry Andric   // (Actually we could for constant but it is not worth the extra logic).
341391bc56edSDimitry Andric   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
341491bc56edSDimitry Andric   if (!Opnd)
341591bc56edSDimitry Andric     return false;
341691bc56edSDimitry Andric 
341791bc56edSDimitry Andric   // Check if the source of the type is narrow enough.
341839d628a0SDimitry Andric   // I.e., check that trunc just drops extended bits of the same kind of
341939d628a0SDimitry Andric   // the extension.
342039d628a0SDimitry Andric   // #1 get the type of the operand and check the kind of the extended bits.
342191bc56edSDimitry Andric   const Type *OpndType;
342291bc56edSDimitry Andric   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
34237d523365SDimitry Andric   if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
34247d523365SDimitry Andric     OpndType = It->second.getPointer();
342539d628a0SDimitry Andric   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
342639d628a0SDimitry Andric     OpndType = Opnd->getOperand(0)->getType();
342791bc56edSDimitry Andric   else
342891bc56edSDimitry Andric     return false;
342991bc56edSDimitry Andric 
34307d523365SDimitry Andric   // #2 check that the truncate just drops extended bits.
34317d523365SDimitry Andric   return Inst->getType()->getIntegerBitWidth() >=
34327d523365SDimitry Andric          OpndType->getIntegerBitWidth();
343391bc56edSDimitry Andric }
343491bc56edSDimitry Andric 
343591bc56edSDimitry Andric TypePromotionHelper::Action TypePromotionHelper::getAction(
34368f0fd8f6SDimitry Andric     Instruction *Ext, const SetOfInstrs &InsertedInsts,
343791bc56edSDimitry Andric     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
343839d628a0SDimitry Andric   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
343939d628a0SDimitry Andric          "Unexpected instruction type");
344039d628a0SDimitry Andric   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
344139d628a0SDimitry Andric   Type *ExtTy = Ext->getType();
344239d628a0SDimitry Andric   bool IsSExt = isa<SExtInst>(Ext);
344339d628a0SDimitry Andric   // If the operand of the extension is not an instruction, we cannot
344491bc56edSDimitry Andric   // get through.
344591bc56edSDimitry Andric   // If it, check we can get through.
344639d628a0SDimitry Andric   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
344791bc56edSDimitry Andric     return nullptr;
344891bc56edSDimitry Andric 
344991bc56edSDimitry Andric   // Do not promote if the operand has been added by codegenprepare.
345091bc56edSDimitry Andric   // Otherwise, it means we are undoing an optimization that is likely to be
345191bc56edSDimitry Andric   // redone, thus causing potential infinite loop.
34528f0fd8f6SDimitry Andric   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
345391bc56edSDimitry Andric     return nullptr;
345491bc56edSDimitry Andric 
345591bc56edSDimitry Andric   // SExt or Trunc instructions.
345691bc56edSDimitry Andric   // Return the related handler.
345739d628a0SDimitry Andric   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
345839d628a0SDimitry Andric       isa<ZExtInst>(ExtOpnd))
345939d628a0SDimitry Andric     return promoteOperandForTruncAndAnyExt;
346091bc56edSDimitry Andric 
346191bc56edSDimitry Andric   // Regular instruction.
346291bc56edSDimitry Andric   // Abort early if we will have to insert non-free instructions.
346339d628a0SDimitry Andric   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
346491bc56edSDimitry Andric     return nullptr;
346539d628a0SDimitry Andric   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
346691bc56edSDimitry Andric }
346791bc56edSDimitry Andric 
346839d628a0SDimitry Andric Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
346991bc56edSDimitry Andric     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
3470ff0cc061SDimitry Andric     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
347139d628a0SDimitry Andric     SmallVectorImpl<Instruction *> *Exts,
3472ff0cc061SDimitry Andric     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
347391bc56edSDimitry Andric   // By construction, the operand of SExt is an instruction. Otherwise we cannot
347491bc56edSDimitry Andric   // get through it and this method should not be called.
347591bc56edSDimitry Andric   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
347639d628a0SDimitry Andric   Value *ExtVal = SExt;
3477ff0cc061SDimitry Andric   bool HasMergedNonFreeExt = false;
347839d628a0SDimitry Andric   if (isa<ZExtInst>(SExtOpnd)) {
347939d628a0SDimitry Andric     // Replace s|zext(zext(opnd))
348039d628a0SDimitry Andric     // => zext(opnd).
3481ff0cc061SDimitry Andric     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
348239d628a0SDimitry Andric     Value *ZExt =
348339d628a0SDimitry Andric         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
348439d628a0SDimitry Andric     TPT.replaceAllUsesWith(SExt, ZExt);
348539d628a0SDimitry Andric     TPT.eraseInstruction(SExt);
348639d628a0SDimitry Andric     ExtVal = ZExt;
348739d628a0SDimitry Andric   } else {
348839d628a0SDimitry Andric     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
348939d628a0SDimitry Andric     // => z|sext(opnd).
349091bc56edSDimitry Andric     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
349139d628a0SDimitry Andric   }
3492ff0cc061SDimitry Andric   CreatedInstsCost = 0;
349391bc56edSDimitry Andric 
349491bc56edSDimitry Andric   // Remove dead code.
349591bc56edSDimitry Andric   if (SExtOpnd->use_empty())
349691bc56edSDimitry Andric     TPT.eraseInstruction(SExtOpnd);
349791bc56edSDimitry Andric 
349839d628a0SDimitry Andric   // Check if the extension is still needed.
349939d628a0SDimitry Andric   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
350039d628a0SDimitry Andric   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
3501ff0cc061SDimitry Andric     if (ExtInst) {
3502ff0cc061SDimitry Andric       if (Exts)
350339d628a0SDimitry Andric         Exts->push_back(ExtInst);
3504ff0cc061SDimitry Andric       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3505ff0cc061SDimitry Andric     }
350639d628a0SDimitry Andric     return ExtVal;
350739d628a0SDimitry Andric   }
350891bc56edSDimitry Andric 
350939d628a0SDimitry Andric   // At this point we have: ext ty opnd to ty.
351039d628a0SDimitry Andric   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
351139d628a0SDimitry Andric   Value *NextVal = ExtInst->getOperand(0);
351239d628a0SDimitry Andric   TPT.eraseInstruction(ExtInst, NextVal);
351391bc56edSDimitry Andric   return NextVal;
351491bc56edSDimitry Andric }
351591bc56edSDimitry Andric 
351639d628a0SDimitry Andric Value *TypePromotionHelper::promoteOperandForOther(
351739d628a0SDimitry Andric     Instruction *Ext, TypePromotionTransaction &TPT,
3518ff0cc061SDimitry Andric     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
351939d628a0SDimitry Andric     SmallVectorImpl<Instruction *> *Exts,
3520ff0cc061SDimitry Andric     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3521ff0cc061SDimitry Andric     bool IsSExt) {
352239d628a0SDimitry Andric   // By construction, the operand of Ext is an instruction. Otherwise we cannot
352391bc56edSDimitry Andric   // get through it and this method should not be called.
352439d628a0SDimitry Andric   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
3525ff0cc061SDimitry Andric   CreatedInstsCost = 0;
352639d628a0SDimitry Andric   if (!ExtOpnd->hasOneUse()) {
352739d628a0SDimitry Andric     // ExtOpnd will be promoted.
352839d628a0SDimitry Andric     // All its uses, but Ext, will need to use a truncated value of the
352991bc56edSDimitry Andric     // promoted version.
353091bc56edSDimitry Andric     // Create the truncate now.
353139d628a0SDimitry Andric     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
353239d628a0SDimitry Andric     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
353339d628a0SDimitry Andric       ITrunc->removeFromParent();
353491bc56edSDimitry Andric       // Insert it just after the definition.
353539d628a0SDimitry Andric       ITrunc->insertAfter(ExtOpnd);
353639d628a0SDimitry Andric       if (Truncs)
353739d628a0SDimitry Andric         Truncs->push_back(ITrunc);
353839d628a0SDimitry Andric     }
353991bc56edSDimitry Andric 
354039d628a0SDimitry Andric     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
35417d523365SDimitry Andric     // Restore the operand of Ext (which has been replaced by the previous call
354291bc56edSDimitry Andric     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
354339d628a0SDimitry Andric     TPT.setOperand(Ext, 0, ExtOpnd);
354491bc56edSDimitry Andric   }
354591bc56edSDimitry Andric 
354691bc56edSDimitry Andric   // Get through the Instruction:
354791bc56edSDimitry Andric   // 1. Update its type.
354839d628a0SDimitry Andric   // 2. Replace the uses of Ext by Inst.
354939d628a0SDimitry Andric   // 3. Extend each operand that needs to be extended.
355091bc56edSDimitry Andric 
355191bc56edSDimitry Andric   // Remember the original type of the instruction before promotion.
355291bc56edSDimitry Andric   // This is useful to know that the high bits are sign extended bits.
355339d628a0SDimitry Andric   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
355439d628a0SDimitry Andric       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
355591bc56edSDimitry Andric   // Step #1.
355639d628a0SDimitry Andric   TPT.mutateType(ExtOpnd, Ext->getType());
355791bc56edSDimitry Andric   // Step #2.
355839d628a0SDimitry Andric   TPT.replaceAllUsesWith(Ext, ExtOpnd);
355991bc56edSDimitry Andric   // Step #3.
356039d628a0SDimitry Andric   Instruction *ExtForOpnd = Ext;
356191bc56edSDimitry Andric 
356239d628a0SDimitry Andric   DEBUG(dbgs() << "Propagate Ext to operands\n");
356339d628a0SDimitry Andric   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
356491bc56edSDimitry Andric        ++OpIdx) {
356539d628a0SDimitry Andric     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
356639d628a0SDimitry Andric     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
356739d628a0SDimitry Andric         !shouldExtOperand(ExtOpnd, OpIdx)) {
356891bc56edSDimitry Andric       DEBUG(dbgs() << "No need to propagate\n");
356991bc56edSDimitry Andric       continue;
357091bc56edSDimitry Andric     }
357139d628a0SDimitry Andric     // Check if we can statically extend the operand.
357239d628a0SDimitry Andric     Value *Opnd = ExtOpnd->getOperand(OpIdx);
357391bc56edSDimitry Andric     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
357439d628a0SDimitry Andric       DEBUG(dbgs() << "Statically extend\n");
357539d628a0SDimitry Andric       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
357639d628a0SDimitry Andric       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
357739d628a0SDimitry Andric                             : Cst->getValue().zext(BitWidth);
357839d628a0SDimitry Andric       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
357991bc56edSDimitry Andric       continue;
358091bc56edSDimitry Andric     }
358191bc56edSDimitry Andric     // UndefValue are typed, so we have to statically sign extend them.
358291bc56edSDimitry Andric     if (isa<UndefValue>(Opnd)) {
358339d628a0SDimitry Andric       DEBUG(dbgs() << "Statically extend\n");
358439d628a0SDimitry Andric       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
358591bc56edSDimitry Andric       continue;
358691bc56edSDimitry Andric     }
358791bc56edSDimitry Andric 
358891bc56edSDimitry Andric     // Otherwise we have to explicity sign extend the operand.
358939d628a0SDimitry Andric     // Check if Ext was reused to extend an operand.
359039d628a0SDimitry Andric     if (!ExtForOpnd) {
359191bc56edSDimitry Andric       // If yes, create a new one.
359239d628a0SDimitry Andric       DEBUG(dbgs() << "More operands to ext\n");
359339d628a0SDimitry Andric       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
359439d628a0SDimitry Andric         : TPT.createZExt(Ext, Opnd, Ext->getType());
359539d628a0SDimitry Andric       if (!isa<Instruction>(ValForExtOpnd)) {
359639d628a0SDimitry Andric         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
359739d628a0SDimitry Andric         continue;
359839d628a0SDimitry Andric       }
359939d628a0SDimitry Andric       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
360091bc56edSDimitry Andric     }
360139d628a0SDimitry Andric     if (Exts)
360239d628a0SDimitry Andric       Exts->push_back(ExtForOpnd);
360339d628a0SDimitry Andric     TPT.setOperand(ExtForOpnd, 0, Opnd);
360491bc56edSDimitry Andric 
360591bc56edSDimitry Andric     // Move the sign extension before the insertion point.
360639d628a0SDimitry Andric     TPT.moveBefore(ExtForOpnd, ExtOpnd);
360739d628a0SDimitry Andric     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3608ff0cc061SDimitry Andric     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
360991bc56edSDimitry Andric     // If more sext are required, new instructions will have to be created.
361039d628a0SDimitry Andric     ExtForOpnd = nullptr;
361191bc56edSDimitry Andric   }
361239d628a0SDimitry Andric   if (ExtForOpnd == Ext) {
361339d628a0SDimitry Andric     DEBUG(dbgs() << "Extension is useless now\n");
361439d628a0SDimitry Andric     TPT.eraseInstruction(Ext);
361591bc56edSDimitry Andric   }
361639d628a0SDimitry Andric   return ExtOpnd;
361791bc56edSDimitry Andric }
361891bc56edSDimitry Andric 
36197d523365SDimitry Andric /// Check whether or not promoting an instruction to a wider type is profitable.
3620ff0cc061SDimitry Andric /// \p NewCost gives the cost of extension instructions created by the
3621ff0cc061SDimitry Andric /// promotion.
3622ff0cc061SDimitry Andric /// \p OldCost gives the cost of extension instructions before the promotion
3623ff0cc061SDimitry Andric /// plus the number of instructions that have been
3624ff0cc061SDimitry Andric /// matched in the addressing mode the promotion.
362591bc56edSDimitry Andric /// \p PromotedOperand is the value that has been promoted.
362691bc56edSDimitry Andric /// \return True if the promotion is profitable, false otherwise.
36277d523365SDimitry Andric bool AddressingModeMatcher::isPromotionProfitable(
3628ff0cc061SDimitry Andric     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3629ff0cc061SDimitry Andric   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3630ff0cc061SDimitry Andric   // The cost of the new extensions is greater than the cost of the
3631ff0cc061SDimitry Andric   // old extension plus what we folded.
363291bc56edSDimitry Andric   // This is not profitable.
3633ff0cc061SDimitry Andric   if (NewCost > OldCost)
363491bc56edSDimitry Andric     return false;
3635ff0cc061SDimitry Andric   if (NewCost < OldCost)
363691bc56edSDimitry Andric     return true;
363791bc56edSDimitry Andric   // The promotion is neutral but it may help folding the sign extension in
363891bc56edSDimitry Andric   // loads for instance.
363991bc56edSDimitry Andric   // Check that we did not create an illegal instruction.
3640875ed548SDimitry Andric   return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
364191bc56edSDimitry Andric }
364291bc56edSDimitry Andric 
36437d523365SDimitry Andric /// Given an instruction or constant expr, see if we can fold the operation
36447d523365SDimitry Andric /// into the addressing mode. If so, update the addressing mode and return
36457d523365SDimitry Andric /// true, otherwise return false without modifying AddrMode.
364691bc56edSDimitry Andric /// If \p MovedAway is not NULL, it contains the information of whether or
364791bc56edSDimitry Andric /// not AddrInst has to be folded into the addressing mode on success.
364891bc56edSDimitry Andric /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
364991bc56edSDimitry Andric /// because it has been moved away.
365091bc56edSDimitry Andric /// Thus AddrInst must not be added in the matched instructions.
365191bc56edSDimitry Andric /// This state can happen when AddrInst is a sext, since it may be moved away.
365291bc56edSDimitry Andric /// Therefore, AddrInst may not be valid when MovedAway is true and it must
365391bc56edSDimitry Andric /// not be referenced anymore.
36547d523365SDimitry Andric bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
365591bc56edSDimitry Andric                                                unsigned Depth,
365691bc56edSDimitry Andric                                                bool *MovedAway) {
365791bc56edSDimitry Andric   // Avoid exponential behavior on extremely deep expression trees.
365891bc56edSDimitry Andric   if (Depth >= 5) return false;
365991bc56edSDimitry Andric 
366091bc56edSDimitry Andric   // By default, all matched instructions stay in place.
366191bc56edSDimitry Andric   if (MovedAway)
366291bc56edSDimitry Andric     *MovedAway = false;
366391bc56edSDimitry Andric 
366491bc56edSDimitry Andric   switch (Opcode) {
366591bc56edSDimitry Andric   case Instruction::PtrToInt:
366691bc56edSDimitry Andric     // PtrToInt is always a noop, as we know that the int type is pointer sized.
36677d523365SDimitry Andric     return matchAddr(AddrInst->getOperand(0), Depth);
3668875ed548SDimitry Andric   case Instruction::IntToPtr: {
3669875ed548SDimitry Andric     auto AS = AddrInst->getType()->getPointerAddressSpace();
3670875ed548SDimitry Andric     auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
367191bc56edSDimitry Andric     // This inttoptr is a no-op if the integer type is pointer sized.
3672875ed548SDimitry Andric     if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
36737d523365SDimitry Andric       return matchAddr(AddrInst->getOperand(0), Depth);
367491bc56edSDimitry Andric     return false;
3675875ed548SDimitry Andric   }
367691bc56edSDimitry Andric   case Instruction::BitCast:
367791bc56edSDimitry Andric     // BitCast is always a noop, and we can handle it as long as it is
367891bc56edSDimitry Andric     // int->int or pointer->pointer (we don't want int<->fp or something).
367991bc56edSDimitry Andric     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
368091bc56edSDimitry Andric          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
368191bc56edSDimitry Andric         // Don't touch identity bitcasts.  These were probably put here by LSR,
368291bc56edSDimitry Andric         // and we don't want to mess around with them.  Assume it knows what it
368391bc56edSDimitry Andric         // is doing.
368491bc56edSDimitry Andric         AddrInst->getOperand(0)->getType() != AddrInst->getType())
36857d523365SDimitry Andric       return matchAddr(AddrInst->getOperand(0), Depth);
368691bc56edSDimitry Andric     return false;
3687ff0cc061SDimitry Andric   case Instruction::AddrSpaceCast: {
3688ff0cc061SDimitry Andric     unsigned SrcAS
3689ff0cc061SDimitry Andric       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3690ff0cc061SDimitry Andric     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3691ff0cc061SDimitry Andric     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
36927d523365SDimitry Andric       return matchAddr(AddrInst->getOperand(0), Depth);
3693ff0cc061SDimitry Andric     return false;
3694ff0cc061SDimitry Andric   }
369591bc56edSDimitry Andric   case Instruction::Add: {
369691bc56edSDimitry Andric     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
369791bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
369891bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
369991bc56edSDimitry Andric     // Start a transaction at this point.
370091bc56edSDimitry Andric     // The LHS may match but not the RHS.
370191bc56edSDimitry Andric     // Therefore, we need a higher level restoration point to undo partially
370291bc56edSDimitry Andric     // matched operation.
370391bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
370491bc56edSDimitry Andric         TPT.getRestorationPoint();
370591bc56edSDimitry Andric 
37067d523365SDimitry Andric     if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
37077d523365SDimitry Andric         matchAddr(AddrInst->getOperand(0), Depth+1))
370891bc56edSDimitry Andric       return true;
370991bc56edSDimitry Andric 
371091bc56edSDimitry Andric     // Restore the old addr mode info.
371191bc56edSDimitry Andric     AddrMode = BackupAddrMode;
371291bc56edSDimitry Andric     AddrModeInsts.resize(OldSize);
371391bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
371491bc56edSDimitry Andric 
371591bc56edSDimitry Andric     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
37167d523365SDimitry Andric     if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
37177d523365SDimitry Andric         matchAddr(AddrInst->getOperand(1), Depth+1))
371891bc56edSDimitry Andric       return true;
371991bc56edSDimitry Andric 
372091bc56edSDimitry Andric     // Otherwise we definitely can't merge the ADD in.
372191bc56edSDimitry Andric     AddrMode = BackupAddrMode;
372291bc56edSDimitry Andric     AddrModeInsts.resize(OldSize);
372391bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
372491bc56edSDimitry Andric     break;
372591bc56edSDimitry Andric   }
372691bc56edSDimitry Andric   //case Instruction::Or:
372791bc56edSDimitry Andric   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
372891bc56edSDimitry Andric   //break;
372991bc56edSDimitry Andric   case Instruction::Mul:
373091bc56edSDimitry Andric   case Instruction::Shl: {
373191bc56edSDimitry Andric     // Can only handle X*C and X << C.
373291bc56edSDimitry Andric     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
373391bc56edSDimitry Andric     if (!RHS)
373491bc56edSDimitry Andric       return false;
373591bc56edSDimitry Andric     int64_t Scale = RHS->getSExtValue();
373691bc56edSDimitry Andric     if (Opcode == Instruction::Shl)
373791bc56edSDimitry Andric       Scale = 1LL << Scale;
373891bc56edSDimitry Andric 
37397d523365SDimitry Andric     return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
374091bc56edSDimitry Andric   }
374191bc56edSDimitry Andric   case Instruction::GetElementPtr: {
374291bc56edSDimitry Andric     // Scan the GEP.  We check it if it contains constant offsets and at most
374391bc56edSDimitry Andric     // one variable offset.
374491bc56edSDimitry Andric     int VariableOperand = -1;
374591bc56edSDimitry Andric     unsigned VariableScale = 0;
374691bc56edSDimitry Andric 
374791bc56edSDimitry Andric     int64_t ConstantOffset = 0;
374891bc56edSDimitry Andric     gep_type_iterator GTI = gep_type_begin(AddrInst);
374991bc56edSDimitry Andric     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3750d88c1a5aSDimitry Andric       if (StructType *STy = GTI.getStructTypeOrNull()) {
3751875ed548SDimitry Andric         const StructLayout *SL = DL.getStructLayout(STy);
375291bc56edSDimitry Andric         unsigned Idx =
375391bc56edSDimitry Andric           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
375491bc56edSDimitry Andric         ConstantOffset += SL->getElementOffset(Idx);
375591bc56edSDimitry Andric       } else {
3756875ed548SDimitry Andric         uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
375791bc56edSDimitry Andric         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
375891bc56edSDimitry Andric           ConstantOffset += CI->getSExtValue()*TypeSize;
375991bc56edSDimitry Andric         } else if (TypeSize) {  // Scales of zero don't do anything.
376091bc56edSDimitry Andric           // We only allow one variable index at the moment.
376191bc56edSDimitry Andric           if (VariableOperand != -1)
376291bc56edSDimitry Andric             return false;
376391bc56edSDimitry Andric 
376491bc56edSDimitry Andric           // Remember the variable index.
376591bc56edSDimitry Andric           VariableOperand = i;
376691bc56edSDimitry Andric           VariableScale = TypeSize;
376791bc56edSDimitry Andric         }
376891bc56edSDimitry Andric       }
376991bc56edSDimitry Andric     }
377091bc56edSDimitry Andric 
377191bc56edSDimitry Andric     // A common case is for the GEP to only do a constant offset.  In this case,
377291bc56edSDimitry Andric     // just add it to the disp field and check validity.
377391bc56edSDimitry Andric     if (VariableOperand == -1) {
377491bc56edSDimitry Andric       AddrMode.BaseOffs += ConstantOffset;
377597bc6c73SDimitry Andric       if (ConstantOffset == 0 ||
3776875ed548SDimitry Andric           TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
377791bc56edSDimitry Andric         // Check to see if we can fold the base pointer in too.
37787d523365SDimitry Andric         if (matchAddr(AddrInst->getOperand(0), Depth+1))
377991bc56edSDimitry Andric           return true;
378091bc56edSDimitry Andric       }
378191bc56edSDimitry Andric       AddrMode.BaseOffs -= ConstantOffset;
378291bc56edSDimitry Andric       return false;
378391bc56edSDimitry Andric     }
378491bc56edSDimitry Andric 
378591bc56edSDimitry Andric     // Save the valid addressing mode in case we can't match.
378691bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
378791bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
378891bc56edSDimitry Andric 
378991bc56edSDimitry Andric     // See if the scale and offset amount is valid for this target.
379091bc56edSDimitry Andric     AddrMode.BaseOffs += ConstantOffset;
379191bc56edSDimitry Andric 
379291bc56edSDimitry Andric     // Match the base operand of the GEP.
37937d523365SDimitry Andric     if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
379491bc56edSDimitry Andric       // If it couldn't be matched, just stuff the value in a register.
379591bc56edSDimitry Andric       if (AddrMode.HasBaseReg) {
379691bc56edSDimitry Andric         AddrMode = BackupAddrMode;
379791bc56edSDimitry Andric         AddrModeInsts.resize(OldSize);
379891bc56edSDimitry Andric         return false;
379991bc56edSDimitry Andric       }
380091bc56edSDimitry Andric       AddrMode.HasBaseReg = true;
380191bc56edSDimitry Andric       AddrMode.BaseReg = AddrInst->getOperand(0);
380291bc56edSDimitry Andric     }
380391bc56edSDimitry Andric 
380491bc56edSDimitry Andric     // Match the remaining variable portion of the GEP.
38057d523365SDimitry Andric     if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
380691bc56edSDimitry Andric                           Depth)) {
380791bc56edSDimitry Andric       // If it couldn't be matched, try stuffing the base into a register
380891bc56edSDimitry Andric       // instead of matching it, and retrying the match of the scale.
380991bc56edSDimitry Andric       AddrMode = BackupAddrMode;
381091bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
381191bc56edSDimitry Andric       if (AddrMode.HasBaseReg)
381291bc56edSDimitry Andric         return false;
381391bc56edSDimitry Andric       AddrMode.HasBaseReg = true;
381491bc56edSDimitry Andric       AddrMode.BaseReg = AddrInst->getOperand(0);
381591bc56edSDimitry Andric       AddrMode.BaseOffs += ConstantOffset;
38167d523365SDimitry Andric       if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
381791bc56edSDimitry Andric                             VariableScale, Depth)) {
381891bc56edSDimitry Andric         // If even that didn't work, bail.
381991bc56edSDimitry Andric         AddrMode = BackupAddrMode;
382091bc56edSDimitry Andric         AddrModeInsts.resize(OldSize);
382191bc56edSDimitry Andric         return false;
382291bc56edSDimitry Andric       }
382391bc56edSDimitry Andric     }
382491bc56edSDimitry Andric 
382591bc56edSDimitry Andric     return true;
382691bc56edSDimitry Andric   }
382739d628a0SDimitry Andric   case Instruction::SExt:
382839d628a0SDimitry Andric   case Instruction::ZExt: {
382939d628a0SDimitry Andric     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
383039d628a0SDimitry Andric     if (!Ext)
383191bc56edSDimitry Andric       return false;
383291bc56edSDimitry Andric 
383339d628a0SDimitry Andric     // Try to move this ext out of the way of the addressing mode.
383491bc56edSDimitry Andric     // Ask for a method for doing so.
383539d628a0SDimitry Andric     TypePromotionHelper::Action TPH =
38368f0fd8f6SDimitry Andric         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
383791bc56edSDimitry Andric     if (!TPH)
383891bc56edSDimitry Andric       return false;
383991bc56edSDimitry Andric 
384091bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
384191bc56edSDimitry Andric         TPT.getRestorationPoint();
3842ff0cc061SDimitry Andric     unsigned CreatedInstsCost = 0;
3843ff0cc061SDimitry Andric     unsigned ExtCost = !TLI.isExtFree(Ext);
384439d628a0SDimitry Andric     Value *PromotedOperand =
3845ff0cc061SDimitry Andric         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
384691bc56edSDimitry Andric     // SExt has been moved away.
384791bc56edSDimitry Andric     // Thus either it will be rematched later in the recursive calls or it is
384891bc56edSDimitry Andric     // gone. Anyway, we must not fold it into the addressing mode at this point.
384991bc56edSDimitry Andric     // E.g.,
385091bc56edSDimitry Andric     // op = add opnd, 1
385139d628a0SDimitry Andric     // idx = ext op
385291bc56edSDimitry Andric     // addr = gep base, idx
385391bc56edSDimitry Andric     // is now:
385439d628a0SDimitry Andric     // promotedOpnd = ext opnd            <- no match here
385591bc56edSDimitry Andric     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
385691bc56edSDimitry Andric     // addr = gep base, op                <- match
385791bc56edSDimitry Andric     if (MovedAway)
385891bc56edSDimitry Andric       *MovedAway = true;
385991bc56edSDimitry Andric 
386091bc56edSDimitry Andric     assert(PromotedOperand &&
386191bc56edSDimitry Andric            "TypePromotionHelper should have filtered out those cases");
386291bc56edSDimitry Andric 
386391bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
386491bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
386591bc56edSDimitry Andric 
38667d523365SDimitry Andric     if (!matchAddr(PromotedOperand, Depth) ||
38677d523365SDimitry Andric         // The total of the new cost is equal to the cost of the created
3868ff0cc061SDimitry Andric         // instructions.
38697d523365SDimitry Andric         // The total of the old cost is equal to the cost of the extension plus
3870ff0cc061SDimitry Andric         // what we have saved in the addressing mode.
38717d523365SDimitry Andric         !isPromotionProfitable(CreatedInstsCost,
3872ff0cc061SDimitry Andric                                ExtCost + (AddrModeInsts.size() - OldSize),
387391bc56edSDimitry Andric                                PromotedOperand)) {
387491bc56edSDimitry Andric       AddrMode = BackupAddrMode;
387591bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
387691bc56edSDimitry Andric       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
387791bc56edSDimitry Andric       TPT.rollback(LastKnownGood);
387891bc56edSDimitry Andric       return false;
387991bc56edSDimitry Andric     }
388091bc56edSDimitry Andric     return true;
388191bc56edSDimitry Andric   }
388291bc56edSDimitry Andric   }
388391bc56edSDimitry Andric   return false;
388491bc56edSDimitry Andric }
388591bc56edSDimitry Andric 
38867d523365SDimitry Andric /// If we can, try to add the value of 'Addr' into the current addressing mode.
38877d523365SDimitry Andric /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
38887d523365SDimitry Andric /// unmodified. This assumes that Addr is either a pointer type or intptr_t
38897d523365SDimitry Andric /// for the target.
389091bc56edSDimitry Andric ///
38917d523365SDimitry Andric bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
389291bc56edSDimitry Andric   // Start a transaction at this point that we will rollback if the matching
389391bc56edSDimitry Andric   // fails.
389491bc56edSDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
389591bc56edSDimitry Andric       TPT.getRestorationPoint();
389691bc56edSDimitry Andric   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
389791bc56edSDimitry Andric     // Fold in immediates if legal for the target.
389891bc56edSDimitry Andric     AddrMode.BaseOffs += CI->getSExtValue();
3899875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
390091bc56edSDimitry Andric       return true;
390191bc56edSDimitry Andric     AddrMode.BaseOffs -= CI->getSExtValue();
390291bc56edSDimitry Andric   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
390391bc56edSDimitry Andric     // If this is a global variable, try to fold it into the addressing mode.
390491bc56edSDimitry Andric     if (!AddrMode.BaseGV) {
390591bc56edSDimitry Andric       AddrMode.BaseGV = GV;
3906875ed548SDimitry Andric       if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
390791bc56edSDimitry Andric         return true;
390891bc56edSDimitry Andric       AddrMode.BaseGV = nullptr;
390991bc56edSDimitry Andric     }
391091bc56edSDimitry Andric   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
391191bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
391291bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
391391bc56edSDimitry Andric 
391491bc56edSDimitry Andric     // Check to see if it is possible to fold this operation.
391591bc56edSDimitry Andric     bool MovedAway = false;
39167d523365SDimitry Andric     if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
39177d523365SDimitry Andric       // This instruction may have been moved away. If so, there is nothing
391891bc56edSDimitry Andric       // to check here.
391991bc56edSDimitry Andric       if (MovedAway)
392091bc56edSDimitry Andric         return true;
392191bc56edSDimitry Andric       // Okay, it's possible to fold this.  Check to see if it is actually
392291bc56edSDimitry Andric       // *profitable* to do so.  We use a simple cost model to avoid increasing
392391bc56edSDimitry Andric       // register pressure too much.
392491bc56edSDimitry Andric       if (I->hasOneUse() ||
39257d523365SDimitry Andric           isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
392691bc56edSDimitry Andric         AddrModeInsts.push_back(I);
392791bc56edSDimitry Andric         return true;
392891bc56edSDimitry Andric       }
392991bc56edSDimitry Andric 
393091bc56edSDimitry Andric       // It isn't profitable to do this, roll back.
393191bc56edSDimitry Andric       //cerr << "NOT FOLDING: " << *I;
393291bc56edSDimitry Andric       AddrMode = BackupAddrMode;
393391bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
393491bc56edSDimitry Andric       TPT.rollback(LastKnownGood);
393591bc56edSDimitry Andric     }
393691bc56edSDimitry Andric   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
39377d523365SDimitry Andric     if (matchOperationAddr(CE, CE->getOpcode(), Depth))
393891bc56edSDimitry Andric       return true;
393991bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
394091bc56edSDimitry Andric   } else if (isa<ConstantPointerNull>(Addr)) {
394191bc56edSDimitry Andric     // Null pointer gets folded without affecting the addressing mode.
394291bc56edSDimitry Andric     return true;
394391bc56edSDimitry Andric   }
394491bc56edSDimitry Andric 
394591bc56edSDimitry Andric   // Worse case, the target should support [reg] addressing modes. :)
394691bc56edSDimitry Andric   if (!AddrMode.HasBaseReg) {
394791bc56edSDimitry Andric     AddrMode.HasBaseReg = true;
394891bc56edSDimitry Andric     AddrMode.BaseReg = Addr;
394991bc56edSDimitry Andric     // Still check for legality in case the target supports [imm] but not [i+r].
3950875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
395191bc56edSDimitry Andric       return true;
395291bc56edSDimitry Andric     AddrMode.HasBaseReg = false;
395391bc56edSDimitry Andric     AddrMode.BaseReg = nullptr;
395491bc56edSDimitry Andric   }
395591bc56edSDimitry Andric 
395691bc56edSDimitry Andric   // If the base register is already taken, see if we can do [r+r].
395791bc56edSDimitry Andric   if (AddrMode.Scale == 0) {
395891bc56edSDimitry Andric     AddrMode.Scale = 1;
395991bc56edSDimitry Andric     AddrMode.ScaledReg = Addr;
3960875ed548SDimitry Andric     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
396191bc56edSDimitry Andric       return true;
396291bc56edSDimitry Andric     AddrMode.Scale = 0;
396391bc56edSDimitry Andric     AddrMode.ScaledReg = nullptr;
396491bc56edSDimitry Andric   }
396591bc56edSDimitry Andric   // Couldn't match.
396691bc56edSDimitry Andric   TPT.rollback(LastKnownGood);
396791bc56edSDimitry Andric   return false;
396891bc56edSDimitry Andric }
396991bc56edSDimitry Andric 
39707d523365SDimitry Andric /// Check to see if all uses of OpVal by the specified inline asm call are due
39717d523365SDimitry Andric /// to memory operands. If so, return true, otherwise return false.
397291bc56edSDimitry Andric static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
39737a7e6055SDimitry Andric                                     const TargetLowering &TLI,
39747a7e6055SDimitry Andric                                     const TargetRegisterInfo &TRI) {
3975db17bf38SDimitry Andric   const Function *F = CI->getFunction();
3976ff0cc061SDimitry Andric   TargetLowering::AsmOperandInfoVector TargetConstraints =
39777a7e6055SDimitry Andric       TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
3978875ed548SDimitry Andric                             ImmutableCallSite(CI));
39797a7e6055SDimitry Andric 
398091bc56edSDimitry Andric   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
398191bc56edSDimitry Andric     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
398291bc56edSDimitry Andric 
398391bc56edSDimitry Andric     // Compute the constraint code and ConstraintType to use.
39847a7e6055SDimitry Andric     TLI.ComputeConstraintToUse(OpInfo, SDValue());
398591bc56edSDimitry Andric 
398691bc56edSDimitry Andric     // If this asm operand is our Value*, and if it isn't an indirect memory
398791bc56edSDimitry Andric     // operand, we can't fold it!
398891bc56edSDimitry Andric     if (OpInfo.CallOperandVal == OpVal &&
398991bc56edSDimitry Andric         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
399091bc56edSDimitry Andric          !OpInfo.isIndirect))
399191bc56edSDimitry Andric       return false;
399291bc56edSDimitry Andric   }
399391bc56edSDimitry Andric 
399491bc56edSDimitry Andric   return true;
399591bc56edSDimitry Andric }
399691bc56edSDimitry Andric 
39977d523365SDimitry Andric /// Recursively walk all the uses of I until we find a memory use.
39987d523365SDimitry Andric /// If we find an obviously non-foldable instruction, return true.
399991bc56edSDimitry Andric /// Add the ultimately found memory instructions to MemoryUses.
4000ff0cc061SDimitry Andric static bool FindAllMemoryUses(
4001ff0cc061SDimitry Andric     Instruction *I,
400291bc56edSDimitry Andric     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
40037a7e6055SDimitry Andric     SmallPtrSetImpl<Instruction *> &ConsideredInsts,
40047a7e6055SDimitry Andric     const TargetLowering &TLI, const TargetRegisterInfo &TRI) {
400591bc56edSDimitry Andric   // If we already considered this instruction, we're done.
400639d628a0SDimitry Andric   if (!ConsideredInsts.insert(I).second)
400791bc56edSDimitry Andric     return false;
400891bc56edSDimitry Andric 
400991bc56edSDimitry Andric   // If this is an obviously unfoldable instruction, bail out.
401091bc56edSDimitry Andric   if (!MightBeFoldableInst(I))
401191bc56edSDimitry Andric     return true;
401291bc56edSDimitry Andric 
40133ca95b02SDimitry Andric   const bool OptSize = I->getFunction()->optForSize();
40143ca95b02SDimitry Andric 
401591bc56edSDimitry Andric   // Loop over all the uses, recursively processing them.
401691bc56edSDimitry Andric   for (Use &U : I->uses()) {
401791bc56edSDimitry Andric     Instruction *UserI = cast<Instruction>(U.getUser());
401891bc56edSDimitry Andric 
401991bc56edSDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
402091bc56edSDimitry Andric       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
402191bc56edSDimitry Andric       continue;
402291bc56edSDimitry Andric     }
402391bc56edSDimitry Andric 
402491bc56edSDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
402591bc56edSDimitry Andric       unsigned opNo = U.getOperandNo();
40267a7e6055SDimitry Andric       if (opNo != StoreInst::getPointerOperandIndex())
40277a7e6055SDimitry Andric         return true; // Storing addr, not into addr.
402891bc56edSDimitry Andric       MemoryUses.push_back(std::make_pair(SI, opNo));
402991bc56edSDimitry Andric       continue;
403091bc56edSDimitry Andric     }
403191bc56edSDimitry Andric 
40327a7e6055SDimitry Andric     if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
40337a7e6055SDimitry Andric       unsigned opNo = U.getOperandNo();
40347a7e6055SDimitry Andric       if (opNo != AtomicRMWInst::getPointerOperandIndex())
40357a7e6055SDimitry Andric         return true; // Storing addr, not into addr.
40367a7e6055SDimitry Andric       MemoryUses.push_back(std::make_pair(RMW, opNo));
40377a7e6055SDimitry Andric       continue;
40387a7e6055SDimitry Andric     }
40397a7e6055SDimitry Andric 
40407a7e6055SDimitry Andric     if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
40417a7e6055SDimitry Andric       unsigned opNo = U.getOperandNo();
40427a7e6055SDimitry Andric       if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
40437a7e6055SDimitry Andric         return true; // Storing addr, not into addr.
40447a7e6055SDimitry Andric       MemoryUses.push_back(std::make_pair(CmpX, opNo));
40457a7e6055SDimitry Andric       continue;
40467a7e6055SDimitry Andric     }
40477a7e6055SDimitry Andric 
404891bc56edSDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
40493ca95b02SDimitry Andric       // If this is a cold call, we can sink the addressing calculation into
40503ca95b02SDimitry Andric       // the cold path.  See optimizeCallInst
40513ca95b02SDimitry Andric       if (!OptSize && CI->hasFnAttr(Attribute::Cold))
40523ca95b02SDimitry Andric         continue;
40533ca95b02SDimitry Andric 
405491bc56edSDimitry Andric       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
405591bc56edSDimitry Andric       if (!IA) return true;
405691bc56edSDimitry Andric 
405791bc56edSDimitry Andric       // If this is a memory operand, we're cool, otherwise bail out.
40587a7e6055SDimitry Andric       if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
405991bc56edSDimitry Andric         return true;
406091bc56edSDimitry Andric       continue;
406191bc56edSDimitry Andric     }
406291bc56edSDimitry Andric 
40637a7e6055SDimitry Andric     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI))
406491bc56edSDimitry Andric       return true;
406591bc56edSDimitry Andric   }
406691bc56edSDimitry Andric 
406791bc56edSDimitry Andric   return false;
406891bc56edSDimitry Andric }
406991bc56edSDimitry Andric 
40707d523365SDimitry Andric /// Return true if Val is already known to be live at the use site that we're
40717d523365SDimitry Andric /// folding it into. If so, there is no cost to include it in the addressing
40727d523365SDimitry Andric /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
40737d523365SDimitry Andric /// instruction already.
40747d523365SDimitry Andric bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
407591bc56edSDimitry Andric                                                    Value *KnownLive2) {
407691bc56edSDimitry Andric   // If Val is either of the known-live values, we know it is live!
407791bc56edSDimitry Andric   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
407891bc56edSDimitry Andric     return true;
407991bc56edSDimitry Andric 
408091bc56edSDimitry Andric   // All values other than instructions and arguments (e.g. constants) are live.
408191bc56edSDimitry Andric   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
408291bc56edSDimitry Andric 
408391bc56edSDimitry Andric   // If Val is a constant sized alloca in the entry block, it is live, this is
408491bc56edSDimitry Andric   // true because it is just a reference to the stack/frame pointer, which is
408591bc56edSDimitry Andric   // live for the whole function.
408691bc56edSDimitry Andric   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
408791bc56edSDimitry Andric     if (AI->isStaticAlloca())
408891bc56edSDimitry Andric       return true;
408991bc56edSDimitry Andric 
409091bc56edSDimitry Andric   // Check to see if this value is already used in the memory instruction's
409191bc56edSDimitry Andric   // block.  If so, it's already live into the block at the very least, so we
409291bc56edSDimitry Andric   // can reasonably fold it.
409391bc56edSDimitry Andric   return Val->isUsedInBasicBlock(MemoryInst->getParent());
409491bc56edSDimitry Andric }
409591bc56edSDimitry Andric 
40967d523365SDimitry Andric /// It is possible for the addressing mode of the machine to fold the specified
40977d523365SDimitry Andric /// instruction into a load or store that ultimately uses it.
40987d523365SDimitry Andric /// However, the specified instruction has multiple uses.
40997d523365SDimitry Andric /// Given this, it may actually increase register pressure to fold it
410091bc56edSDimitry Andric /// into the load. For example, consider this code:
410191bc56edSDimitry Andric ///
410291bc56edSDimitry Andric ///     X = ...
410391bc56edSDimitry Andric ///     Y = X+1
410491bc56edSDimitry Andric ///     use(Y)   -> nonload/store
410591bc56edSDimitry Andric ///     Z = Y+1
410691bc56edSDimitry Andric ///     load Z
410791bc56edSDimitry Andric ///
410891bc56edSDimitry Andric /// In this case, Y has multiple uses, and can be folded into the load of Z
410991bc56edSDimitry Andric /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
411091bc56edSDimitry Andric /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
411191bc56edSDimitry Andric /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
411291bc56edSDimitry Andric /// number of computations either.
411391bc56edSDimitry Andric ///
411491bc56edSDimitry Andric /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
411591bc56edSDimitry Andric /// X was live across 'load Z' for other reasons, we actually *would* want to
411691bc56edSDimitry Andric /// fold the addressing mode in the Z case.  This would make Y die earlier.
411791bc56edSDimitry Andric bool AddressingModeMatcher::
41187d523365SDimitry Andric isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
411991bc56edSDimitry Andric                                      ExtAddrMode &AMAfter) {
412091bc56edSDimitry Andric   if (IgnoreProfitability) return true;
412191bc56edSDimitry Andric 
412291bc56edSDimitry Andric   // AMBefore is the addressing mode before this instruction was folded into it,
412391bc56edSDimitry Andric   // and AMAfter is the addressing mode after the instruction was folded.  Get
412491bc56edSDimitry Andric   // the set of registers referenced by AMAfter and subtract out those
412591bc56edSDimitry Andric   // referenced by AMBefore: this is the set of values which folding in this
412691bc56edSDimitry Andric   // address extends the lifetime of.
412791bc56edSDimitry Andric   //
412891bc56edSDimitry Andric   // Note that there are only two potential values being referenced here,
412991bc56edSDimitry Andric   // BaseReg and ScaleReg (global addresses are always available, as are any
413091bc56edSDimitry Andric   // folded immediates).
413191bc56edSDimitry Andric   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
413291bc56edSDimitry Andric 
413391bc56edSDimitry Andric   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
413491bc56edSDimitry Andric   // lifetime wasn't extended by adding this instruction.
41357d523365SDimitry Andric   if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
413691bc56edSDimitry Andric     BaseReg = nullptr;
41377d523365SDimitry Andric   if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
413891bc56edSDimitry Andric     ScaledReg = nullptr;
413991bc56edSDimitry Andric 
414091bc56edSDimitry Andric   // If folding this instruction (and it's subexprs) didn't extend any live
414191bc56edSDimitry Andric   // ranges, we're ok with it.
414291bc56edSDimitry Andric   if (!BaseReg && !ScaledReg)
414391bc56edSDimitry Andric     return true;
414491bc56edSDimitry Andric 
41453ca95b02SDimitry Andric   // If all uses of this instruction can have the address mode sunk into them,
41463ca95b02SDimitry Andric   // we can remove the addressing mode and effectively trade one live register
41473ca95b02SDimitry Andric   // for another (at worst.)  In this context, folding an addressing mode into
41483ca95b02SDimitry Andric   // the use is just a particularly nice way of sinking it.
414991bc56edSDimitry Andric   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
415091bc56edSDimitry Andric   SmallPtrSet<Instruction*, 16> ConsideredInsts;
41517a7e6055SDimitry Andric   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
415291bc56edSDimitry Andric     return false;  // Has a non-memory, non-foldable use!
415391bc56edSDimitry Andric 
415491bc56edSDimitry Andric   // Now that we know that all uses of this instruction are part of a chain of
415591bc56edSDimitry Andric   // computation involving only operations that could theoretically be folded
41563ca95b02SDimitry Andric   // into a memory use, loop over each of these memory operation uses and see
41573ca95b02SDimitry Andric   // if they could  *actually* fold the instruction.  The assumption is that
41583ca95b02SDimitry Andric   // addressing modes are cheap and that duplicating the computation involved
41593ca95b02SDimitry Andric   // many times is worthwhile, even on a fastpath. For sinking candidates
41603ca95b02SDimitry Andric   // (i.e. cold call sites), this serves as a way to prevent excessive code
41613ca95b02SDimitry Andric   // growth since most architectures have some reasonable small and fast way to
41623ca95b02SDimitry Andric   // compute an effective address.  (i.e LEA on x86)
416391bc56edSDimitry Andric   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
416491bc56edSDimitry Andric   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
416591bc56edSDimitry Andric     Instruction *User = MemoryUses[i].first;
416691bc56edSDimitry Andric     unsigned OpNo = MemoryUses[i].second;
416791bc56edSDimitry Andric 
416891bc56edSDimitry Andric     // Get the access type of this use.  If the use isn't a pointer, we don't
416991bc56edSDimitry Andric     // know what it accesses.
417091bc56edSDimitry Andric     Value *Address = User->getOperand(OpNo);
417197bc6c73SDimitry Andric     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
417297bc6c73SDimitry Andric     if (!AddrTy)
417391bc56edSDimitry Andric       return false;
417497bc6c73SDimitry Andric     Type *AddressAccessTy = AddrTy->getElementType();
417597bc6c73SDimitry Andric     unsigned AS = AddrTy->getAddressSpace();
417691bc56edSDimitry Andric 
417791bc56edSDimitry Andric     // Do a match against the root of this address, ignoring profitability. This
417891bc56edSDimitry Andric     // will tell us if the addressing mode for the memory operation will
417991bc56edSDimitry Andric     // *actually* cover the shared instruction.
418091bc56edSDimitry Andric     ExtAddrMode Result;
418191bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
418291bc56edSDimitry Andric         TPT.getRestorationPoint();
41837a7e6055SDimitry Andric     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
41847a7e6055SDimitry Andric                                   AddressAccessTy, AS,
41858f0fd8f6SDimitry Andric                                   MemoryInst, Result, InsertedInsts,
418691bc56edSDimitry Andric                                   PromotedInsts, TPT);
418791bc56edSDimitry Andric     Matcher.IgnoreProfitability = true;
41887d523365SDimitry Andric     bool Success = Matcher.matchAddr(Address, 0);
418991bc56edSDimitry Andric     (void)Success; assert(Success && "Couldn't select *anything*?");
419091bc56edSDimitry Andric 
419191bc56edSDimitry Andric     // The match was to check the profitability, the changes made are not
419291bc56edSDimitry Andric     // part of the original matcher. Therefore, they should be dropped
419391bc56edSDimitry Andric     // otherwise the original matcher will not present the right state.
419491bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
419591bc56edSDimitry Andric 
419691bc56edSDimitry Andric     // If the match didn't cover I, then it won't be shared by it.
4197d88c1a5aSDimitry Andric     if (!is_contained(MatchedAddrModeInsts, I))
419891bc56edSDimitry Andric       return false;
419991bc56edSDimitry Andric 
420091bc56edSDimitry Andric     MatchedAddrModeInsts.clear();
420191bc56edSDimitry Andric   }
420291bc56edSDimitry Andric 
420391bc56edSDimitry Andric   return true;
420491bc56edSDimitry Andric }
420591bc56edSDimitry Andric 
420691bc56edSDimitry Andric } // end anonymous namespace
420791bc56edSDimitry Andric 
42087d523365SDimitry Andric /// Return true if the specified values are defined in a
420991bc56edSDimitry Andric /// different basic block than BB.
421091bc56edSDimitry Andric static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
421191bc56edSDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(V))
421291bc56edSDimitry Andric     return I->getParent() != BB;
421391bc56edSDimitry Andric   return false;
421491bc56edSDimitry Andric }
421591bc56edSDimitry Andric 
42163ca95b02SDimitry Andric /// Sink addressing mode computation immediate before MemoryInst if doing so
42173ca95b02SDimitry Andric /// can be done without increasing register pressure.  The need for the
42183ca95b02SDimitry Andric /// register pressure constraint means this can end up being an all or nothing
42193ca95b02SDimitry Andric /// decision for all uses of the same addressing computation.
42203ca95b02SDimitry Andric ///
42217d523365SDimitry Andric /// Load and Store Instructions often have addressing modes that can do
42227d523365SDimitry Andric /// significant amounts of computation. As such, instruction selection will try
42237d523365SDimitry Andric /// to get the load or store to do as much computation as possible for the
42247d523365SDimitry Andric /// program. The problem is that isel can only see within a single block. As
42257d523365SDimitry Andric /// such, we sink as much legal addressing mode work into the block as possible.
422691bc56edSDimitry Andric ///
422791bc56edSDimitry Andric /// This method is used to optimize both load/store and inline asms with memory
42283ca95b02SDimitry Andric /// operands.  It's also used to sink addressing computations feeding into cold
42293ca95b02SDimitry Andric /// call sites into their (cold) basic block.
42303ca95b02SDimitry Andric ///
42313ca95b02SDimitry Andric /// The motivation for handling sinking into cold blocks is that doing so can
42323ca95b02SDimitry Andric /// both enable other address mode sinking (by satisfying the register pressure
42333ca95b02SDimitry Andric /// constraint above), and reduce register pressure globally (by removing the
42343ca95b02SDimitry Andric /// addressing mode computation from the fast path entirely.).
42357d523365SDimitry Andric bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
423697bc6c73SDimitry Andric                                         Type *AccessTy, unsigned AddrSpace) {
423791bc56edSDimitry Andric   Value *Repl = Addr;
423891bc56edSDimitry Andric 
423991bc56edSDimitry Andric   // Try to collapse single-value PHI nodes.  This is necessary to undo
424091bc56edSDimitry Andric   // unprofitable PRE transformations.
424191bc56edSDimitry Andric   SmallVector<Value*, 8> worklist;
424291bc56edSDimitry Andric   SmallPtrSet<Value*, 16> Visited;
424391bc56edSDimitry Andric   worklist.push_back(Addr);
424491bc56edSDimitry Andric 
424591bc56edSDimitry Andric   // Use a worklist to iteratively look through PHI nodes, and ensure that
424691bc56edSDimitry Andric   // the addressing mode obtained from the non-PHI roots of the graph
424791bc56edSDimitry Andric   // are equivalent.
424891bc56edSDimitry Andric   Value *Consensus = nullptr;
424991bc56edSDimitry Andric   unsigned NumUsesConsensus = 0;
425091bc56edSDimitry Andric   bool IsNumUsesConsensusValid = false;
425191bc56edSDimitry Andric   SmallVector<Instruction*, 16> AddrModeInsts;
425291bc56edSDimitry Andric   ExtAddrMode AddrMode;
42537a7e6055SDimitry Andric   TypePromotionTransaction TPT(RemovedInsts);
425491bc56edSDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
425591bc56edSDimitry Andric       TPT.getRestorationPoint();
425691bc56edSDimitry Andric   while (!worklist.empty()) {
425791bc56edSDimitry Andric     Value *V = worklist.back();
425891bc56edSDimitry Andric     worklist.pop_back();
425991bc56edSDimitry Andric 
426091bc56edSDimitry Andric     // Break use-def graph loops.
426139d628a0SDimitry Andric     if (!Visited.insert(V).second) {
426291bc56edSDimitry Andric       Consensus = nullptr;
426391bc56edSDimitry Andric       break;
426491bc56edSDimitry Andric     }
426591bc56edSDimitry Andric 
426691bc56edSDimitry Andric     // For a PHI node, push all of its incoming values.
426791bc56edSDimitry Andric     if (PHINode *P = dyn_cast<PHINode>(V)) {
4268ff0cc061SDimitry Andric       for (Value *IncValue : P->incoming_values())
4269ff0cc061SDimitry Andric         worklist.push_back(IncValue);
427091bc56edSDimitry Andric       continue;
427191bc56edSDimitry Andric     }
427291bc56edSDimitry Andric 
42733ca95b02SDimitry Andric     // For non-PHIs, determine the addressing mode being computed.  Note that
42743ca95b02SDimitry Andric     // the result may differ depending on what other uses our candidate
42753ca95b02SDimitry Andric     // addressing instructions might have.
427691bc56edSDimitry Andric     SmallVector<Instruction*, 16> NewAddrModeInsts;
427791bc56edSDimitry Andric     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
42787a7e6055SDimitry Andric       V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI,
42798f0fd8f6SDimitry Andric       InsertedInsts, PromotedInsts, TPT);
428091bc56edSDimitry Andric 
428191bc56edSDimitry Andric     // This check is broken into two cases with very similar code to avoid using
428291bc56edSDimitry Andric     // getNumUses() as much as possible. Some values have a lot of uses, so
428391bc56edSDimitry Andric     // calling getNumUses() unconditionally caused a significant compile-time
428491bc56edSDimitry Andric     // regression.
428591bc56edSDimitry Andric     if (!Consensus) {
428691bc56edSDimitry Andric       Consensus = V;
428791bc56edSDimitry Andric       AddrMode = NewAddrMode;
428891bc56edSDimitry Andric       AddrModeInsts = NewAddrModeInsts;
428991bc56edSDimitry Andric       continue;
429091bc56edSDimitry Andric     } else if (NewAddrMode == AddrMode) {
429191bc56edSDimitry Andric       if (!IsNumUsesConsensusValid) {
429291bc56edSDimitry Andric         NumUsesConsensus = Consensus->getNumUses();
429391bc56edSDimitry Andric         IsNumUsesConsensusValid = true;
429491bc56edSDimitry Andric       }
429591bc56edSDimitry Andric 
429691bc56edSDimitry Andric       // Ensure that the obtained addressing mode is equivalent to that obtained
429791bc56edSDimitry Andric       // for all other roots of the PHI traversal.  Also, when choosing one
429891bc56edSDimitry Andric       // such root as representative, select the one with the most uses in order
429991bc56edSDimitry Andric       // to keep the cost modeling heuristics in AddressingModeMatcher
430091bc56edSDimitry Andric       // applicable.
430191bc56edSDimitry Andric       unsigned NumUses = V->getNumUses();
430291bc56edSDimitry Andric       if (NumUses > NumUsesConsensus) {
430391bc56edSDimitry Andric         Consensus = V;
430491bc56edSDimitry Andric         NumUsesConsensus = NumUses;
430591bc56edSDimitry Andric         AddrModeInsts = NewAddrModeInsts;
430691bc56edSDimitry Andric       }
430791bc56edSDimitry Andric       continue;
430891bc56edSDimitry Andric     }
430991bc56edSDimitry Andric 
431091bc56edSDimitry Andric     Consensus = nullptr;
431191bc56edSDimitry Andric     break;
431291bc56edSDimitry Andric   }
431391bc56edSDimitry Andric 
431491bc56edSDimitry Andric   // If the addressing mode couldn't be determined, or if multiple different
431591bc56edSDimitry Andric   // ones were determined, bail out now.
431691bc56edSDimitry Andric   if (!Consensus) {
431791bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
431891bc56edSDimitry Andric     return false;
431991bc56edSDimitry Andric   }
432091bc56edSDimitry Andric   TPT.commit();
432191bc56edSDimitry Andric 
432291bc56edSDimitry Andric   // If all the instructions matched are already in this BB, don't do anything.
4323d88c1a5aSDimitry Andric   if (none_of(AddrModeInsts, [&](Value *V) {
4324d88c1a5aSDimitry Andric         return IsNonLocalValue(V, MemoryInst->getParent());
4325d88c1a5aSDimitry Andric       })) {
432691bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
432791bc56edSDimitry Andric     return false;
432891bc56edSDimitry Andric   }
432991bc56edSDimitry Andric 
433091bc56edSDimitry Andric   // Insert this computation right after this user.  Since our caller is
433191bc56edSDimitry Andric   // scanning from the top of the BB to the bottom, reuse of the expr are
433291bc56edSDimitry Andric   // guaranteed to happen later.
433391bc56edSDimitry Andric   IRBuilder<> Builder(MemoryInst);
433491bc56edSDimitry Andric 
433591bc56edSDimitry Andric   // Now that we determined the addressing expression we want to use and know
433691bc56edSDimitry Andric   // that we have to sink it into this block.  Check to see if we have already
433791bc56edSDimitry Andric   // done this for some other load/store instr in this block.  If so, reuse the
433891bc56edSDimitry Andric   // computation.
433991bc56edSDimitry Andric   Value *&SunkAddr = SunkAddrs[Addr];
434091bc56edSDimitry Andric   if (SunkAddr) {
434191bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
434291bc56edSDimitry Andric                  << *MemoryInst << "\n");
434391bc56edSDimitry Andric     if (SunkAddr->getType() != Addr->getType())
43447a7e6055SDimitry Andric       SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
4345ff0cc061SDimitry Andric   } else if (AddrSinkUsingGEPs ||
4346ff0cc061SDimitry Andric              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
43477a7e6055SDimitry Andric               SubtargetInfo->useAA())) {
434891bc56edSDimitry Andric     // By default, we use the GEP-based method when AA is used later. This
434991bc56edSDimitry Andric     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
435091bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
435191bc56edSDimitry Andric                  << *MemoryInst << "\n");
4352875ed548SDimitry Andric     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
435391bc56edSDimitry Andric     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
435491bc56edSDimitry Andric 
435591bc56edSDimitry Andric     // First, find the pointer.
435691bc56edSDimitry Andric     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
435791bc56edSDimitry Andric       ResultPtr = AddrMode.BaseReg;
435891bc56edSDimitry Andric       AddrMode.BaseReg = nullptr;
435991bc56edSDimitry Andric     }
436091bc56edSDimitry Andric 
436191bc56edSDimitry Andric     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
436291bc56edSDimitry Andric       // We can't add more than one pointer together, nor can we scale a
436391bc56edSDimitry Andric       // pointer (both of which seem meaningless).
436491bc56edSDimitry Andric       if (ResultPtr || AddrMode.Scale != 1)
436591bc56edSDimitry Andric         return false;
436691bc56edSDimitry Andric 
436791bc56edSDimitry Andric       ResultPtr = AddrMode.ScaledReg;
436891bc56edSDimitry Andric       AddrMode.Scale = 0;
436991bc56edSDimitry Andric     }
437091bc56edSDimitry Andric 
437191bc56edSDimitry Andric     if (AddrMode.BaseGV) {
437291bc56edSDimitry Andric       if (ResultPtr)
437391bc56edSDimitry Andric         return false;
437491bc56edSDimitry Andric 
437591bc56edSDimitry Andric       ResultPtr = AddrMode.BaseGV;
437691bc56edSDimitry Andric     }
437791bc56edSDimitry Andric 
437891bc56edSDimitry Andric     // If the real base value actually came from an inttoptr, then the matcher
437991bc56edSDimitry Andric     // will look through it and provide only the integer value. In that case,
438091bc56edSDimitry Andric     // use it here.
438191bc56edSDimitry Andric     if (!ResultPtr && AddrMode.BaseReg) {
438291bc56edSDimitry Andric       ResultPtr =
438391bc56edSDimitry Andric         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
438491bc56edSDimitry Andric       AddrMode.BaseReg = nullptr;
438591bc56edSDimitry Andric     } else if (!ResultPtr && AddrMode.Scale == 1) {
438691bc56edSDimitry Andric       ResultPtr =
438791bc56edSDimitry Andric         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
438891bc56edSDimitry Andric       AddrMode.Scale = 0;
438991bc56edSDimitry Andric     }
439091bc56edSDimitry Andric 
439191bc56edSDimitry Andric     if (!ResultPtr &&
439291bc56edSDimitry Andric         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
439391bc56edSDimitry Andric       SunkAddr = Constant::getNullValue(Addr->getType());
439491bc56edSDimitry Andric     } else if (!ResultPtr) {
439591bc56edSDimitry Andric       return false;
439691bc56edSDimitry Andric     } else {
439791bc56edSDimitry Andric       Type *I8PtrTy =
439891bc56edSDimitry Andric           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4399ff0cc061SDimitry Andric       Type *I8Ty = Builder.getInt8Ty();
440091bc56edSDimitry Andric 
440191bc56edSDimitry Andric       // Start with the base register. Do this first so that subsequent address
440291bc56edSDimitry Andric       // matching finds it last, which will prevent it from trying to match it
440391bc56edSDimitry Andric       // as the scaled value in case it happens to be a mul. That would be
440491bc56edSDimitry Andric       // problematic if we've sunk a different mul for the scale, because then
440591bc56edSDimitry Andric       // we'd end up sinking both muls.
440691bc56edSDimitry Andric       if (AddrMode.BaseReg) {
440791bc56edSDimitry Andric         Value *V = AddrMode.BaseReg;
440891bc56edSDimitry Andric         if (V->getType() != IntPtrTy)
440991bc56edSDimitry Andric           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
441091bc56edSDimitry Andric 
441191bc56edSDimitry Andric         ResultIndex = V;
441291bc56edSDimitry Andric       }
441391bc56edSDimitry Andric 
441491bc56edSDimitry Andric       // Add the scale value.
441591bc56edSDimitry Andric       if (AddrMode.Scale) {
441691bc56edSDimitry Andric         Value *V = AddrMode.ScaledReg;
441791bc56edSDimitry Andric         if (V->getType() == IntPtrTy) {
441891bc56edSDimitry Andric           // done.
441991bc56edSDimitry Andric         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
442091bc56edSDimitry Andric                    cast<IntegerType>(V->getType())->getBitWidth()) {
442191bc56edSDimitry Andric           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
442291bc56edSDimitry Andric         } else {
442391bc56edSDimitry Andric           // It is only safe to sign extend the BaseReg if we know that the math
442491bc56edSDimitry Andric           // required to create it did not overflow before we extend it. Since
442591bc56edSDimitry Andric           // the original IR value was tossed in favor of a constant back when
442691bc56edSDimitry Andric           // the AddrMode was created we need to bail out gracefully if widths
442791bc56edSDimitry Andric           // do not match instead of extending it.
442891bc56edSDimitry Andric           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
442991bc56edSDimitry Andric           if (I && (ResultIndex != AddrMode.BaseReg))
443091bc56edSDimitry Andric             I->eraseFromParent();
443191bc56edSDimitry Andric           return false;
443291bc56edSDimitry Andric         }
443391bc56edSDimitry Andric 
443491bc56edSDimitry Andric         if (AddrMode.Scale != 1)
443591bc56edSDimitry Andric           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
443691bc56edSDimitry Andric                                 "sunkaddr");
443791bc56edSDimitry Andric         if (ResultIndex)
443891bc56edSDimitry Andric           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
443991bc56edSDimitry Andric         else
444091bc56edSDimitry Andric           ResultIndex = V;
444191bc56edSDimitry Andric       }
444291bc56edSDimitry Andric 
444391bc56edSDimitry Andric       // Add in the Base Offset if present.
444491bc56edSDimitry Andric       if (AddrMode.BaseOffs) {
444591bc56edSDimitry Andric         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
444691bc56edSDimitry Andric         if (ResultIndex) {
444791bc56edSDimitry Andric           // We need to add this separately from the scale above to help with
444891bc56edSDimitry Andric           // SDAG consecutive load/store merging.
444991bc56edSDimitry Andric           if (ResultPtr->getType() != I8PtrTy)
44507a7e6055SDimitry Andric             ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4451ff0cc061SDimitry Andric           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
445291bc56edSDimitry Andric         }
445391bc56edSDimitry Andric 
445491bc56edSDimitry Andric         ResultIndex = V;
445591bc56edSDimitry Andric       }
445691bc56edSDimitry Andric 
445791bc56edSDimitry Andric       if (!ResultIndex) {
445891bc56edSDimitry Andric         SunkAddr = ResultPtr;
445991bc56edSDimitry Andric       } else {
446091bc56edSDimitry Andric         if (ResultPtr->getType() != I8PtrTy)
44617a7e6055SDimitry Andric           ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4462ff0cc061SDimitry Andric         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
446391bc56edSDimitry Andric       }
446491bc56edSDimitry Andric 
446591bc56edSDimitry Andric       if (SunkAddr->getType() != Addr->getType())
44667a7e6055SDimitry Andric         SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
446791bc56edSDimitry Andric     }
446891bc56edSDimitry Andric   } else {
446991bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
447091bc56edSDimitry Andric                  << *MemoryInst << "\n");
4471875ed548SDimitry Andric     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
447291bc56edSDimitry Andric     Value *Result = nullptr;
447391bc56edSDimitry Andric 
447491bc56edSDimitry Andric     // Start with the base register. Do this first so that subsequent address
447591bc56edSDimitry Andric     // matching finds it last, which will prevent it from trying to match it
447691bc56edSDimitry Andric     // as the scaled value in case it happens to be a mul. That would be
447791bc56edSDimitry Andric     // problematic if we've sunk a different mul for the scale, because then
447891bc56edSDimitry Andric     // we'd end up sinking both muls.
447991bc56edSDimitry Andric     if (AddrMode.BaseReg) {
448091bc56edSDimitry Andric       Value *V = AddrMode.BaseReg;
448191bc56edSDimitry Andric       if (V->getType()->isPointerTy())
448291bc56edSDimitry Andric         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
448391bc56edSDimitry Andric       if (V->getType() != IntPtrTy)
448491bc56edSDimitry Andric         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
448591bc56edSDimitry Andric       Result = V;
448691bc56edSDimitry Andric     }
448791bc56edSDimitry Andric 
448891bc56edSDimitry Andric     // Add the scale value.
448991bc56edSDimitry Andric     if (AddrMode.Scale) {
449091bc56edSDimitry Andric       Value *V = AddrMode.ScaledReg;
449191bc56edSDimitry Andric       if (V->getType() == IntPtrTy) {
449291bc56edSDimitry Andric         // done.
449391bc56edSDimitry Andric       } else if (V->getType()->isPointerTy()) {
449491bc56edSDimitry Andric         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
449591bc56edSDimitry Andric       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
449691bc56edSDimitry Andric                  cast<IntegerType>(V->getType())->getBitWidth()) {
449791bc56edSDimitry Andric         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
449891bc56edSDimitry Andric       } else {
449991bc56edSDimitry Andric         // It is only safe to sign extend the BaseReg if we know that the math
450091bc56edSDimitry Andric         // required to create it did not overflow before we extend it. Since
450191bc56edSDimitry Andric         // the original IR value was tossed in favor of a constant back when
450291bc56edSDimitry Andric         // the AddrMode was created we need to bail out gracefully if widths
450391bc56edSDimitry Andric         // do not match instead of extending it.
450491bc56edSDimitry Andric         Instruction *I = dyn_cast_or_null<Instruction>(Result);
450591bc56edSDimitry Andric         if (I && (Result != AddrMode.BaseReg))
450691bc56edSDimitry Andric           I->eraseFromParent();
450791bc56edSDimitry Andric         return false;
450891bc56edSDimitry Andric       }
450991bc56edSDimitry Andric       if (AddrMode.Scale != 1)
451091bc56edSDimitry Andric         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
451191bc56edSDimitry Andric                               "sunkaddr");
451291bc56edSDimitry Andric       if (Result)
451391bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
451491bc56edSDimitry Andric       else
451591bc56edSDimitry Andric         Result = V;
451691bc56edSDimitry Andric     }
451791bc56edSDimitry Andric 
451891bc56edSDimitry Andric     // Add in the BaseGV if present.
451991bc56edSDimitry Andric     if (AddrMode.BaseGV) {
452091bc56edSDimitry Andric       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
452191bc56edSDimitry Andric       if (Result)
452291bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
452391bc56edSDimitry Andric       else
452491bc56edSDimitry Andric         Result = V;
452591bc56edSDimitry Andric     }
452691bc56edSDimitry Andric 
452791bc56edSDimitry Andric     // Add in the Base Offset if present.
452891bc56edSDimitry Andric     if (AddrMode.BaseOffs) {
452991bc56edSDimitry Andric       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
453091bc56edSDimitry Andric       if (Result)
453191bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
453291bc56edSDimitry Andric       else
453391bc56edSDimitry Andric         Result = V;
453491bc56edSDimitry Andric     }
453591bc56edSDimitry Andric 
453691bc56edSDimitry Andric     if (!Result)
453791bc56edSDimitry Andric       SunkAddr = Constant::getNullValue(Addr->getType());
453891bc56edSDimitry Andric     else
453991bc56edSDimitry Andric       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
454091bc56edSDimitry Andric   }
454191bc56edSDimitry Andric 
454291bc56edSDimitry Andric   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
454391bc56edSDimitry Andric 
454491bc56edSDimitry Andric   // If we have no uses, recursively delete the value and all dead instructions
454591bc56edSDimitry Andric   // using it.
454691bc56edSDimitry Andric   if (Repl->use_empty()) {
454791bc56edSDimitry Andric     // This can cause recursive deletion, which can invalidate our iterator.
4548f37b6182SDimitry Andric     // Use a WeakTrackingVH to hold onto it in case this happens.
45493ca95b02SDimitry Andric     Value *CurValue = &*CurInstIterator;
4550f37b6182SDimitry Andric     WeakTrackingVH IterHandle(CurValue);
455191bc56edSDimitry Andric     BasicBlock *BB = CurInstIterator->getParent();
455291bc56edSDimitry Andric 
455391bc56edSDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
455491bc56edSDimitry Andric 
45553ca95b02SDimitry Andric     if (IterHandle != CurValue) {
455691bc56edSDimitry Andric       // If the iterator instruction was recursively deleted, start over at the
455791bc56edSDimitry Andric       // start of the block.
455891bc56edSDimitry Andric       CurInstIterator = BB->begin();
455991bc56edSDimitry Andric       SunkAddrs.clear();
456091bc56edSDimitry Andric     }
456191bc56edSDimitry Andric   }
456291bc56edSDimitry Andric   ++NumMemoryInsts;
456391bc56edSDimitry Andric   return true;
456491bc56edSDimitry Andric }
456591bc56edSDimitry Andric 
45667d523365SDimitry Andric /// If there are any memory operands, use OptimizeMemoryInst to sink their
45677d523365SDimitry Andric /// address computing into the block when possible / profitable.
45687d523365SDimitry Andric bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
456991bc56edSDimitry Andric   bool MadeChange = false;
457091bc56edSDimitry Andric 
4571ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI =
4572db17bf38SDimitry Andric       TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
4573875ed548SDimitry Andric   TargetLowering::AsmOperandInfoVector TargetConstraints =
4574875ed548SDimitry Andric       TLI->ParseConstraints(*DL, TRI, CS);
457591bc56edSDimitry Andric   unsigned ArgNo = 0;
457691bc56edSDimitry Andric   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
457791bc56edSDimitry Andric     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
457891bc56edSDimitry Andric 
457991bc56edSDimitry Andric     // Compute the constraint code and ConstraintType to use.
458091bc56edSDimitry Andric     TLI->ComputeConstraintToUse(OpInfo, SDValue());
458191bc56edSDimitry Andric 
458291bc56edSDimitry Andric     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
458391bc56edSDimitry Andric         OpInfo.isIndirect) {
458491bc56edSDimitry Andric       Value *OpVal = CS->getArgOperand(ArgNo++);
45857d523365SDimitry Andric       MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
458691bc56edSDimitry Andric     } else if (OpInfo.Type == InlineAsm::isInput)
458791bc56edSDimitry Andric       ArgNo++;
458891bc56edSDimitry Andric   }
458991bc56edSDimitry Andric 
459091bc56edSDimitry Andric   return MadeChange;
459191bc56edSDimitry Andric }
459291bc56edSDimitry Andric 
45937a7e6055SDimitry Andric /// \brief Check if all the uses of \p Val are equivalent (or free) zero or
459439d628a0SDimitry Andric /// sign extensions.
45957a7e6055SDimitry Andric static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
45967a7e6055SDimitry Andric   assert(!Val->use_empty() && "Input must have at least one use");
45977a7e6055SDimitry Andric   const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
459839d628a0SDimitry Andric   bool IsSExt = isa<SExtInst>(FirstUser);
459939d628a0SDimitry Andric   Type *ExtTy = FirstUser->getType();
46007a7e6055SDimitry Andric   for (const User *U : Val->users()) {
460139d628a0SDimitry Andric     const Instruction *UI = cast<Instruction>(U);
460239d628a0SDimitry Andric     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
460339d628a0SDimitry Andric       return false;
460439d628a0SDimitry Andric     Type *CurTy = UI->getType();
460539d628a0SDimitry Andric     // Same input and output types: Same instruction after CSE.
460639d628a0SDimitry Andric     if (CurTy == ExtTy)
460739d628a0SDimitry Andric       continue;
460839d628a0SDimitry Andric 
460939d628a0SDimitry Andric     // If IsSExt is true, we are in this situation:
46107a7e6055SDimitry Andric     // a = Val
461139d628a0SDimitry Andric     // b = sext ty1 a to ty2
461239d628a0SDimitry Andric     // c = sext ty1 a to ty3
461339d628a0SDimitry Andric     // Assuming ty2 is shorter than ty3, this could be turned into:
46147a7e6055SDimitry Andric     // a = Val
461539d628a0SDimitry Andric     // b = sext ty1 a to ty2
461639d628a0SDimitry Andric     // c = sext ty2 b to ty3
461739d628a0SDimitry Andric     // However, the last sext is not free.
461839d628a0SDimitry Andric     if (IsSExt)
461939d628a0SDimitry Andric       return false;
462039d628a0SDimitry Andric 
462139d628a0SDimitry Andric     // This is a ZExt, maybe this is free to extend from one type to another.
462239d628a0SDimitry Andric     // In that case, we would not account for a different use.
462339d628a0SDimitry Andric     Type *NarrowTy;
462439d628a0SDimitry Andric     Type *LargeTy;
462539d628a0SDimitry Andric     if (ExtTy->getScalarType()->getIntegerBitWidth() >
462639d628a0SDimitry Andric         CurTy->getScalarType()->getIntegerBitWidth()) {
462739d628a0SDimitry Andric       NarrowTy = CurTy;
462839d628a0SDimitry Andric       LargeTy = ExtTy;
462939d628a0SDimitry Andric     } else {
463039d628a0SDimitry Andric       NarrowTy = ExtTy;
463139d628a0SDimitry Andric       LargeTy = CurTy;
463239d628a0SDimitry Andric     }
463339d628a0SDimitry Andric 
463439d628a0SDimitry Andric     if (!TLI.isZExtFree(NarrowTy, LargeTy))
463539d628a0SDimitry Andric       return false;
463639d628a0SDimitry Andric   }
463739d628a0SDimitry Andric   // All uses are the same or can be derived from one another for free.
463839d628a0SDimitry Andric   return true;
463939d628a0SDimitry Andric }
464039d628a0SDimitry Andric 
46417a7e6055SDimitry Andric /// \brief Try to speculatively promote extensions in \p Exts and continue
46427a7e6055SDimitry Andric /// promoting through newly promoted operands recursively as far as doing so is
46437a7e6055SDimitry Andric /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
46447a7e6055SDimitry Andric /// When some promotion happened, \p TPT contains the proper state to revert
46457a7e6055SDimitry Andric /// them.
464639d628a0SDimitry Andric ///
46477a7e6055SDimitry Andric /// \return true if some promotion happened, false otherwise.
46487a7e6055SDimitry Andric bool CodeGenPrepare::tryToPromoteExts(
46497a7e6055SDimitry Andric     TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
46507a7e6055SDimitry Andric     SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
46517a7e6055SDimitry Andric     unsigned CreatedInstsCost) {
46527a7e6055SDimitry Andric   bool Promoted = false;
46537a7e6055SDimitry Andric 
46547a7e6055SDimitry Andric   // Iterate over all the extensions to try to promote them.
465539d628a0SDimitry Andric   for (auto I : Exts) {
46567a7e6055SDimitry Andric     // Early check if we directly have ext(load).
46577a7e6055SDimitry Andric     if (isa<LoadInst>(I->getOperand(0))) {
46587a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
46597a7e6055SDimitry Andric       continue;
466039d628a0SDimitry Andric     }
46617a7e6055SDimitry Andric 
46627a7e6055SDimitry Andric     // Check whether or not we want to do any promotion.  The reason we have
46637a7e6055SDimitry Andric     // this check inside the for loop is to catch the case where an extension
46647a7e6055SDimitry Andric     // is directly fed by a load because in such case the extension can be moved
46657a7e6055SDimitry Andric     // up without any promotion on its operands.
466639d628a0SDimitry Andric     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
46677a7e6055SDimitry Andric       return false;
46687a7e6055SDimitry Andric 
466939d628a0SDimitry Andric     // Get the action to perform the promotion.
46707a7e6055SDimitry Andric     TypePromotionHelper::Action TPH =
46717a7e6055SDimitry Andric         TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
467239d628a0SDimitry Andric     // Check if we can promote.
46737a7e6055SDimitry Andric     if (!TPH) {
46747a7e6055SDimitry Andric       // Save the current extension as we cannot move up through its operand.
46757a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
467639d628a0SDimitry Andric       continue;
46777a7e6055SDimitry Andric     }
46787a7e6055SDimitry Andric 
467939d628a0SDimitry Andric     // Save the current state.
468039d628a0SDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
468139d628a0SDimitry Andric         TPT.getRestorationPoint();
468239d628a0SDimitry Andric     SmallVector<Instruction *, 4> NewExts;
4683ff0cc061SDimitry Andric     unsigned NewCreatedInstsCost = 0;
4684ff0cc061SDimitry Andric     unsigned ExtCost = !TLI->isExtFree(I);
468539d628a0SDimitry Andric     // Promote.
4686ff0cc061SDimitry Andric     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4687ff0cc061SDimitry Andric                              &NewExts, nullptr, *TLI);
468839d628a0SDimitry Andric     assert(PromotedVal &&
468939d628a0SDimitry Andric            "TypePromotionHelper should have filtered out those cases");
469039d628a0SDimitry Andric 
469139d628a0SDimitry Andric     // We would be able to merge only one extension in a load.
469239d628a0SDimitry Andric     // Therefore, if we have more than 1 new extension we heuristically
469339d628a0SDimitry Andric     // cut this search path, because it means we degrade the code quality.
469439d628a0SDimitry Andric     // With exactly 2, the transformation is neutral, because we will merge
469539d628a0SDimitry Andric     // one extension but leave one. However, we optimistically keep going,
469639d628a0SDimitry Andric     // because the new extension may be removed too.
4697ff0cc061SDimitry Andric     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
46987a7e6055SDimitry Andric     // FIXME: It would be possible to propagate a negative value instead of
46997a7e6055SDimitry Andric     // conservatively ceiling it to 0.
47007a7e6055SDimitry Andric     TotalCreatedInstsCost =
47017a7e6055SDimitry Andric         std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
470239d628a0SDimitry Andric     if (!StressExtLdPromotion &&
4703ff0cc061SDimitry Andric         (TotalCreatedInstsCost > 1 ||
4704875ed548SDimitry Andric          !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
47057a7e6055SDimitry Andric       // This promotion is not profitable, rollback to the previous state, and
47067a7e6055SDimitry Andric       // save the current extension in ProfitablyMovedExts as the latest
47077a7e6055SDimitry Andric       // speculative promotion turned out to be unprofitable.
470839d628a0SDimitry Andric       TPT.rollback(LastKnownGood);
47097a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
47107a7e6055SDimitry Andric       continue;
47117a7e6055SDimitry Andric     }
47127a7e6055SDimitry Andric     // Continue promoting NewExts as far as doing so is profitable.
47137a7e6055SDimitry Andric     SmallVector<Instruction *, 2> NewlyMovedExts;
47147a7e6055SDimitry Andric     (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
47157a7e6055SDimitry Andric     bool NewPromoted = false;
47167a7e6055SDimitry Andric     for (auto ExtInst : NewlyMovedExts) {
47177a7e6055SDimitry Andric       Instruction *MovedExt = cast<Instruction>(ExtInst);
47187a7e6055SDimitry Andric       Value *ExtOperand = MovedExt->getOperand(0);
47197a7e6055SDimitry Andric       // If we have reached to a load, we need this extra profitability check
47207a7e6055SDimitry Andric       // as it could potentially be merged into an ext(load).
47217a7e6055SDimitry Andric       if (isa<LoadInst>(ExtOperand) &&
47227a7e6055SDimitry Andric           !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
47237a7e6055SDimitry Andric             (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
47247a7e6055SDimitry Andric         continue;
47257a7e6055SDimitry Andric 
47267a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(MovedExt);
47277a7e6055SDimitry Andric       NewPromoted = true;
47287a7e6055SDimitry Andric     }
47297a7e6055SDimitry Andric 
47307a7e6055SDimitry Andric     // If none of speculative promotions for NewExts is profitable, rollback
47317a7e6055SDimitry Andric     // and save the current extension (I) as the last profitable extension.
47327a7e6055SDimitry Andric     if (!NewPromoted) {
47337a7e6055SDimitry Andric       TPT.rollback(LastKnownGood);
47347a7e6055SDimitry Andric       ProfitablyMovedExts.push_back(I);
473539d628a0SDimitry Andric       continue;
473639d628a0SDimitry Andric     }
473739d628a0SDimitry Andric     // The promotion is profitable.
47387a7e6055SDimitry Andric     Promoted = true;
473939d628a0SDimitry Andric   }
47407a7e6055SDimitry Andric   return Promoted;
47417a7e6055SDimitry Andric }
47427a7e6055SDimitry Andric 
47437a7e6055SDimitry Andric /// Merging redundant sexts when one is dominating the other.
47447a7e6055SDimitry Andric bool CodeGenPrepare::mergeSExts(Function &F) {
47457a7e6055SDimitry Andric   DominatorTree DT(F);
47467a7e6055SDimitry Andric   bool Changed = false;
47477a7e6055SDimitry Andric   for (auto &Entry : ValToSExtendedUses) {
47487a7e6055SDimitry Andric     SExts &Insts = Entry.second;
47497a7e6055SDimitry Andric     SExts CurPts;
47507a7e6055SDimitry Andric     for (Instruction *Inst : Insts) {
47517a7e6055SDimitry Andric       if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
47527a7e6055SDimitry Andric           Inst->getOperand(0) != Entry.first)
47537a7e6055SDimitry Andric         continue;
47547a7e6055SDimitry Andric       bool inserted = false;
47557a7e6055SDimitry Andric       for (auto &Pt : CurPts) {
47567a7e6055SDimitry Andric         if (DT.dominates(Inst, Pt)) {
47577a7e6055SDimitry Andric           Pt->replaceAllUsesWith(Inst);
47587a7e6055SDimitry Andric           RemovedInsts.insert(Pt);
47597a7e6055SDimitry Andric           Pt->removeFromParent();
47607a7e6055SDimitry Andric           Pt = Inst;
47617a7e6055SDimitry Andric           inserted = true;
47627a7e6055SDimitry Andric           Changed = true;
47637a7e6055SDimitry Andric           break;
47647a7e6055SDimitry Andric         }
47657a7e6055SDimitry Andric         if (!DT.dominates(Pt, Inst))
47667a7e6055SDimitry Andric           // Give up if we need to merge in a common dominator as the
47677a7e6055SDimitry Andric           // expermients show it is not profitable.
47687a7e6055SDimitry Andric           continue;
47697a7e6055SDimitry Andric         Inst->replaceAllUsesWith(Pt);
47707a7e6055SDimitry Andric         RemovedInsts.insert(Inst);
47717a7e6055SDimitry Andric         Inst->removeFromParent();
47727a7e6055SDimitry Andric         inserted = true;
47737a7e6055SDimitry Andric         Changed = true;
47747a7e6055SDimitry Andric         break;
47757a7e6055SDimitry Andric       }
47767a7e6055SDimitry Andric       if (!inserted)
47777a7e6055SDimitry Andric         CurPts.push_back(Inst);
47787a7e6055SDimitry Andric     }
47797a7e6055SDimitry Andric   }
47807a7e6055SDimitry Andric   return Changed;
47817a7e6055SDimitry Andric }
47827a7e6055SDimitry Andric 
47837a7e6055SDimitry Andric /// Return true, if an ext(load) can be formed from an extension in
47847a7e6055SDimitry Andric /// \p MovedExts.
47857a7e6055SDimitry Andric bool CodeGenPrepare::canFormExtLd(
47867a7e6055SDimitry Andric     const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
47877a7e6055SDimitry Andric     Instruction *&Inst, bool HasPromoted) {
47887a7e6055SDimitry Andric   for (auto *MovedExtInst : MovedExts) {
47897a7e6055SDimitry Andric     if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
47907a7e6055SDimitry Andric       LI = cast<LoadInst>(MovedExtInst->getOperand(0));
47917a7e6055SDimitry Andric       Inst = MovedExtInst;
47927a7e6055SDimitry Andric       break;
47937a7e6055SDimitry Andric     }
47947a7e6055SDimitry Andric   }
47957a7e6055SDimitry Andric   if (!LI)
479639d628a0SDimitry Andric     return false;
47977a7e6055SDimitry Andric 
47987a7e6055SDimitry Andric   // If they're already in the same block, there's nothing to do.
47997a7e6055SDimitry Andric   // Make the cheap checks first if we did not promote.
48007a7e6055SDimitry Andric   // If we promoted, we need to check if it is indeed profitable.
48017a7e6055SDimitry Andric   if (!HasPromoted && LI->getParent() == Inst->getParent())
48027a7e6055SDimitry Andric     return false;
48037a7e6055SDimitry Andric 
48047a7e6055SDimitry Andric   EVT VT = TLI->getValueType(*DL, Inst->getType());
48057a7e6055SDimitry Andric   EVT LoadVT = TLI->getValueType(*DL, LI->getType());
48067a7e6055SDimitry Andric 
48077a7e6055SDimitry Andric   // If the load has other users and the truncate is not free, this probably
48087a7e6055SDimitry Andric   // isn't worthwhile.
48097a7e6055SDimitry Andric   if (!LI->hasOneUse() && (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
48107a7e6055SDimitry Andric       !TLI->isTruncateFree(Inst->getType(), LI->getType()))
48117a7e6055SDimitry Andric     return false;
48127a7e6055SDimitry Andric 
48137a7e6055SDimitry Andric   // Check whether the target supports casts folded into loads.
48147a7e6055SDimitry Andric   unsigned LType;
48157a7e6055SDimitry Andric   if (isa<ZExtInst>(Inst))
48167a7e6055SDimitry Andric     LType = ISD::ZEXTLOAD;
48177a7e6055SDimitry Andric   else {
48187a7e6055SDimitry Andric     assert(isa<SExtInst>(Inst) && "Unexpected ext type!");
48197a7e6055SDimitry Andric     LType = ISD::SEXTLOAD;
48207a7e6055SDimitry Andric   }
48217a7e6055SDimitry Andric 
48227a7e6055SDimitry Andric   return TLI->isLoadExtLegal(LType, VT, LoadVT);
482339d628a0SDimitry Andric }
482439d628a0SDimitry Andric 
48257d523365SDimitry Andric /// Move a zext or sext fed by a load into the same basic block as the load,
48267d523365SDimitry Andric /// unless conditions are unfavorable. This allows SelectionDAG to fold the
48277d523365SDimitry Andric /// extend into the load.
482891bc56edSDimitry Andric ///
48297a7e6055SDimitry Andric /// E.g.,
48307a7e6055SDimitry Andric /// \code
48317a7e6055SDimitry Andric /// %ld = load i32* %addr
48327a7e6055SDimitry Andric /// %add = add nuw i32 %ld, 4
48337a7e6055SDimitry Andric /// %zext = zext i32 %add to i64
48347a7e6055SDimitry Andric // \endcode
48357a7e6055SDimitry Andric /// =>
48367a7e6055SDimitry Andric /// \code
48377a7e6055SDimitry Andric /// %ld = load i32* %addr
48387a7e6055SDimitry Andric /// %zext = zext i32 %ld to i64
48397a7e6055SDimitry Andric /// %add = add nuw i64 %zext, 4
48407a7e6055SDimitry Andric /// \encode
48417a7e6055SDimitry Andric /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
48427a7e6055SDimitry Andric /// allow us to match zext(load i32*) to i64.
48437a7e6055SDimitry Andric ///
48447a7e6055SDimitry Andric /// Also, try to promote the computations used to obtain a sign extended
48457a7e6055SDimitry Andric /// value used into memory accesses.
48467a7e6055SDimitry Andric /// E.g.,
48477a7e6055SDimitry Andric /// \code
48487a7e6055SDimitry Andric /// a = add nsw i32 b, 3
48497a7e6055SDimitry Andric /// d = sext i32 a to i64
48507a7e6055SDimitry Andric /// e = getelementptr ..., i64 d
48517a7e6055SDimitry Andric /// \endcode
48527a7e6055SDimitry Andric /// =>
48537a7e6055SDimitry Andric /// \code
48547a7e6055SDimitry Andric /// f = sext i32 b to i64
48557a7e6055SDimitry Andric /// a = add nsw i64 f, 3
48567a7e6055SDimitry Andric /// e = getelementptr ..., i64 a
48577a7e6055SDimitry Andric /// \endcode
48587a7e6055SDimitry Andric ///
48597a7e6055SDimitry Andric /// \p Inst[in/out] the extension may be modified during the process if some
48607a7e6055SDimitry Andric /// promotions apply.
48617a7e6055SDimitry Andric bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
48627a7e6055SDimitry Andric   // ExtLoad formation and address type promotion infrastructure requires TLI to
48637a7e6055SDimitry Andric   // be effective.
4864d88c1a5aSDimitry Andric   if (!TLI)
4865d88c1a5aSDimitry Andric     return false;
4866d88c1a5aSDimitry Andric 
48677a7e6055SDimitry Andric   bool AllowPromotionWithoutCommonHeader = false;
48687a7e6055SDimitry Andric   /// See if it is an interesting sext operations for the address type
48697a7e6055SDimitry Andric   /// promotion before trying to promote it, e.g., the ones with the right
48707a7e6055SDimitry Andric   /// type and used in memory accesses.
48717a7e6055SDimitry Andric   bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
48727a7e6055SDimitry Andric       *Inst, AllowPromotionWithoutCommonHeader);
48737a7e6055SDimitry Andric   TypePromotionTransaction TPT(RemovedInsts);
487439d628a0SDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
487539d628a0SDimitry Andric       TPT.getRestorationPoint();
487639d628a0SDimitry Andric   SmallVector<Instruction *, 1> Exts;
48777a7e6055SDimitry Andric   SmallVector<Instruction *, 2> SpeculativelyMovedExts;
48787a7e6055SDimitry Andric   Exts.push_back(Inst);
48797a7e6055SDimitry Andric 
48807a7e6055SDimitry Andric   bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
48817a7e6055SDimitry Andric 
488291bc56edSDimitry Andric   // Look for a load being extended.
488339d628a0SDimitry Andric   LoadInst *LI = nullptr;
48847a7e6055SDimitry Andric   Instruction *ExtFedByLoad;
488591bc56edSDimitry Andric 
48867a7e6055SDimitry Andric   // Try to promote a chain of computation if it allows to form an extended
48877a7e6055SDimitry Andric   // load.
48887a7e6055SDimitry Andric   if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
48897a7e6055SDimitry Andric     assert(LI && ExtFedByLoad && "Expect a valid load and extension");
489039d628a0SDimitry Andric     TPT.commit();
48917a7e6055SDimitry Andric     // Move the extend into the same block as the load
48927a7e6055SDimitry Andric     ExtFedByLoad->removeFromParent();
48937a7e6055SDimitry Andric     ExtFedByLoad->insertAfter(LI);
4894d88c1a5aSDimitry Andric     // CGP does not check if the zext would be speculatively executed when moved
48957a7e6055SDimitry Andric     // to the same basic block as the load. Preserving its original location
48967a7e6055SDimitry Andric     // would pessimize the debugging experience, as well as negatively impact
48977a7e6055SDimitry Andric     // the quality of sample pgo. We don't want to use "line 0" as that has a
4898d88c1a5aSDimitry Andric     // size cost in the line-table section and logically the zext can be seen as
48997a7e6055SDimitry Andric     // part of the load. Therefore we conservatively reuse the same debug
49007a7e6055SDimitry Andric     // location for the load and the zext.
49017a7e6055SDimitry Andric     ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
490291bc56edSDimitry Andric     ++NumExtsMoved;
49037a7e6055SDimitry Andric     Inst = ExtFedByLoad;
490491bc56edSDimitry Andric     return true;
490591bc56edSDimitry Andric   }
490691bc56edSDimitry Andric 
49077a7e6055SDimitry Andric   // Continue promoting SExts if known as considerable depending on targets.
49087a7e6055SDimitry Andric   if (ATPConsiderable &&
49097a7e6055SDimitry Andric       performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
49107a7e6055SDimitry Andric                                   HasPromoted, TPT, SpeculativelyMovedExts))
49117a7e6055SDimitry Andric     return true;
49127a7e6055SDimitry Andric 
49137a7e6055SDimitry Andric   TPT.rollback(LastKnownGood);
49147a7e6055SDimitry Andric   return false;
49157a7e6055SDimitry Andric }
49167a7e6055SDimitry Andric 
49177a7e6055SDimitry Andric // Perform address type promotion if doing so is profitable.
49187a7e6055SDimitry Andric // If AllowPromotionWithoutCommonHeader == false, we should find other sext
49197a7e6055SDimitry Andric // instructions that sign extended the same initial value. However, if
49207a7e6055SDimitry Andric // AllowPromotionWithoutCommonHeader == true, we expect promoting the
49217a7e6055SDimitry Andric // extension is just profitable.
49227a7e6055SDimitry Andric bool CodeGenPrepare::performAddressTypePromotion(
49237a7e6055SDimitry Andric     Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
49247a7e6055SDimitry Andric     bool HasPromoted, TypePromotionTransaction &TPT,
49257a7e6055SDimitry Andric     SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
49267a7e6055SDimitry Andric   bool Promoted = false;
49277a7e6055SDimitry Andric   SmallPtrSet<Instruction *, 1> UnhandledExts;
49287a7e6055SDimitry Andric   bool AllSeenFirst = true;
49297a7e6055SDimitry Andric   for (auto I : SpeculativelyMovedExts) {
49307a7e6055SDimitry Andric     Value *HeadOfChain = I->getOperand(0);
49317a7e6055SDimitry Andric     DenseMap<Value *, Instruction *>::iterator AlreadySeen =
49327a7e6055SDimitry Andric         SeenChainsForSExt.find(HeadOfChain);
49337a7e6055SDimitry Andric     // If there is an unhandled SExt which has the same header, try to promote
49347a7e6055SDimitry Andric     // it as well.
49357a7e6055SDimitry Andric     if (AlreadySeen != SeenChainsForSExt.end()) {
49367a7e6055SDimitry Andric       if (AlreadySeen->second != nullptr)
49377a7e6055SDimitry Andric         UnhandledExts.insert(AlreadySeen->second);
49387a7e6055SDimitry Andric       AllSeenFirst = false;
49397a7e6055SDimitry Andric     }
49407a7e6055SDimitry Andric   }
49417a7e6055SDimitry Andric 
49427a7e6055SDimitry Andric   if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
49437a7e6055SDimitry Andric                         SpeculativelyMovedExts.size() == 1)) {
49447a7e6055SDimitry Andric     TPT.commit();
49457a7e6055SDimitry Andric     if (HasPromoted)
49467a7e6055SDimitry Andric       Promoted = true;
49477a7e6055SDimitry Andric     for (auto I : SpeculativelyMovedExts) {
49487a7e6055SDimitry Andric       Value *HeadOfChain = I->getOperand(0);
49497a7e6055SDimitry Andric       SeenChainsForSExt[HeadOfChain] = nullptr;
49507a7e6055SDimitry Andric       ValToSExtendedUses[HeadOfChain].push_back(I);
49517a7e6055SDimitry Andric     }
49527a7e6055SDimitry Andric     // Update Inst as promotion happen.
49537a7e6055SDimitry Andric     Inst = SpeculativelyMovedExts.pop_back_val();
49547a7e6055SDimitry Andric   } else {
49557a7e6055SDimitry Andric     // This is the first chain visited from the header, keep the current chain
49567a7e6055SDimitry Andric     // as unhandled. Defer to promote this until we encounter another SExt
49577a7e6055SDimitry Andric     // chain derived from the same header.
49587a7e6055SDimitry Andric     for (auto I : SpeculativelyMovedExts) {
49597a7e6055SDimitry Andric       Value *HeadOfChain = I->getOperand(0);
49607a7e6055SDimitry Andric       SeenChainsForSExt[HeadOfChain] = Inst;
49617a7e6055SDimitry Andric     }
49627a7e6055SDimitry Andric     return false;
49637a7e6055SDimitry Andric   }
49647a7e6055SDimitry Andric 
49657a7e6055SDimitry Andric   if (!AllSeenFirst && !UnhandledExts.empty())
49667a7e6055SDimitry Andric     for (auto VisitedSExt : UnhandledExts) {
49677a7e6055SDimitry Andric       if (RemovedInsts.count(VisitedSExt))
49687a7e6055SDimitry Andric         continue;
49697a7e6055SDimitry Andric       TypePromotionTransaction TPT(RemovedInsts);
49707a7e6055SDimitry Andric       SmallVector<Instruction *, 1> Exts;
49717a7e6055SDimitry Andric       SmallVector<Instruction *, 2> Chains;
49727a7e6055SDimitry Andric       Exts.push_back(VisitedSExt);
49737a7e6055SDimitry Andric       bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
49747a7e6055SDimitry Andric       TPT.commit();
49757a7e6055SDimitry Andric       if (HasPromoted)
49767a7e6055SDimitry Andric         Promoted = true;
49777a7e6055SDimitry Andric       for (auto I : Chains) {
49787a7e6055SDimitry Andric         Value *HeadOfChain = I->getOperand(0);
49797a7e6055SDimitry Andric         // Mark this as handled.
49807a7e6055SDimitry Andric         SeenChainsForSExt[HeadOfChain] = nullptr;
49817a7e6055SDimitry Andric         ValToSExtendedUses[HeadOfChain].push_back(I);
49827a7e6055SDimitry Andric       }
49837a7e6055SDimitry Andric     }
49847a7e6055SDimitry Andric   return Promoted;
49857a7e6055SDimitry Andric }
49867a7e6055SDimitry Andric 
49877d523365SDimitry Andric bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
498891bc56edSDimitry Andric   BasicBlock *DefBB = I->getParent();
498991bc56edSDimitry Andric 
499091bc56edSDimitry Andric   // If the result of a {s|z}ext and its source are both live out, rewrite all
499191bc56edSDimitry Andric   // other uses of the source with result of extension.
499291bc56edSDimitry Andric   Value *Src = I->getOperand(0);
499391bc56edSDimitry Andric   if (Src->hasOneUse())
499491bc56edSDimitry Andric     return false;
499591bc56edSDimitry Andric 
499691bc56edSDimitry Andric   // Only do this xform if truncating is free.
499791bc56edSDimitry Andric   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
499891bc56edSDimitry Andric     return false;
499991bc56edSDimitry Andric 
500091bc56edSDimitry Andric   // Only safe to perform the optimization if the source is also defined in
500191bc56edSDimitry Andric   // this block.
500291bc56edSDimitry Andric   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
500391bc56edSDimitry Andric     return false;
500491bc56edSDimitry Andric 
500591bc56edSDimitry Andric   bool DefIsLiveOut = false;
500691bc56edSDimitry Andric   for (User *U : I->users()) {
500791bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
500891bc56edSDimitry Andric 
500991bc56edSDimitry Andric     // Figure out which BB this ext is used in.
501091bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
501191bc56edSDimitry Andric     if (UserBB == DefBB) continue;
501291bc56edSDimitry Andric     DefIsLiveOut = true;
501391bc56edSDimitry Andric     break;
501491bc56edSDimitry Andric   }
501591bc56edSDimitry Andric   if (!DefIsLiveOut)
501691bc56edSDimitry Andric     return false;
501791bc56edSDimitry Andric 
501891bc56edSDimitry Andric   // Make sure none of the uses are PHI nodes.
501991bc56edSDimitry Andric   for (User *U : Src->users()) {
502091bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
502191bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
502291bc56edSDimitry Andric     if (UserBB == DefBB) continue;
502391bc56edSDimitry Andric     // Be conservative. We don't want this xform to end up introducing
502491bc56edSDimitry Andric     // reloads just before load / store instructions.
502591bc56edSDimitry Andric     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
502691bc56edSDimitry Andric       return false;
502791bc56edSDimitry Andric   }
502891bc56edSDimitry Andric 
502991bc56edSDimitry Andric   // InsertedTruncs - Only insert one trunc in each block once.
503091bc56edSDimitry Andric   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
503191bc56edSDimitry Andric 
503291bc56edSDimitry Andric   bool MadeChange = false;
503391bc56edSDimitry Andric   for (Use &U : Src->uses()) {
503491bc56edSDimitry Andric     Instruction *User = cast<Instruction>(U.getUser());
503591bc56edSDimitry Andric 
503691bc56edSDimitry Andric     // Figure out which BB this ext is used in.
503791bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
503891bc56edSDimitry Andric     if (UserBB == DefBB) continue;
503991bc56edSDimitry Andric 
504091bc56edSDimitry Andric     // Both src and def are live in this block. Rewrite the use.
504191bc56edSDimitry Andric     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
504291bc56edSDimitry Andric 
504391bc56edSDimitry Andric     if (!InsertedTrunc) {
504491bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
50457d523365SDimitry Andric       assert(InsertPt != UserBB->end());
50467d523365SDimitry Andric       InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
50478f0fd8f6SDimitry Andric       InsertedInsts.insert(InsertedTrunc);
504891bc56edSDimitry Andric     }
504991bc56edSDimitry Andric 
505091bc56edSDimitry Andric     // Replace a use of the {s|z}ext source with a use of the result.
505191bc56edSDimitry Andric     U = InsertedTrunc;
505291bc56edSDimitry Andric     ++NumExtUses;
505391bc56edSDimitry Andric     MadeChange = true;
505491bc56edSDimitry Andric   }
505591bc56edSDimitry Andric 
505691bc56edSDimitry Andric   return MadeChange;
505791bc56edSDimitry Andric }
505891bc56edSDimitry Andric 
50597d523365SDimitry Andric // Find loads whose uses only use some of the loaded value's bits.  Add an "and"
50607d523365SDimitry Andric // just after the load if the target can fold this into one extload instruction,
50617d523365SDimitry Andric // with the hope of eliminating some of the other later "and" instructions using
50627d523365SDimitry Andric // the loaded value.  "and"s that are made trivially redundant by the insertion
50637d523365SDimitry Andric // of the new "and" are removed by this function, while others (e.g. those whose
50647d523365SDimitry Andric // path from the load goes through a phi) are left for isel to potentially
50657d523365SDimitry Andric // remove.
50667d523365SDimitry Andric //
50677d523365SDimitry Andric // For example:
50687d523365SDimitry Andric //
50697d523365SDimitry Andric // b0:
50707d523365SDimitry Andric //   x = load i32
50717d523365SDimitry Andric //   ...
50727d523365SDimitry Andric // b1:
50737d523365SDimitry Andric //   y = and x, 0xff
50747d523365SDimitry Andric //   z = use y
50757d523365SDimitry Andric //
50767d523365SDimitry Andric // becomes:
50777d523365SDimitry Andric //
50787d523365SDimitry Andric // b0:
50797d523365SDimitry Andric //   x = load i32
50807d523365SDimitry Andric //   x' = and x, 0xff
50817d523365SDimitry Andric //   ...
50827d523365SDimitry Andric // b1:
50837d523365SDimitry Andric //   z = use x'
50847d523365SDimitry Andric //
50857d523365SDimitry Andric // whereas:
50867d523365SDimitry Andric //
50877d523365SDimitry Andric // b0:
50887d523365SDimitry Andric //   x1 = load i32
50897d523365SDimitry Andric //   ...
50907d523365SDimitry Andric // b1:
50917d523365SDimitry Andric //   x2 = load i32
50927d523365SDimitry Andric //   ...
50937d523365SDimitry Andric // b2:
50947d523365SDimitry Andric //   x = phi x1, x2
50957d523365SDimitry Andric //   y = and x, 0xff
50967d523365SDimitry Andric //
50977d523365SDimitry Andric // becomes (after a call to optimizeLoadExt for each load):
50987d523365SDimitry Andric //
50997d523365SDimitry Andric // b0:
51007d523365SDimitry Andric //   x1 = load i32
51017d523365SDimitry Andric //   x1' = and x1, 0xff
51027d523365SDimitry Andric //   ...
51037d523365SDimitry Andric // b1:
51047d523365SDimitry Andric //   x2 = load i32
51057d523365SDimitry Andric //   x2' = and x2, 0xff
51067d523365SDimitry Andric //   ...
51077d523365SDimitry Andric // b2:
51087d523365SDimitry Andric //   x = phi x1', x2'
51097d523365SDimitry Andric //   y = and x, 0xff
51107d523365SDimitry Andric //
51117d523365SDimitry Andric 
51127d523365SDimitry Andric bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
51137d523365SDimitry Andric 
51147d523365SDimitry Andric   if (!Load->isSimple() ||
51157d523365SDimitry Andric       !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
51167d523365SDimitry Andric     return false;
51177d523365SDimitry Andric 
51187a7e6055SDimitry Andric   // Skip loads we've already transformed.
51197a7e6055SDimitry Andric   if (Load->hasOneUse() &&
51207a7e6055SDimitry Andric       InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
51217d523365SDimitry Andric     return false;
51227d523365SDimitry Andric 
51237d523365SDimitry Andric   // Look at all uses of Load, looking through phis, to determine how many bits
51247d523365SDimitry Andric   // of the loaded value are needed.
51257d523365SDimitry Andric   SmallVector<Instruction *, 8> WorkList;
51267d523365SDimitry Andric   SmallPtrSet<Instruction *, 16> Visited;
51277d523365SDimitry Andric   SmallVector<Instruction *, 8> AndsToMaybeRemove;
51287d523365SDimitry Andric   for (auto *U : Load->users())
51297d523365SDimitry Andric     WorkList.push_back(cast<Instruction>(U));
51307d523365SDimitry Andric 
51317d523365SDimitry Andric   EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
51327d523365SDimitry Andric   unsigned BitWidth = LoadResultVT.getSizeInBits();
51337d523365SDimitry Andric   APInt DemandBits(BitWidth, 0);
51347d523365SDimitry Andric   APInt WidestAndBits(BitWidth, 0);
51357d523365SDimitry Andric 
51367d523365SDimitry Andric   while (!WorkList.empty()) {
51377d523365SDimitry Andric     Instruction *I = WorkList.back();
51387d523365SDimitry Andric     WorkList.pop_back();
51397d523365SDimitry Andric 
51407d523365SDimitry Andric     // Break use-def graph loops.
51417d523365SDimitry Andric     if (!Visited.insert(I).second)
51427d523365SDimitry Andric       continue;
51437d523365SDimitry Andric 
51447d523365SDimitry Andric     // For a PHI node, push all of its users.
51457d523365SDimitry Andric     if (auto *Phi = dyn_cast<PHINode>(I)) {
51467d523365SDimitry Andric       for (auto *U : Phi->users())
51477d523365SDimitry Andric         WorkList.push_back(cast<Instruction>(U));
51487d523365SDimitry Andric       continue;
51497d523365SDimitry Andric     }
51507d523365SDimitry Andric 
51517d523365SDimitry Andric     switch (I->getOpcode()) {
51527d523365SDimitry Andric     case llvm::Instruction::And: {
51537d523365SDimitry Andric       auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
51547d523365SDimitry Andric       if (!AndC)
51557d523365SDimitry Andric         return false;
51567d523365SDimitry Andric       APInt AndBits = AndC->getValue();
51577d523365SDimitry Andric       DemandBits |= AndBits;
51587d523365SDimitry Andric       // Keep track of the widest and mask we see.
51597d523365SDimitry Andric       if (AndBits.ugt(WidestAndBits))
51607d523365SDimitry Andric         WidestAndBits = AndBits;
51617d523365SDimitry Andric       if (AndBits == WidestAndBits && I->getOperand(0) == Load)
51627d523365SDimitry Andric         AndsToMaybeRemove.push_back(I);
51637d523365SDimitry Andric       break;
51647d523365SDimitry Andric     }
51657d523365SDimitry Andric 
51667d523365SDimitry Andric     case llvm::Instruction::Shl: {
51677d523365SDimitry Andric       auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
51687d523365SDimitry Andric       if (!ShlC)
51697d523365SDimitry Andric         return false;
51707d523365SDimitry Andric       uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
51716bc11b14SDimitry Andric       DemandBits.setLowBits(BitWidth - ShiftAmt);
51727d523365SDimitry Andric       break;
51737d523365SDimitry Andric     }
51747d523365SDimitry Andric 
51757d523365SDimitry Andric     case llvm::Instruction::Trunc: {
51767d523365SDimitry Andric       EVT TruncVT = TLI->getValueType(*DL, I->getType());
51777d523365SDimitry Andric       unsigned TruncBitWidth = TruncVT.getSizeInBits();
51786bc11b14SDimitry Andric       DemandBits.setLowBits(TruncBitWidth);
51797d523365SDimitry Andric       break;
51807d523365SDimitry Andric     }
51817d523365SDimitry Andric 
51827d523365SDimitry Andric     default:
51837d523365SDimitry Andric       return false;
51847d523365SDimitry Andric     }
51857d523365SDimitry Andric   }
51867d523365SDimitry Andric 
51877d523365SDimitry Andric   uint32_t ActiveBits = DemandBits.getActiveBits();
51887d523365SDimitry Andric   // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
51897d523365SDimitry Andric   // target even if isLoadExtLegal says an i1 EXTLOAD is valid.  For example,
51907d523365SDimitry Andric   // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
51917d523365SDimitry Andric   // (and (load x) 1) is not matched as a single instruction, rather as a LDR
51927d523365SDimitry Andric   // followed by an AND.
51937d523365SDimitry Andric   // TODO: Look into removing this restriction by fixing backends to either
51947d523365SDimitry Andric   // return false for isLoadExtLegal for i1 or have them select this pattern to
51957d523365SDimitry Andric   // a single instruction.
51967d523365SDimitry Andric   //
51977d523365SDimitry Andric   // Also avoid hoisting if we didn't see any ands with the exact DemandBits
51987d523365SDimitry Andric   // mask, since these are the only ands that will be removed by isel.
51997a7e6055SDimitry Andric   if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
52007d523365SDimitry Andric       WidestAndBits != DemandBits)
52017d523365SDimitry Andric     return false;
52027d523365SDimitry Andric 
52037d523365SDimitry Andric   LLVMContext &Ctx = Load->getType()->getContext();
52047d523365SDimitry Andric   Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
52057d523365SDimitry Andric   EVT TruncVT = TLI->getValueType(*DL, TruncTy);
52067d523365SDimitry Andric 
52077d523365SDimitry Andric   // Reject cases that won't be matched as extloads.
52087d523365SDimitry Andric   if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
52097d523365SDimitry Andric       !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
52107d523365SDimitry Andric     return false;
52117d523365SDimitry Andric 
52127d523365SDimitry Andric   IRBuilder<> Builder(Load->getNextNode());
52137d523365SDimitry Andric   auto *NewAnd = dyn_cast<Instruction>(
52147d523365SDimitry Andric       Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
52157a7e6055SDimitry Andric   // Mark this instruction as "inserted by CGP", so that other
52167a7e6055SDimitry Andric   // optimizations don't touch it.
52177a7e6055SDimitry Andric   InsertedInsts.insert(NewAnd);
52187d523365SDimitry Andric 
52197d523365SDimitry Andric   // Replace all uses of load with new and (except for the use of load in the
52207d523365SDimitry Andric   // new and itself).
52217d523365SDimitry Andric   Load->replaceAllUsesWith(NewAnd);
52227d523365SDimitry Andric   NewAnd->setOperand(0, Load);
52237d523365SDimitry Andric 
52247d523365SDimitry Andric   // Remove any and instructions that are now redundant.
52257d523365SDimitry Andric   for (auto *And : AndsToMaybeRemove)
52267d523365SDimitry Andric     // Check that the and mask is the same as the one we decided to put on the
52277d523365SDimitry Andric     // new and.
52287d523365SDimitry Andric     if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
52297d523365SDimitry Andric       And->replaceAllUsesWith(NewAnd);
52307d523365SDimitry Andric       if (&*CurInstIterator == And)
52317d523365SDimitry Andric         CurInstIterator = std::next(And->getIterator());
52327d523365SDimitry Andric       And->eraseFromParent();
52337d523365SDimitry Andric       ++NumAndUses;
52347d523365SDimitry Andric     }
52357d523365SDimitry Andric 
52367d523365SDimitry Andric   ++NumAndsAdded;
52377d523365SDimitry Andric   return true;
52387d523365SDimitry Andric }
52397d523365SDimitry Andric 
52407d523365SDimitry Andric /// Check if V (an operand of a select instruction) is an expensive instruction
52417d523365SDimitry Andric /// that is only used once.
52427d523365SDimitry Andric static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
52437d523365SDimitry Andric   auto *I = dyn_cast<Instruction>(V);
52447d523365SDimitry Andric   // If it's safe to speculatively execute, then it should not have side
52457d523365SDimitry Andric   // effects; therefore, it's safe to sink and possibly *not* execute.
52467d523365SDimitry Andric   return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
52477d523365SDimitry Andric          TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
52487d523365SDimitry Andric }
52497d523365SDimitry Andric 
52507d523365SDimitry Andric /// Returns true if a SelectInst should be turned into an explicit branch.
52517d523365SDimitry Andric static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
52523ca95b02SDimitry Andric                                                 const TargetLowering *TLI,
52537d523365SDimitry Andric                                                 SelectInst *SI) {
52543ca95b02SDimitry Andric   // If even a predictable select is cheap, then a branch can't be cheaper.
52553ca95b02SDimitry Andric   if (!TLI->isPredictableSelectExpensive())
52563ca95b02SDimitry Andric     return false;
52573ca95b02SDimitry Andric 
525891bc56edSDimitry Andric   // FIXME: This should use the same heuristics as IfConversion to determine
52593ca95b02SDimitry Andric   // whether a select is better represented as a branch.
52603ca95b02SDimitry Andric 
52613ca95b02SDimitry Andric   // If metadata tells us that the select condition is obviously predictable,
52623ca95b02SDimitry Andric   // then we want to replace the select with a branch.
52633ca95b02SDimitry Andric   uint64_t TrueWeight, FalseWeight;
52643ca95b02SDimitry Andric   if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
52653ca95b02SDimitry Andric     uint64_t Max = std::max(TrueWeight, FalseWeight);
52663ca95b02SDimitry Andric     uint64_t Sum = TrueWeight + FalseWeight;
52673ca95b02SDimitry Andric     if (Sum != 0) {
52683ca95b02SDimitry Andric       auto Probability = BranchProbability::getBranchProbability(Max, Sum);
52693ca95b02SDimitry Andric       if (Probability > TLI->getPredictableBranchThreshold())
52703ca95b02SDimitry Andric         return true;
52713ca95b02SDimitry Andric     }
52723ca95b02SDimitry Andric   }
527391bc56edSDimitry Andric 
527491bc56edSDimitry Andric   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
527591bc56edSDimitry Andric 
52767d523365SDimitry Andric   // If a branch is predictable, an out-of-order CPU can avoid blocking on its
52777d523365SDimitry Andric   // comparison condition. If the compare has more than one use, there's
52787d523365SDimitry Andric   // probably another cmov or setcc around, so it's not worth emitting a branch.
52797d523365SDimitry Andric   if (!Cmp || !Cmp->hasOneUse())
528091bc56edSDimitry Andric     return false;
528191bc56edSDimitry Andric 
52827d523365SDimitry Andric   // If either operand of the select is expensive and only needed on one side
52837d523365SDimitry Andric   // of the select, we should form a branch.
52847d523365SDimitry Andric   if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
52857d523365SDimitry Andric       sinkSelectOperand(TTI, SI->getFalseValue()))
52867d523365SDimitry Andric     return true;
52877d523365SDimitry Andric 
52887d523365SDimitry Andric   return false;
528991bc56edSDimitry Andric }
529091bc56edSDimitry Andric 
5291d88c1a5aSDimitry Andric /// If \p isTrue is true, return the true value of \p SI, otherwise return
5292d88c1a5aSDimitry Andric /// false value of \p SI. If the true/false value of \p SI is defined by any
5293d88c1a5aSDimitry Andric /// select instructions in \p Selects, look through the defining select
5294d88c1a5aSDimitry Andric /// instruction until the true/false value is not defined in \p Selects.
5295d88c1a5aSDimitry Andric static Value *getTrueOrFalseValue(
5296d88c1a5aSDimitry Andric     SelectInst *SI, bool isTrue,
5297d88c1a5aSDimitry Andric     const SmallPtrSet<const Instruction *, 2> &Selects) {
5298d88c1a5aSDimitry Andric   Value *V;
5299d88c1a5aSDimitry Andric 
5300d88c1a5aSDimitry Andric   for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5301d88c1a5aSDimitry Andric        DefSI = dyn_cast<SelectInst>(V)) {
5302d88c1a5aSDimitry Andric     assert(DefSI->getCondition() == SI->getCondition() &&
5303d88c1a5aSDimitry Andric            "The condition of DefSI does not match with SI");
5304d88c1a5aSDimitry Andric     V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5305d88c1a5aSDimitry Andric   }
5306d88c1a5aSDimitry Andric   return V;
5307d88c1a5aSDimitry Andric }
530891bc56edSDimitry Andric 
530991bc56edSDimitry Andric /// If we have a SelectInst that will likely profit from branch prediction,
531091bc56edSDimitry Andric /// turn it into a branch.
53117d523365SDimitry Andric bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
5312d88c1a5aSDimitry Andric   // Find all consecutive select instructions that share the same condition.
5313d88c1a5aSDimitry Andric   SmallVector<SelectInst *, 2> ASI;
5314d88c1a5aSDimitry Andric   ASI.push_back(SI);
5315d88c1a5aSDimitry Andric   for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5316d88c1a5aSDimitry Andric        It != SI->getParent()->end(); ++It) {
5317d88c1a5aSDimitry Andric     SelectInst *I = dyn_cast<SelectInst>(&*It);
5318d88c1a5aSDimitry Andric     if (I && SI->getCondition() == I->getCondition()) {
5319d88c1a5aSDimitry Andric       ASI.push_back(I);
5320d88c1a5aSDimitry Andric     } else {
5321d88c1a5aSDimitry Andric       break;
5322d88c1a5aSDimitry Andric     }
5323d88c1a5aSDimitry Andric   }
5324d88c1a5aSDimitry Andric 
5325d88c1a5aSDimitry Andric   SelectInst *LastSI = ASI.back();
5326d88c1a5aSDimitry Andric   // Increment the current iterator to skip all the rest of select instructions
5327d88c1a5aSDimitry Andric   // because they will be either "not lowered" or "all lowered" to branch.
5328d88c1a5aSDimitry Andric   CurInstIterator = std::next(LastSI->getIterator());
5329d88c1a5aSDimitry Andric 
533091bc56edSDimitry Andric   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
533191bc56edSDimitry Andric 
533291bc56edSDimitry Andric   // Can we convert the 'select' to CF ?
53333ca95b02SDimitry Andric   if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
53343ca95b02SDimitry Andric       SI->getMetadata(LLVMContext::MD_unpredictable))
533591bc56edSDimitry Andric     return false;
533691bc56edSDimitry Andric 
533791bc56edSDimitry Andric   TargetLowering::SelectSupportKind SelectKind;
533891bc56edSDimitry Andric   if (VectorCond)
533991bc56edSDimitry Andric     SelectKind = TargetLowering::VectorMaskSelect;
534091bc56edSDimitry Andric   else if (SI->getType()->isVectorTy())
534191bc56edSDimitry Andric     SelectKind = TargetLowering::ScalarCondVectorVal;
534291bc56edSDimitry Andric   else
534391bc56edSDimitry Andric     SelectKind = TargetLowering::ScalarValSelect;
534491bc56edSDimitry Andric 
53453ca95b02SDimitry Andric   if (TLI->isSelectSupported(SelectKind) &&
53463ca95b02SDimitry Andric       !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
534791bc56edSDimitry Andric     return false;
534891bc56edSDimitry Andric 
534991bc56edSDimitry Andric   ModifiedDT = true;
535091bc56edSDimitry Andric 
53517d523365SDimitry Andric   // Transform a sequence like this:
53527d523365SDimitry Andric   //    start:
53537d523365SDimitry Andric   //       %cmp = cmp uge i32 %a, %b
53547d523365SDimitry Andric   //       %sel = select i1 %cmp, i32 %c, i32 %d
53557d523365SDimitry Andric   //
53567d523365SDimitry Andric   // Into:
53577d523365SDimitry Andric   //    start:
53587d523365SDimitry Andric   //       %cmp = cmp uge i32 %a, %b
53597d523365SDimitry Andric   //       br i1 %cmp, label %select.true, label %select.false
53607d523365SDimitry Andric   //    select.true:
53617d523365SDimitry Andric   //       br label %select.end
53627d523365SDimitry Andric   //    select.false:
53637d523365SDimitry Andric   //       br label %select.end
53647d523365SDimitry Andric   //    select.end:
53657d523365SDimitry Andric   //       %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
53667d523365SDimitry Andric   //
53677d523365SDimitry Andric   // In addition, we may sink instructions that produce %c or %d from
53687d523365SDimitry Andric   // the entry block into the destination(s) of the new branch.
53697d523365SDimitry Andric   // If the true or false blocks do not contain a sunken instruction, that
53707d523365SDimitry Andric   // block and its branch may be optimized away. In that case, one side of the
53717d523365SDimitry Andric   // first branch will point directly to select.end, and the corresponding PHI
53727d523365SDimitry Andric   // predecessor block will be the start block.
53737d523365SDimitry Andric 
537491bc56edSDimitry Andric   // First, we split the block containing the select into 2 blocks.
537591bc56edSDimitry Andric   BasicBlock *StartBlock = SI->getParent();
5376d88c1a5aSDimitry Andric   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
53777d523365SDimitry Andric   BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
537891bc56edSDimitry Andric 
53797d523365SDimitry Andric   // Delete the unconditional branch that was just created by the split.
538091bc56edSDimitry Andric   StartBlock->getTerminator()->eraseFromParent();
53817d523365SDimitry Andric 
53827d523365SDimitry Andric   // These are the new basic blocks for the conditional branch.
53837d523365SDimitry Andric   // At least one will become an actual new basic block.
53847d523365SDimitry Andric   BasicBlock *TrueBlock = nullptr;
53857d523365SDimitry Andric   BasicBlock *FalseBlock = nullptr;
5386d88c1a5aSDimitry Andric   BranchInst *TrueBranch = nullptr;
5387d88c1a5aSDimitry Andric   BranchInst *FalseBranch = nullptr;
53887d523365SDimitry Andric 
53897d523365SDimitry Andric   // Sink expensive instructions into the conditional blocks to avoid executing
53907d523365SDimitry Andric   // them speculatively.
5391d88c1a5aSDimitry Andric   for (SelectInst *SI : ASI) {
53927d523365SDimitry Andric     if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5393d88c1a5aSDimitry Andric       if (TrueBlock == nullptr) {
53947d523365SDimitry Andric         TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
53957d523365SDimitry Andric                                        EndBlock->getParent(), EndBlock);
5396d88c1a5aSDimitry Andric         TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5397d88c1a5aSDimitry Andric       }
53987d523365SDimitry Andric       auto *TrueInst = cast<Instruction>(SI->getTrueValue());
53997d523365SDimitry Andric       TrueInst->moveBefore(TrueBranch);
54007d523365SDimitry Andric     }
54017d523365SDimitry Andric     if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5402d88c1a5aSDimitry Andric       if (FalseBlock == nullptr) {
54037d523365SDimitry Andric         FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
54047d523365SDimitry Andric                                         EndBlock->getParent(), EndBlock);
5405d88c1a5aSDimitry Andric         FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5406d88c1a5aSDimitry Andric       }
54077d523365SDimitry Andric       auto *FalseInst = cast<Instruction>(SI->getFalseValue());
54087d523365SDimitry Andric       FalseInst->moveBefore(FalseBranch);
54097d523365SDimitry Andric     }
5410d88c1a5aSDimitry Andric   }
54117d523365SDimitry Andric 
54127d523365SDimitry Andric   // If there was nothing to sink, then arbitrarily choose the 'false' side
54137d523365SDimitry Andric   // for a new input value to the PHI.
54147d523365SDimitry Andric   if (TrueBlock == FalseBlock) {
54157d523365SDimitry Andric     assert(TrueBlock == nullptr &&
54167d523365SDimitry Andric            "Unexpected basic block transform while optimizing select");
54177d523365SDimitry Andric 
54187d523365SDimitry Andric     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
54197d523365SDimitry Andric                                     EndBlock->getParent(), EndBlock);
54207d523365SDimitry Andric     BranchInst::Create(EndBlock, FalseBlock);
54217d523365SDimitry Andric   }
542291bc56edSDimitry Andric 
542391bc56edSDimitry Andric   // Insert the real conditional branch based on the original condition.
54247d523365SDimitry Andric   // If we did not create a new block for one of the 'true' or 'false' paths
54257d523365SDimitry Andric   // of the condition, it means that side of the branch goes to the end block
54267d523365SDimitry Andric   // directly and the path originates from the start block from the point of
54277d523365SDimitry Andric   // view of the new PHI.
5428d88c1a5aSDimitry Andric   BasicBlock *TT, *FT;
54297d523365SDimitry Andric   if (TrueBlock == nullptr) {
5430d88c1a5aSDimitry Andric     TT = EndBlock;
5431d88c1a5aSDimitry Andric     FT = FalseBlock;
54327d523365SDimitry Andric     TrueBlock = StartBlock;
54337d523365SDimitry Andric   } else if (FalseBlock == nullptr) {
5434d88c1a5aSDimitry Andric     TT = TrueBlock;
5435d88c1a5aSDimitry Andric     FT = EndBlock;
54367d523365SDimitry Andric     FalseBlock = StartBlock;
54377d523365SDimitry Andric   } else {
5438d88c1a5aSDimitry Andric     TT = TrueBlock;
5439d88c1a5aSDimitry Andric     FT = FalseBlock;
54407d523365SDimitry Andric   }
5441d88c1a5aSDimitry Andric   IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
544291bc56edSDimitry Andric 
5443d88c1a5aSDimitry Andric   SmallPtrSet<const Instruction *, 2> INS;
5444d88c1a5aSDimitry Andric   INS.insert(ASI.begin(), ASI.end());
5445d88c1a5aSDimitry Andric   // Use reverse iterator because later select may use the value of the
5446d88c1a5aSDimitry Andric   // earlier select, and we need to propagate value through earlier select
5447d88c1a5aSDimitry Andric   // to get the PHI operand.
5448d88c1a5aSDimitry Andric   for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5449d88c1a5aSDimitry Andric     SelectInst *SI = *It;
545091bc56edSDimitry Andric     // The select itself is replaced with a PHI Node.
54517d523365SDimitry Andric     PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
545291bc56edSDimitry Andric     PN->takeName(SI);
5453d88c1a5aSDimitry Andric     PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5454d88c1a5aSDimitry Andric     PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
54557d523365SDimitry Andric 
545691bc56edSDimitry Andric     SI->replaceAllUsesWith(PN);
545791bc56edSDimitry Andric     SI->eraseFromParent();
5458d88c1a5aSDimitry Andric     INS.erase(SI);
5459d88c1a5aSDimitry Andric     ++NumSelectsExpanded;
5460d88c1a5aSDimitry Andric   }
546191bc56edSDimitry Andric 
546291bc56edSDimitry Andric   // Instruct OptimizeBlock to skip to the next block.
546391bc56edSDimitry Andric   CurInstIterator = StartBlock->end();
546491bc56edSDimitry Andric   return true;
546591bc56edSDimitry Andric }
546691bc56edSDimitry Andric 
546791bc56edSDimitry Andric static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
546891bc56edSDimitry Andric   SmallVector<int, 16> Mask(SVI->getShuffleMask());
546991bc56edSDimitry Andric   int SplatElem = -1;
547091bc56edSDimitry Andric   for (unsigned i = 0; i < Mask.size(); ++i) {
547191bc56edSDimitry Andric     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
547291bc56edSDimitry Andric       return false;
547391bc56edSDimitry Andric     SplatElem = Mask[i];
547491bc56edSDimitry Andric   }
547591bc56edSDimitry Andric 
547691bc56edSDimitry Andric   return true;
547791bc56edSDimitry Andric }
547891bc56edSDimitry Andric 
547991bc56edSDimitry Andric /// Some targets have expensive vector shifts if the lanes aren't all the same
548091bc56edSDimitry Andric /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
548191bc56edSDimitry Andric /// it's often worth sinking a shufflevector splat down to its use so that
548291bc56edSDimitry Andric /// codegen can spot all lanes are identical.
54837d523365SDimitry Andric bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
548491bc56edSDimitry Andric   BasicBlock *DefBB = SVI->getParent();
548591bc56edSDimitry Andric 
548691bc56edSDimitry Andric   // Only do this xform if variable vector shifts are particularly expensive.
548791bc56edSDimitry Andric   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
548891bc56edSDimitry Andric     return false;
548991bc56edSDimitry Andric 
549091bc56edSDimitry Andric   // We only expect better codegen by sinking a shuffle if we can recognise a
549191bc56edSDimitry Andric   // constant splat.
549291bc56edSDimitry Andric   if (!isBroadcastShuffle(SVI))
549391bc56edSDimitry Andric     return false;
549491bc56edSDimitry Andric 
549591bc56edSDimitry Andric   // InsertedShuffles - Only insert a shuffle in each block once.
549691bc56edSDimitry Andric   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
549791bc56edSDimitry Andric 
549891bc56edSDimitry Andric   bool MadeChange = false;
549991bc56edSDimitry Andric   for (User *U : SVI->users()) {
550091bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
550191bc56edSDimitry Andric 
550291bc56edSDimitry Andric     // Figure out which BB this ext is used in.
550391bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
550491bc56edSDimitry Andric     if (UserBB == DefBB) continue;
550591bc56edSDimitry Andric 
550691bc56edSDimitry Andric     // For now only apply this when the splat is used by a shift instruction.
550791bc56edSDimitry Andric     if (!UI->isShift()) continue;
550891bc56edSDimitry Andric 
550991bc56edSDimitry Andric     // Everything checks out, sink the shuffle if the user's block doesn't
551091bc56edSDimitry Andric     // already have a copy.
551191bc56edSDimitry Andric     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
551291bc56edSDimitry Andric 
551391bc56edSDimitry Andric     if (!InsertedShuffle) {
551491bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
55157d523365SDimitry Andric       assert(InsertPt != UserBB->end());
55167d523365SDimitry Andric       InsertedShuffle =
55177d523365SDimitry Andric           new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
55187d523365SDimitry Andric                                 SVI->getOperand(2), "", &*InsertPt);
551991bc56edSDimitry Andric     }
552091bc56edSDimitry Andric 
552191bc56edSDimitry Andric     UI->replaceUsesOfWith(SVI, InsertedShuffle);
552291bc56edSDimitry Andric     MadeChange = true;
552391bc56edSDimitry Andric   }
552491bc56edSDimitry Andric 
552591bc56edSDimitry Andric   // If we removed all uses, nuke the shuffle.
552691bc56edSDimitry Andric   if (SVI->use_empty()) {
552791bc56edSDimitry Andric     SVI->eraseFromParent();
552891bc56edSDimitry Andric     MadeChange = true;
552991bc56edSDimitry Andric   }
553091bc56edSDimitry Andric 
553191bc56edSDimitry Andric   return MadeChange;
553291bc56edSDimitry Andric }
553391bc56edSDimitry Andric 
55347d523365SDimitry Andric bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
55357d523365SDimitry Andric   if (!TLI || !DL)
55367d523365SDimitry Andric     return false;
55377d523365SDimitry Andric 
55387d523365SDimitry Andric   Value *Cond = SI->getCondition();
55397d523365SDimitry Andric   Type *OldType = Cond->getType();
55407d523365SDimitry Andric   LLVMContext &Context = Cond->getContext();
55417d523365SDimitry Andric   MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
55427d523365SDimitry Andric   unsigned RegWidth = RegType.getSizeInBits();
55437d523365SDimitry Andric 
55447d523365SDimitry Andric   if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
55457d523365SDimitry Andric     return false;
55467d523365SDimitry Andric 
55477d523365SDimitry Andric   // If the register width is greater than the type width, expand the condition
55487d523365SDimitry Andric   // of the switch instruction and each case constant to the width of the
55497d523365SDimitry Andric   // register. By widening the type of the switch condition, subsequent
55507d523365SDimitry Andric   // comparisons (for case comparisons) will not need to be extended to the
55517d523365SDimitry Andric   // preferred register width, so we will potentially eliminate N-1 extends,
55527d523365SDimitry Andric   // where N is the number of cases in the switch.
55537d523365SDimitry Andric   auto *NewType = Type::getIntNTy(Context, RegWidth);
55547d523365SDimitry Andric 
55557d523365SDimitry Andric   // Zero-extend the switch condition and case constants unless the switch
55567d523365SDimitry Andric   // condition is a function argument that is already being sign-extended.
55577d523365SDimitry Andric   // In that case, we can avoid an unnecessary mask/extension by sign-extending
55587d523365SDimitry Andric   // everything instead.
55597d523365SDimitry Andric   Instruction::CastOps ExtType = Instruction::ZExt;
55607d523365SDimitry Andric   if (auto *Arg = dyn_cast<Argument>(Cond))
55617d523365SDimitry Andric     if (Arg->hasSExtAttr())
55627d523365SDimitry Andric       ExtType = Instruction::SExt;
55637d523365SDimitry Andric 
55647d523365SDimitry Andric   auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
55657d523365SDimitry Andric   ExtInst->insertBefore(SI);
55667d523365SDimitry Andric   SI->setCondition(ExtInst);
55677a7e6055SDimitry Andric   for (auto Case : SI->cases()) {
55687d523365SDimitry Andric     APInt NarrowConst = Case.getCaseValue()->getValue();
55697d523365SDimitry Andric     APInt WideConst = (ExtType == Instruction::ZExt) ?
55707d523365SDimitry Andric                       NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
55717d523365SDimitry Andric     Case.setValue(ConstantInt::get(Context, WideConst));
55727d523365SDimitry Andric   }
55737d523365SDimitry Andric 
55747d523365SDimitry Andric   return true;
55757d523365SDimitry Andric }
55767d523365SDimitry Andric 
5577f9448bf3SDimitry Andric 
557839d628a0SDimitry Andric namespace {
557939d628a0SDimitry Andric /// \brief Helper class to promote a scalar operation to a vector one.
558039d628a0SDimitry Andric /// This class is used to move downward extractelement transition.
558139d628a0SDimitry Andric /// E.g.,
558239d628a0SDimitry Andric /// a = vector_op <2 x i32>
558339d628a0SDimitry Andric /// b = extractelement <2 x i32> a, i32 0
558439d628a0SDimitry Andric /// c = scalar_op b
558539d628a0SDimitry Andric /// store c
558639d628a0SDimitry Andric ///
558739d628a0SDimitry Andric /// =>
558839d628a0SDimitry Andric /// a = vector_op <2 x i32>
558939d628a0SDimitry Andric /// c = vector_op a (equivalent to scalar_op on the related lane)
559039d628a0SDimitry Andric /// * d = extractelement <2 x i32> c, i32 0
559139d628a0SDimitry Andric /// * store d
559239d628a0SDimitry Andric /// Assuming both extractelement and store can be combine, we get rid of the
559339d628a0SDimitry Andric /// transition.
559439d628a0SDimitry Andric class VectorPromoteHelper {
5595875ed548SDimitry Andric   /// DataLayout associated with the current module.
5596875ed548SDimitry Andric   const DataLayout &DL;
5597875ed548SDimitry Andric 
559839d628a0SDimitry Andric   /// Used to perform some checks on the legality of vector operations.
559939d628a0SDimitry Andric   const TargetLowering &TLI;
560039d628a0SDimitry Andric 
560139d628a0SDimitry Andric   /// Used to estimated the cost of the promoted chain.
560239d628a0SDimitry Andric   const TargetTransformInfo &TTI;
560339d628a0SDimitry Andric 
560439d628a0SDimitry Andric   /// The transition being moved downwards.
560539d628a0SDimitry Andric   Instruction *Transition;
560639d628a0SDimitry Andric   /// The sequence of instructions to be promoted.
560739d628a0SDimitry Andric   SmallVector<Instruction *, 4> InstsToBePromoted;
560839d628a0SDimitry Andric   /// Cost of combining a store and an extract.
560939d628a0SDimitry Andric   unsigned StoreExtractCombineCost;
561039d628a0SDimitry Andric   /// Instruction that will be combined with the transition.
561139d628a0SDimitry Andric   Instruction *CombineInst;
561239d628a0SDimitry Andric 
561339d628a0SDimitry Andric   /// \brief The instruction that represents the current end of the transition.
561439d628a0SDimitry Andric   /// Since we are faking the promotion until we reach the end of the chain
561539d628a0SDimitry Andric   /// of computation, we need a way to get the current end of the transition.
561639d628a0SDimitry Andric   Instruction *getEndOfTransition() const {
561739d628a0SDimitry Andric     if (InstsToBePromoted.empty())
561839d628a0SDimitry Andric       return Transition;
561939d628a0SDimitry Andric     return InstsToBePromoted.back();
562039d628a0SDimitry Andric   }
562139d628a0SDimitry Andric 
562239d628a0SDimitry Andric   /// \brief Return the index of the original value in the transition.
562339d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
562439d628a0SDimitry Andric   /// c, is at index 0.
562539d628a0SDimitry Andric   unsigned getTransitionOriginalValueIdx() const {
562639d628a0SDimitry Andric     assert(isa<ExtractElementInst>(Transition) &&
562739d628a0SDimitry Andric            "Other kind of transitions are not supported yet");
562839d628a0SDimitry Andric     return 0;
562939d628a0SDimitry Andric   }
563039d628a0SDimitry Andric 
563139d628a0SDimitry Andric   /// \brief Return the index of the index in the transition.
563239d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
563339d628a0SDimitry Andric   /// is at index 1.
563439d628a0SDimitry Andric   unsigned getTransitionIdx() const {
563539d628a0SDimitry Andric     assert(isa<ExtractElementInst>(Transition) &&
563639d628a0SDimitry Andric            "Other kind of transitions are not supported yet");
563739d628a0SDimitry Andric     return 1;
563839d628a0SDimitry Andric   }
563939d628a0SDimitry Andric 
564039d628a0SDimitry Andric   /// \brief Get the type of the transition.
564139d628a0SDimitry Andric   /// This is the type of the original value.
564239d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
564339d628a0SDimitry Andric   /// transition is <2 x i32>.
564439d628a0SDimitry Andric   Type *getTransitionType() const {
564539d628a0SDimitry Andric     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
564639d628a0SDimitry Andric   }
564739d628a0SDimitry Andric 
564839d628a0SDimitry Andric   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
564939d628a0SDimitry Andric   /// I.e., we have the following sequence:
565039d628a0SDimitry Andric   /// Def = Transition <ty1> a to <ty2>
565139d628a0SDimitry Andric   /// b = ToBePromoted <ty2> Def, ...
565239d628a0SDimitry Andric   /// =>
565339d628a0SDimitry Andric   /// b = ToBePromoted <ty1> a, ...
565439d628a0SDimitry Andric   /// Def = Transition <ty1> ToBePromoted to <ty2>
565539d628a0SDimitry Andric   void promoteImpl(Instruction *ToBePromoted);
565639d628a0SDimitry Andric 
565739d628a0SDimitry Andric   /// \brief Check whether or not it is profitable to promote all the
565839d628a0SDimitry Andric   /// instructions enqueued to be promoted.
565939d628a0SDimitry Andric   bool isProfitableToPromote() {
566039d628a0SDimitry Andric     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
566139d628a0SDimitry Andric     unsigned Index = isa<ConstantInt>(ValIdx)
566239d628a0SDimitry Andric                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
566339d628a0SDimitry Andric                          : -1;
566439d628a0SDimitry Andric     Type *PromotedType = getTransitionType();
566539d628a0SDimitry Andric 
566639d628a0SDimitry Andric     StoreInst *ST = cast<StoreInst>(CombineInst);
566739d628a0SDimitry Andric     unsigned AS = ST->getPointerAddressSpace();
566839d628a0SDimitry Andric     unsigned Align = ST->getAlignment();
566939d628a0SDimitry Andric     // Check if this store is supported.
567039d628a0SDimitry Andric     if (!TLI.allowsMisalignedMemoryAccesses(
5671875ed548SDimitry Andric             TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5672875ed548SDimitry Andric             Align)) {
567339d628a0SDimitry Andric       // If this is not supported, there is no way we can combine
567439d628a0SDimitry Andric       // the extract with the store.
567539d628a0SDimitry Andric       return false;
567639d628a0SDimitry Andric     }
567739d628a0SDimitry Andric 
567839d628a0SDimitry Andric     // The scalar chain of computation has to pay for the transition
567939d628a0SDimitry Andric     // scalar to vector.
568039d628a0SDimitry Andric     // The vector chain has to account for the combining cost.
568139d628a0SDimitry Andric     uint64_t ScalarCost =
568239d628a0SDimitry Andric         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
568339d628a0SDimitry Andric     uint64_t VectorCost = StoreExtractCombineCost;
568439d628a0SDimitry Andric     for (const auto &Inst : InstsToBePromoted) {
568539d628a0SDimitry Andric       // Compute the cost.
568639d628a0SDimitry Andric       // By construction, all instructions being promoted are arithmetic ones.
568739d628a0SDimitry Andric       // Moreover, one argument is a constant that can be viewed as a splat
568839d628a0SDimitry Andric       // constant.
568939d628a0SDimitry Andric       Value *Arg0 = Inst->getOperand(0);
569039d628a0SDimitry Andric       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
569139d628a0SDimitry Andric                             isa<ConstantFP>(Arg0);
569239d628a0SDimitry Andric       TargetTransformInfo::OperandValueKind Arg0OVK =
569339d628a0SDimitry Andric           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
569439d628a0SDimitry Andric                          : TargetTransformInfo::OK_AnyValue;
569539d628a0SDimitry Andric       TargetTransformInfo::OperandValueKind Arg1OVK =
569639d628a0SDimitry Andric           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
569739d628a0SDimitry Andric                           : TargetTransformInfo::OK_AnyValue;
569839d628a0SDimitry Andric       ScalarCost += TTI.getArithmeticInstrCost(
569939d628a0SDimitry Andric           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
570039d628a0SDimitry Andric       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
570139d628a0SDimitry Andric                                                Arg0OVK, Arg1OVK);
570239d628a0SDimitry Andric     }
570339d628a0SDimitry Andric     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
570439d628a0SDimitry Andric                  << ScalarCost << "\nVector: " << VectorCost << '\n');
570539d628a0SDimitry Andric     return ScalarCost > VectorCost;
570639d628a0SDimitry Andric   }
570739d628a0SDimitry Andric 
570839d628a0SDimitry Andric   /// \brief Generate a constant vector with \p Val with the same
570939d628a0SDimitry Andric   /// number of elements as the transition.
571039d628a0SDimitry Andric   /// \p UseSplat defines whether or not \p Val should be replicated
57117d523365SDimitry Andric   /// across the whole vector.
571239d628a0SDimitry Andric   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
571339d628a0SDimitry Andric   /// otherwise we generate a vector with as many undef as possible:
571439d628a0SDimitry Andric   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
571539d628a0SDimitry Andric   /// used at the index of the extract.
571639d628a0SDimitry Andric   Value *getConstantVector(Constant *Val, bool UseSplat) const {
571739d628a0SDimitry Andric     unsigned ExtractIdx = UINT_MAX;
571839d628a0SDimitry Andric     if (!UseSplat) {
571939d628a0SDimitry Andric       // If we cannot determine where the constant must be, we have to
572039d628a0SDimitry Andric       // use a splat constant.
572139d628a0SDimitry Andric       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
572239d628a0SDimitry Andric       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
572339d628a0SDimitry Andric         ExtractIdx = CstVal->getSExtValue();
572439d628a0SDimitry Andric       else
572539d628a0SDimitry Andric         UseSplat = true;
572639d628a0SDimitry Andric     }
572739d628a0SDimitry Andric 
572839d628a0SDimitry Andric     unsigned End = getTransitionType()->getVectorNumElements();
572939d628a0SDimitry Andric     if (UseSplat)
573039d628a0SDimitry Andric       return ConstantVector::getSplat(End, Val);
573139d628a0SDimitry Andric 
573239d628a0SDimitry Andric     SmallVector<Constant *, 4> ConstVec;
573339d628a0SDimitry Andric     UndefValue *UndefVal = UndefValue::get(Val->getType());
573439d628a0SDimitry Andric     for (unsigned Idx = 0; Idx != End; ++Idx) {
573539d628a0SDimitry Andric       if (Idx == ExtractIdx)
573639d628a0SDimitry Andric         ConstVec.push_back(Val);
573739d628a0SDimitry Andric       else
573839d628a0SDimitry Andric         ConstVec.push_back(UndefVal);
573939d628a0SDimitry Andric     }
574039d628a0SDimitry Andric     return ConstantVector::get(ConstVec);
574139d628a0SDimitry Andric   }
574239d628a0SDimitry Andric 
574339d628a0SDimitry Andric   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
574439d628a0SDimitry Andric   /// in \p Use can trigger undefined behavior.
574539d628a0SDimitry Andric   static bool canCauseUndefinedBehavior(const Instruction *Use,
574639d628a0SDimitry Andric                                         unsigned OperandIdx) {
574739d628a0SDimitry Andric     // This is not safe to introduce undef when the operand is on
574839d628a0SDimitry Andric     // the right hand side of a division-like instruction.
574939d628a0SDimitry Andric     if (OperandIdx != 1)
575039d628a0SDimitry Andric       return false;
575139d628a0SDimitry Andric     switch (Use->getOpcode()) {
575239d628a0SDimitry Andric     default:
575339d628a0SDimitry Andric       return false;
575439d628a0SDimitry Andric     case Instruction::SDiv:
575539d628a0SDimitry Andric     case Instruction::UDiv:
575639d628a0SDimitry Andric     case Instruction::SRem:
575739d628a0SDimitry Andric     case Instruction::URem:
575839d628a0SDimitry Andric       return true;
575939d628a0SDimitry Andric     case Instruction::FDiv:
576039d628a0SDimitry Andric     case Instruction::FRem:
576139d628a0SDimitry Andric       return !Use->hasNoNaNs();
576239d628a0SDimitry Andric     }
576339d628a0SDimitry Andric     llvm_unreachable(nullptr);
576439d628a0SDimitry Andric   }
576539d628a0SDimitry Andric 
576639d628a0SDimitry Andric public:
5767875ed548SDimitry Andric   VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5768875ed548SDimitry Andric                       const TargetTransformInfo &TTI, Instruction *Transition,
5769875ed548SDimitry Andric                       unsigned CombineCost)
5770875ed548SDimitry Andric       : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
577139d628a0SDimitry Andric         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
577239d628a0SDimitry Andric     assert(Transition && "Do not know how to promote null");
577339d628a0SDimitry Andric   }
577439d628a0SDimitry Andric 
577539d628a0SDimitry Andric   /// \brief Check if we can promote \p ToBePromoted to \p Type.
577639d628a0SDimitry Andric   bool canPromote(const Instruction *ToBePromoted) const {
577739d628a0SDimitry Andric     // We could support CastInst too.
577839d628a0SDimitry Andric     return isa<BinaryOperator>(ToBePromoted);
577939d628a0SDimitry Andric   }
578039d628a0SDimitry Andric 
578139d628a0SDimitry Andric   /// \brief Check if it is profitable to promote \p ToBePromoted
578239d628a0SDimitry Andric   /// by moving downward the transition through.
578339d628a0SDimitry Andric   bool shouldPromote(const Instruction *ToBePromoted) const {
578439d628a0SDimitry Andric     // Promote only if all the operands can be statically expanded.
578539d628a0SDimitry Andric     // Indeed, we do not want to introduce any new kind of transitions.
578639d628a0SDimitry Andric     for (const Use &U : ToBePromoted->operands()) {
578739d628a0SDimitry Andric       const Value *Val = U.get();
578839d628a0SDimitry Andric       if (Val == getEndOfTransition()) {
578939d628a0SDimitry Andric         // If the use is a division and the transition is on the rhs,
579039d628a0SDimitry Andric         // we cannot promote the operation, otherwise we may create a
579139d628a0SDimitry Andric         // division by zero.
579239d628a0SDimitry Andric         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
579339d628a0SDimitry Andric           return false;
579439d628a0SDimitry Andric         continue;
579539d628a0SDimitry Andric       }
579639d628a0SDimitry Andric       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
579739d628a0SDimitry Andric           !isa<ConstantFP>(Val))
579839d628a0SDimitry Andric         return false;
579939d628a0SDimitry Andric     }
580039d628a0SDimitry Andric     // Check that the resulting operation is legal.
580139d628a0SDimitry Andric     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
580239d628a0SDimitry Andric     if (!ISDOpcode)
580339d628a0SDimitry Andric       return false;
580439d628a0SDimitry Andric     return StressStoreExtract ||
580539d628a0SDimitry Andric            TLI.isOperationLegalOrCustom(
5806875ed548SDimitry Andric                ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
580739d628a0SDimitry Andric   }
580839d628a0SDimitry Andric 
580939d628a0SDimitry Andric   /// \brief Check whether or not \p Use can be combined
581039d628a0SDimitry Andric   /// with the transition.
581139d628a0SDimitry Andric   /// I.e., is it possible to do Use(Transition) => AnotherUse?
581239d628a0SDimitry Andric   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
581339d628a0SDimitry Andric 
581439d628a0SDimitry Andric   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
581539d628a0SDimitry Andric   void enqueueForPromotion(Instruction *ToBePromoted) {
581639d628a0SDimitry Andric     InstsToBePromoted.push_back(ToBePromoted);
581739d628a0SDimitry Andric   }
581839d628a0SDimitry Andric 
581939d628a0SDimitry Andric   /// \brief Set the instruction that will be combined with the transition.
582039d628a0SDimitry Andric   void recordCombineInstruction(Instruction *ToBeCombined) {
582139d628a0SDimitry Andric     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
582239d628a0SDimitry Andric     CombineInst = ToBeCombined;
582339d628a0SDimitry Andric   }
582439d628a0SDimitry Andric 
582539d628a0SDimitry Andric   /// \brief Promote all the instructions enqueued for promotion if it is
582639d628a0SDimitry Andric   /// is profitable.
582739d628a0SDimitry Andric   /// \return True if the promotion happened, false otherwise.
582839d628a0SDimitry Andric   bool promote() {
582939d628a0SDimitry Andric     // Check if there is something to promote.
583039d628a0SDimitry Andric     // Right now, if we do not have anything to combine with,
583139d628a0SDimitry Andric     // we assume the promotion is not profitable.
583239d628a0SDimitry Andric     if (InstsToBePromoted.empty() || !CombineInst)
583339d628a0SDimitry Andric       return false;
583439d628a0SDimitry Andric 
583539d628a0SDimitry Andric     // Check cost.
583639d628a0SDimitry Andric     if (!StressStoreExtract && !isProfitableToPromote())
583739d628a0SDimitry Andric       return false;
583839d628a0SDimitry Andric 
583939d628a0SDimitry Andric     // Promote.
584039d628a0SDimitry Andric     for (auto &ToBePromoted : InstsToBePromoted)
584139d628a0SDimitry Andric       promoteImpl(ToBePromoted);
584239d628a0SDimitry Andric     InstsToBePromoted.clear();
584339d628a0SDimitry Andric     return true;
584439d628a0SDimitry Andric   }
584539d628a0SDimitry Andric };
584639d628a0SDimitry Andric } // End of anonymous namespace.
584739d628a0SDimitry Andric 
584839d628a0SDimitry Andric void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
584939d628a0SDimitry Andric   // At this point, we know that all the operands of ToBePromoted but Def
585039d628a0SDimitry Andric   // can be statically promoted.
585139d628a0SDimitry Andric   // For Def, we need to use its parameter in ToBePromoted:
585239d628a0SDimitry Andric   // b = ToBePromoted ty1 a
585339d628a0SDimitry Andric   // Def = Transition ty1 b to ty2
585439d628a0SDimitry Andric   // Move the transition down.
585539d628a0SDimitry Andric   // 1. Replace all uses of the promoted operation by the transition.
585639d628a0SDimitry Andric   // = ... b => = ... Def.
585739d628a0SDimitry Andric   assert(ToBePromoted->getType() == Transition->getType() &&
585839d628a0SDimitry Andric          "The type of the result of the transition does not match "
585939d628a0SDimitry Andric          "the final type");
586039d628a0SDimitry Andric   ToBePromoted->replaceAllUsesWith(Transition);
586139d628a0SDimitry Andric   // 2. Update the type of the uses.
586239d628a0SDimitry Andric   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
586339d628a0SDimitry Andric   Type *TransitionTy = getTransitionType();
586439d628a0SDimitry Andric   ToBePromoted->mutateType(TransitionTy);
586539d628a0SDimitry Andric   // 3. Update all the operands of the promoted operation with promoted
586639d628a0SDimitry Andric   // operands.
586739d628a0SDimitry Andric   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
586839d628a0SDimitry Andric   for (Use &U : ToBePromoted->operands()) {
586939d628a0SDimitry Andric     Value *Val = U.get();
587039d628a0SDimitry Andric     Value *NewVal = nullptr;
587139d628a0SDimitry Andric     if (Val == Transition)
587239d628a0SDimitry Andric       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
587339d628a0SDimitry Andric     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
587439d628a0SDimitry Andric              isa<ConstantFP>(Val)) {
587539d628a0SDimitry Andric       // Use a splat constant if it is not safe to use undef.
587639d628a0SDimitry Andric       NewVal = getConstantVector(
587739d628a0SDimitry Andric           cast<Constant>(Val),
587839d628a0SDimitry Andric           isa<UndefValue>(Val) ||
587939d628a0SDimitry Andric               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
588039d628a0SDimitry Andric     } else
588139d628a0SDimitry Andric       llvm_unreachable("Did you modified shouldPromote and forgot to update "
588239d628a0SDimitry Andric                        "this?");
588339d628a0SDimitry Andric     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
588439d628a0SDimitry Andric   }
588539d628a0SDimitry Andric   Transition->removeFromParent();
588639d628a0SDimitry Andric   Transition->insertAfter(ToBePromoted);
588739d628a0SDimitry Andric   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
588839d628a0SDimitry Andric }
588939d628a0SDimitry Andric 
589039d628a0SDimitry Andric /// Some targets can do store(extractelement) with one instruction.
589139d628a0SDimitry Andric /// Try to push the extractelement towards the stores when the target
589239d628a0SDimitry Andric /// has this feature and this is profitable.
58937d523365SDimitry Andric bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
589439d628a0SDimitry Andric   unsigned CombineCost = UINT_MAX;
589539d628a0SDimitry Andric   if (DisableStoreExtract || !TLI ||
589639d628a0SDimitry Andric       (!StressStoreExtract &&
589739d628a0SDimitry Andric        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
589839d628a0SDimitry Andric                                        Inst->getOperand(1), CombineCost)))
589939d628a0SDimitry Andric     return false;
590039d628a0SDimitry Andric 
590139d628a0SDimitry Andric   // At this point we know that Inst is a vector to scalar transition.
590239d628a0SDimitry Andric   // Try to move it down the def-use chain, until:
590339d628a0SDimitry Andric   // - We can combine the transition with its single use
590439d628a0SDimitry Andric   //   => we got rid of the transition.
590539d628a0SDimitry Andric   // - We escape the current basic block
590639d628a0SDimitry Andric   //   => we would need to check that we are moving it at a cheaper place and
590739d628a0SDimitry Andric   //      we do not do that for now.
590839d628a0SDimitry Andric   BasicBlock *Parent = Inst->getParent();
590939d628a0SDimitry Andric   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
5910875ed548SDimitry Andric   VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
591139d628a0SDimitry Andric   // If the transition has more than one use, assume this is not going to be
591239d628a0SDimitry Andric   // beneficial.
591339d628a0SDimitry Andric   while (Inst->hasOneUse()) {
591439d628a0SDimitry Andric     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
591539d628a0SDimitry Andric     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
591639d628a0SDimitry Andric 
591739d628a0SDimitry Andric     if (ToBePromoted->getParent() != Parent) {
591839d628a0SDimitry Andric       DEBUG(dbgs() << "Instruction to promote is in a different block ("
591939d628a0SDimitry Andric                    << ToBePromoted->getParent()->getName()
592039d628a0SDimitry Andric                    << ") than the transition (" << Parent->getName() << ").\n");
592139d628a0SDimitry Andric       return false;
592239d628a0SDimitry Andric     }
592339d628a0SDimitry Andric 
592439d628a0SDimitry Andric     if (VPH.canCombine(ToBePromoted)) {
592539d628a0SDimitry Andric       DEBUG(dbgs() << "Assume " << *Inst << '\n'
592639d628a0SDimitry Andric                    << "will be combined with: " << *ToBePromoted << '\n');
592739d628a0SDimitry Andric       VPH.recordCombineInstruction(ToBePromoted);
592839d628a0SDimitry Andric       bool Changed = VPH.promote();
592939d628a0SDimitry Andric       NumStoreExtractExposed += Changed;
593039d628a0SDimitry Andric       return Changed;
593139d628a0SDimitry Andric     }
593239d628a0SDimitry Andric 
593339d628a0SDimitry Andric     DEBUG(dbgs() << "Try promoting.\n");
593439d628a0SDimitry Andric     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
593539d628a0SDimitry Andric       return false;
593639d628a0SDimitry Andric 
593739d628a0SDimitry Andric     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
593839d628a0SDimitry Andric 
593939d628a0SDimitry Andric     VPH.enqueueForPromotion(ToBePromoted);
594039d628a0SDimitry Andric     Inst = ToBePromoted;
594139d628a0SDimitry Andric   }
594239d628a0SDimitry Andric   return false;
594339d628a0SDimitry Andric }
594439d628a0SDimitry Andric 
5945d88c1a5aSDimitry Andric /// For the instruction sequence of store below, F and I values
5946d88c1a5aSDimitry Andric /// are bundled together as an i64 value before being stored into memory.
5947d88c1a5aSDimitry Andric /// Sometimes it is more efficent to generate separate stores for F and I,
5948d88c1a5aSDimitry Andric /// which can remove the bitwise instructions or sink them to colder places.
5949d88c1a5aSDimitry Andric ///
5950d88c1a5aSDimitry Andric ///   (store (or (zext (bitcast F to i32) to i64),
5951d88c1a5aSDimitry Andric ///              (shl (zext I to i64), 32)), addr)  -->
5952d88c1a5aSDimitry Andric ///   (store F, addr) and (store I, addr+4)
5953d88c1a5aSDimitry Andric ///
5954d88c1a5aSDimitry Andric /// Similarly, splitting for other merged store can also be beneficial, like:
5955d88c1a5aSDimitry Andric /// For pair of {i32, i32}, i64 store --> two i32 stores.
5956d88c1a5aSDimitry Andric /// For pair of {i32, i16}, i64 store --> two i32 stores.
5957d88c1a5aSDimitry Andric /// For pair of {i16, i16}, i32 store --> two i16 stores.
5958d88c1a5aSDimitry Andric /// For pair of {i16, i8},  i32 store --> two i16 stores.
5959d88c1a5aSDimitry Andric /// For pair of {i8, i8},   i16 store --> two i8 stores.
5960d88c1a5aSDimitry Andric ///
5961d88c1a5aSDimitry Andric /// We allow each target to determine specifically which kind of splitting is
5962d88c1a5aSDimitry Andric /// supported.
5963d88c1a5aSDimitry Andric ///
5964d88c1a5aSDimitry Andric /// The store patterns are commonly seen from the simple code snippet below
5965d88c1a5aSDimitry Andric /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5966d88c1a5aSDimitry Andric ///   void goo(const std::pair<int, float> &);
5967d88c1a5aSDimitry Andric ///   hoo() {
5968d88c1a5aSDimitry Andric ///     ...
5969d88c1a5aSDimitry Andric ///     goo(std::make_pair(tmp, ftmp));
5970d88c1a5aSDimitry Andric ///     ...
5971d88c1a5aSDimitry Andric ///   }
5972d88c1a5aSDimitry Andric ///
5973d88c1a5aSDimitry Andric /// Although we already have similar splitting in DAG Combine, we duplicate
5974d88c1a5aSDimitry Andric /// it in CodeGenPrepare to catch the case in which pattern is across
5975d88c1a5aSDimitry Andric /// multiple BBs. The logic in DAG Combine is kept to catch case generated
5976d88c1a5aSDimitry Andric /// during code expansion.
5977d88c1a5aSDimitry Andric static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5978d88c1a5aSDimitry Andric                                 const TargetLowering &TLI) {
5979d88c1a5aSDimitry Andric   // Handle simple but common cases only.
5980d88c1a5aSDimitry Andric   Type *StoreType = SI.getValueOperand()->getType();
5981d88c1a5aSDimitry Andric   if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5982d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(StoreType) == 0)
5983d88c1a5aSDimitry Andric     return false;
5984d88c1a5aSDimitry Andric 
5985d88c1a5aSDimitry Andric   unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5986d88c1a5aSDimitry Andric   Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5987d88c1a5aSDimitry Andric   if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5988d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(SplitStoreType))
5989d88c1a5aSDimitry Andric     return false;
5990d88c1a5aSDimitry Andric 
5991d88c1a5aSDimitry Andric   // Match the following patterns:
5992d88c1a5aSDimitry Andric   // (store (or (zext LValue to i64),
5993d88c1a5aSDimitry Andric   //            (shl (zext HValue to i64), 32)), HalfValBitSize)
5994d88c1a5aSDimitry Andric   //  or
5995d88c1a5aSDimitry Andric   // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5996d88c1a5aSDimitry Andric   //            (zext LValue to i64),
5997d88c1a5aSDimitry Andric   // Expect both operands of OR and the first operand of SHL have only
5998d88c1a5aSDimitry Andric   // one use.
5999d88c1a5aSDimitry Andric   Value *LValue, *HValue;
6000d88c1a5aSDimitry Andric   if (!match(SI.getValueOperand(),
6001d88c1a5aSDimitry Andric              m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6002d88c1a5aSDimitry Andric                     m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6003d88c1a5aSDimitry Andric                                    m_SpecificInt(HalfValBitSize))))))
6004d88c1a5aSDimitry Andric     return false;
6005d88c1a5aSDimitry Andric 
6006d88c1a5aSDimitry Andric   // Check LValue and HValue are int with size less or equal than 32.
6007d88c1a5aSDimitry Andric   if (!LValue->getType()->isIntegerTy() ||
6008d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6009d88c1a5aSDimitry Andric       !HValue->getType()->isIntegerTy() ||
6010d88c1a5aSDimitry Andric       DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6011d88c1a5aSDimitry Andric     return false;
6012d88c1a5aSDimitry Andric 
6013d88c1a5aSDimitry Andric   // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6014d88c1a5aSDimitry Andric   // as the input of target query.
6015d88c1a5aSDimitry Andric   auto *LBC = dyn_cast<BitCastInst>(LValue);
6016d88c1a5aSDimitry Andric   auto *HBC = dyn_cast<BitCastInst>(HValue);
6017d88c1a5aSDimitry Andric   EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6018d88c1a5aSDimitry Andric                   : EVT::getEVT(LValue->getType());
6019d88c1a5aSDimitry Andric   EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6020d88c1a5aSDimitry Andric                    : EVT::getEVT(HValue->getType());
6021d88c1a5aSDimitry Andric   if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6022d88c1a5aSDimitry Andric     return false;
6023d88c1a5aSDimitry Andric 
6024d88c1a5aSDimitry Andric   // Start to split store.
6025d88c1a5aSDimitry Andric   IRBuilder<> Builder(SI.getContext());
6026d88c1a5aSDimitry Andric   Builder.SetInsertPoint(&SI);
6027d88c1a5aSDimitry Andric 
6028d88c1a5aSDimitry Andric   // If LValue/HValue is a bitcast in another BB, create a new one in current
6029d88c1a5aSDimitry Andric   // BB so it may be merged with the splitted stores by dag combiner.
6030d88c1a5aSDimitry Andric   if (LBC && LBC->getParent() != SI.getParent())
6031d88c1a5aSDimitry Andric     LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6032d88c1a5aSDimitry Andric   if (HBC && HBC->getParent() != SI.getParent())
6033d88c1a5aSDimitry Andric     HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6034d88c1a5aSDimitry Andric 
6035d88c1a5aSDimitry Andric   auto CreateSplitStore = [&](Value *V, bool Upper) {
6036d88c1a5aSDimitry Andric     V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6037d88c1a5aSDimitry Andric     Value *Addr = Builder.CreateBitCast(
6038d88c1a5aSDimitry Andric         SI.getOperand(1),
6039d88c1a5aSDimitry Andric         SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6040d88c1a5aSDimitry Andric     if (Upper)
6041d88c1a5aSDimitry Andric       Addr = Builder.CreateGEP(
6042d88c1a5aSDimitry Andric           SplitStoreType, Addr,
6043d88c1a5aSDimitry Andric           ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6044d88c1a5aSDimitry Andric     Builder.CreateAlignedStore(
6045d88c1a5aSDimitry Andric         V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6046d88c1a5aSDimitry Andric   };
6047d88c1a5aSDimitry Andric 
6048d88c1a5aSDimitry Andric   CreateSplitStore(LValue, false);
6049d88c1a5aSDimitry Andric   CreateSplitStore(HValue, true);
6050d88c1a5aSDimitry Andric 
6051d88c1a5aSDimitry Andric   // Delete the old store.
6052d88c1a5aSDimitry Andric   SI.eraseFromParent();
6053d88c1a5aSDimitry Andric   return true;
6054d88c1a5aSDimitry Andric }
6055d88c1a5aSDimitry Andric 
60567d523365SDimitry Andric bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
60578f0fd8f6SDimitry Andric   // Bail out if we inserted the instruction to prevent optimizations from
60588f0fd8f6SDimitry Andric   // stepping on each other's toes.
60598f0fd8f6SDimitry Andric   if (InsertedInsts.count(I))
60608f0fd8f6SDimitry Andric     return false;
60618f0fd8f6SDimitry Andric 
606291bc56edSDimitry Andric   if (PHINode *P = dyn_cast<PHINode>(I)) {
606391bc56edSDimitry Andric     // It is possible for very late stage optimizations (such as SimplifyCFG)
606491bc56edSDimitry Andric     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
606591bc56edSDimitry Andric     // trivial PHI, go ahead and zap it here.
6066f37b6182SDimitry Andric     if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
606791bc56edSDimitry Andric       P->replaceAllUsesWith(V);
606891bc56edSDimitry Andric       P->eraseFromParent();
606991bc56edSDimitry Andric       ++NumPHIsElim;
607091bc56edSDimitry Andric       return true;
607191bc56edSDimitry Andric     }
607291bc56edSDimitry Andric     return false;
607391bc56edSDimitry Andric   }
607491bc56edSDimitry Andric 
607591bc56edSDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
607691bc56edSDimitry Andric     // If the source of the cast is a constant, then this should have
607791bc56edSDimitry Andric     // already been constant folded.  The only reason NOT to constant fold
607891bc56edSDimitry Andric     // it is if something (e.g. LSR) was careful to place the constant
607991bc56edSDimitry Andric     // evaluation in a block other than then one that uses it (e.g. to hoist
608091bc56edSDimitry Andric     // the address of globals out of a loop).  If this is the case, we don't
608191bc56edSDimitry Andric     // want to forward-subst the cast.
608291bc56edSDimitry Andric     if (isa<Constant>(CI->getOperand(0)))
608391bc56edSDimitry Andric       return false;
608491bc56edSDimitry Andric 
6085875ed548SDimitry Andric     if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
608691bc56edSDimitry Andric       return true;
608791bc56edSDimitry Andric 
608891bc56edSDimitry Andric     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
608991bc56edSDimitry Andric       /// Sink a zext or sext into its user blocks if the target type doesn't
609091bc56edSDimitry Andric       /// fit in one register
6091875ed548SDimitry Andric       if (TLI &&
6092875ed548SDimitry Andric           TLI->getTypeAction(CI->getContext(),
6093875ed548SDimitry Andric                              TLI->getValueType(*DL, CI->getType())) ==
609491bc56edSDimitry Andric               TargetLowering::TypeExpandInteger) {
609591bc56edSDimitry Andric         return SinkCast(CI);
609691bc56edSDimitry Andric       } else {
60977a7e6055SDimitry Andric         bool MadeChange = optimizeExt(I);
60987d523365SDimitry Andric         return MadeChange | optimizeExtUses(I);
609991bc56edSDimitry Andric       }
610091bc56edSDimitry Andric     }
610191bc56edSDimitry Andric     return false;
610291bc56edSDimitry Andric   }
610391bc56edSDimitry Andric 
610491bc56edSDimitry Andric   if (CmpInst *CI = dyn_cast<CmpInst>(I))
610591bc56edSDimitry Andric     if (!TLI || !TLI->hasMultipleConditionRegisters())
61063ca95b02SDimitry Andric       return OptimizeCmpExpression(CI, TLI);
610791bc56edSDimitry Andric 
610891bc56edSDimitry Andric   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6109d88c1a5aSDimitry Andric     LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
611097bc6c73SDimitry Andric     if (TLI) {
61117d523365SDimitry Andric       bool Modified = optimizeLoadExt(LI);
611297bc6c73SDimitry Andric       unsigned AS = LI->getPointerAddressSpace();
61137d523365SDimitry Andric       Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
61147d523365SDimitry Andric       return Modified;
611597bc6c73SDimitry Andric     }
611691bc56edSDimitry Andric     return false;
611791bc56edSDimitry Andric   }
611891bc56edSDimitry Andric 
611991bc56edSDimitry Andric   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
6120d88c1a5aSDimitry Andric     if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6121d88c1a5aSDimitry Andric       return true;
6122d88c1a5aSDimitry Andric     SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
612397bc6c73SDimitry Andric     if (TLI) {
612497bc6c73SDimitry Andric       unsigned AS = SI->getPointerAddressSpace();
61257d523365SDimitry Andric       return optimizeMemoryInst(I, SI->getOperand(1),
612697bc6c73SDimitry Andric                                 SI->getOperand(0)->getType(), AS);
612797bc6c73SDimitry Andric     }
612891bc56edSDimitry Andric     return false;
612991bc56edSDimitry Andric   }
613091bc56edSDimitry Andric 
61317a7e6055SDimitry Andric   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
61327a7e6055SDimitry Andric       unsigned AS = RMW->getPointerAddressSpace();
61337a7e6055SDimitry Andric       return optimizeMemoryInst(I, RMW->getPointerOperand(),
61347a7e6055SDimitry Andric                                 RMW->getType(), AS);
61357a7e6055SDimitry Andric   }
61367a7e6055SDimitry Andric 
61377a7e6055SDimitry Andric   if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
61387a7e6055SDimitry Andric       unsigned AS = CmpX->getPointerAddressSpace();
61397a7e6055SDimitry Andric       return optimizeMemoryInst(I, CmpX->getPointerOperand(),
61407a7e6055SDimitry Andric                                 CmpX->getCompareOperand()->getType(), AS);
61417a7e6055SDimitry Andric   }
61427a7e6055SDimitry Andric 
614391bc56edSDimitry Andric   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
614491bc56edSDimitry Andric 
61457a7e6055SDimitry Andric   if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
61467a7e6055SDimitry Andric       EnableAndCmpSinking && TLI)
61477a7e6055SDimitry Andric     return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
61487a7e6055SDimitry Andric 
614991bc56edSDimitry Andric   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
615091bc56edSDimitry Andric                 BinOp->getOpcode() == Instruction::LShr)) {
615191bc56edSDimitry Andric     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
615291bc56edSDimitry Andric     if (TLI && CI && TLI->hasExtractBitsInsn())
6153875ed548SDimitry Andric       return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
615491bc56edSDimitry Andric 
615591bc56edSDimitry Andric     return false;
615691bc56edSDimitry Andric   }
615791bc56edSDimitry Andric 
615891bc56edSDimitry Andric   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
615991bc56edSDimitry Andric     if (GEPI->hasAllZeroIndices()) {
616091bc56edSDimitry Andric       /// The GEP operand must be a pointer, so must its result -> BitCast
616191bc56edSDimitry Andric       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
616291bc56edSDimitry Andric                                         GEPI->getName(), GEPI);
616391bc56edSDimitry Andric       GEPI->replaceAllUsesWith(NC);
616491bc56edSDimitry Andric       GEPI->eraseFromParent();
616591bc56edSDimitry Andric       ++NumGEPsElim;
61667d523365SDimitry Andric       optimizeInst(NC, ModifiedDT);
616791bc56edSDimitry Andric       return true;
616891bc56edSDimitry Andric     }
616991bc56edSDimitry Andric     return false;
617091bc56edSDimitry Andric   }
617191bc56edSDimitry Andric 
617291bc56edSDimitry Andric   if (CallInst *CI = dyn_cast<CallInst>(I))
61737d523365SDimitry Andric     return optimizeCallInst(CI, ModifiedDT);
617491bc56edSDimitry Andric 
617591bc56edSDimitry Andric   if (SelectInst *SI = dyn_cast<SelectInst>(I))
61767d523365SDimitry Andric     return optimizeSelectInst(SI);
617791bc56edSDimitry Andric 
617891bc56edSDimitry Andric   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
61797d523365SDimitry Andric     return optimizeShuffleVectorInst(SVI);
61807d523365SDimitry Andric 
61817d523365SDimitry Andric   if (auto *Switch = dyn_cast<SwitchInst>(I))
61827d523365SDimitry Andric     return optimizeSwitchInst(Switch);
618391bc56edSDimitry Andric 
618439d628a0SDimitry Andric   if (isa<ExtractElementInst>(I))
61857d523365SDimitry Andric     return optimizeExtractElementInst(I);
618639d628a0SDimitry Andric 
618791bc56edSDimitry Andric   return false;
618891bc56edSDimitry Andric }
618991bc56edSDimitry Andric 
61908c24ff90SDimitry Andric /// Given an OR instruction, check to see if this is a bitreverse
61918c24ff90SDimitry Andric /// idiom. If so, insert the new intrinsic and return true.
61928c24ff90SDimitry Andric static bool makeBitReverse(Instruction &I, const DataLayout &DL,
61938c24ff90SDimitry Andric                            const TargetLowering &TLI) {
61948c24ff90SDimitry Andric   if (!I.getType()->isIntegerTy() ||
61958c24ff90SDimitry Andric       !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
61968c24ff90SDimitry Andric                                     TLI.getValueType(DL, I.getType(), true)))
61978c24ff90SDimitry Andric     return false;
61988c24ff90SDimitry Andric 
61998c24ff90SDimitry Andric   SmallVector<Instruction*, 4> Insts;
62003ca95b02SDimitry Andric   if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
62018c24ff90SDimitry Andric     return false;
62028c24ff90SDimitry Andric   Instruction *LastInst = Insts.back();
62038c24ff90SDimitry Andric   I.replaceAllUsesWith(LastInst);
62048c24ff90SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(&I);
62058c24ff90SDimitry Andric   return true;
62068c24ff90SDimitry Andric }
62078c24ff90SDimitry Andric 
620891bc56edSDimitry Andric // In this pass we look for GEP and cast instructions that are used
620991bc56edSDimitry Andric // across basic blocks and rewrite them to improve basic-block-at-a-time
621091bc56edSDimitry Andric // selection.
62117d523365SDimitry Andric bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
621291bc56edSDimitry Andric   SunkAddrs.clear();
621391bc56edSDimitry Andric   bool MadeChange = false;
621491bc56edSDimitry Andric 
621591bc56edSDimitry Andric   CurInstIterator = BB.begin();
621639d628a0SDimitry Andric   while (CurInstIterator != BB.end()) {
62177d523365SDimitry Andric     MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
621839d628a0SDimitry Andric     if (ModifiedDT)
621939d628a0SDimitry Andric       return true;
622039d628a0SDimitry Andric   }
62218c24ff90SDimitry Andric 
62228c24ff90SDimitry Andric   bool MadeBitReverse = true;
62238c24ff90SDimitry Andric   while (TLI && MadeBitReverse) {
62248c24ff90SDimitry Andric     MadeBitReverse = false;
62258c24ff90SDimitry Andric     for (auto &I : reverse(BB)) {
62268c24ff90SDimitry Andric       if (makeBitReverse(I, *DL, *TLI)) {
62278c24ff90SDimitry Andric         MadeBitReverse = MadeChange = true;
62283ca95b02SDimitry Andric         ModifiedDT = true;
62298c24ff90SDimitry Andric         break;
62308c24ff90SDimitry Andric       }
62318c24ff90SDimitry Andric     }
62328c24ff90SDimitry Andric   }
62337d523365SDimitry Andric   MadeChange |= dupRetToEnableTailCallOpts(&BB);
623491bc56edSDimitry Andric 
623591bc56edSDimitry Andric   return MadeChange;
623691bc56edSDimitry Andric }
623791bc56edSDimitry Andric 
623891bc56edSDimitry Andric // llvm.dbg.value is far away from the value then iSel may not be able
623991bc56edSDimitry Andric // handle it properly. iSel will drop llvm.dbg.value if it can not
624091bc56edSDimitry Andric // find a node corresponding to the value.
62417d523365SDimitry Andric bool CodeGenPrepare::placeDbgValues(Function &F) {
624291bc56edSDimitry Andric   bool MadeChange = false;
624339d628a0SDimitry Andric   for (BasicBlock &BB : F) {
624491bc56edSDimitry Andric     Instruction *PrevNonDbgInst = nullptr;
624539d628a0SDimitry Andric     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
62467d523365SDimitry Andric       Instruction *Insn = &*BI++;
624791bc56edSDimitry Andric       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
624891bc56edSDimitry Andric       // Leave dbg.values that refer to an alloca alone. These
624991bc56edSDimitry Andric       // instrinsics describe the address of a variable (= the alloca)
625091bc56edSDimitry Andric       // being taken.  They should not be moved next to the alloca
625191bc56edSDimitry Andric       // (and to the beginning of the scope), but rather stay close to
625291bc56edSDimitry Andric       // where said address is used.
625391bc56edSDimitry Andric       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
625491bc56edSDimitry Andric         PrevNonDbgInst = Insn;
625591bc56edSDimitry Andric         continue;
625691bc56edSDimitry Andric       }
625791bc56edSDimitry Andric 
625891bc56edSDimitry Andric       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
625991bc56edSDimitry Andric       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
62607d523365SDimitry Andric         // If VI is a phi in a block with an EHPad terminator, we can't insert
62617d523365SDimitry Andric         // after it.
62627d523365SDimitry Andric         if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
62637d523365SDimitry Andric           continue;
626491bc56edSDimitry Andric         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
626591bc56edSDimitry Andric         DVI->removeFromParent();
626691bc56edSDimitry Andric         if (isa<PHINode>(VI))
62677d523365SDimitry Andric           DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
626891bc56edSDimitry Andric         else
626991bc56edSDimitry Andric           DVI->insertAfter(VI);
627091bc56edSDimitry Andric         MadeChange = true;
627191bc56edSDimitry Andric         ++NumDbgValueMoved;
627291bc56edSDimitry Andric       }
627391bc56edSDimitry Andric     }
627491bc56edSDimitry Andric   }
627591bc56edSDimitry Andric   return MadeChange;
627691bc56edSDimitry Andric }
627791bc56edSDimitry Andric 
627839d628a0SDimitry Andric /// \brief Scale down both weights to fit into uint32_t.
627939d628a0SDimitry Andric static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
628039d628a0SDimitry Andric   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
628139d628a0SDimitry Andric   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
628239d628a0SDimitry Andric   NewTrue = NewTrue / Scale;
628339d628a0SDimitry Andric   NewFalse = NewFalse / Scale;
628439d628a0SDimitry Andric }
628539d628a0SDimitry Andric 
628639d628a0SDimitry Andric /// \brief Some targets prefer to split a conditional branch like:
628739d628a0SDimitry Andric /// \code
628839d628a0SDimitry Andric ///   %0 = icmp ne i32 %a, 0
628939d628a0SDimitry Andric ///   %1 = icmp ne i32 %b, 0
629039d628a0SDimitry Andric ///   %or.cond = or i1 %0, %1
629139d628a0SDimitry Andric ///   br i1 %or.cond, label %TrueBB, label %FalseBB
629239d628a0SDimitry Andric /// \endcode
629339d628a0SDimitry Andric /// into multiple branch instructions like:
629439d628a0SDimitry Andric /// \code
629539d628a0SDimitry Andric ///   bb1:
629639d628a0SDimitry Andric ///     %0 = icmp ne i32 %a, 0
629739d628a0SDimitry Andric ///     br i1 %0, label %TrueBB, label %bb2
629839d628a0SDimitry Andric ///   bb2:
629939d628a0SDimitry Andric ///     %1 = icmp ne i32 %b, 0
630039d628a0SDimitry Andric ///     br i1 %1, label %TrueBB, label %FalseBB
630139d628a0SDimitry Andric /// \endcode
630239d628a0SDimitry Andric /// This usually allows instruction selection to do even further optimizations
630339d628a0SDimitry Andric /// and combine the compare with the branch instruction. Currently this is
630439d628a0SDimitry Andric /// applied for targets which have "cheap" jump instructions.
630539d628a0SDimitry Andric ///
630639d628a0SDimitry Andric /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
630739d628a0SDimitry Andric ///
630839d628a0SDimitry Andric bool CodeGenPrepare::splitBranchCondition(Function &F) {
6309ff0cc061SDimitry Andric   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
631039d628a0SDimitry Andric     return false;
631139d628a0SDimitry Andric 
631239d628a0SDimitry Andric   bool MadeChange = false;
631339d628a0SDimitry Andric   for (auto &BB : F) {
631439d628a0SDimitry Andric     // Does this BB end with the following?
631539d628a0SDimitry Andric     //   %cond1 = icmp|fcmp|binary instruction ...
631639d628a0SDimitry Andric     //   %cond2 = icmp|fcmp|binary instruction ...
631739d628a0SDimitry Andric     //   %cond.or = or|and i1 %cond1, cond2
631839d628a0SDimitry Andric     //   br i1 %cond.or label %dest1, label %dest2"
631939d628a0SDimitry Andric     BinaryOperator *LogicOp;
632039d628a0SDimitry Andric     BasicBlock *TBB, *FBB;
632139d628a0SDimitry Andric     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
632239d628a0SDimitry Andric       continue;
632339d628a0SDimitry Andric 
63247d523365SDimitry Andric     auto *Br1 = cast<BranchInst>(BB.getTerminator());
63257d523365SDimitry Andric     if (Br1->getMetadata(LLVMContext::MD_unpredictable))
63267d523365SDimitry Andric       continue;
63277d523365SDimitry Andric 
632839d628a0SDimitry Andric     unsigned Opc;
632939d628a0SDimitry Andric     Value *Cond1, *Cond2;
633039d628a0SDimitry Andric     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
633139d628a0SDimitry Andric                              m_OneUse(m_Value(Cond2)))))
633239d628a0SDimitry Andric       Opc = Instruction::And;
633339d628a0SDimitry Andric     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
633439d628a0SDimitry Andric                                  m_OneUse(m_Value(Cond2)))))
633539d628a0SDimitry Andric       Opc = Instruction::Or;
633639d628a0SDimitry Andric     else
633739d628a0SDimitry Andric       continue;
633839d628a0SDimitry Andric 
633939d628a0SDimitry Andric     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
634039d628a0SDimitry Andric         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
634139d628a0SDimitry Andric       continue;
634239d628a0SDimitry Andric 
634339d628a0SDimitry Andric     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
634439d628a0SDimitry Andric 
634539d628a0SDimitry Andric     // Create a new BB.
63463ca95b02SDimitry Andric     auto TmpBB =
63473ca95b02SDimitry Andric         BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
63483ca95b02SDimitry Andric                            BB.getParent(), BB.getNextNode());
634939d628a0SDimitry Andric 
635039d628a0SDimitry Andric     // Update original basic block by using the first condition directly by the
635139d628a0SDimitry Andric     // branch instruction and removing the no longer needed and/or instruction.
635239d628a0SDimitry Andric     Br1->setCondition(Cond1);
635339d628a0SDimitry Andric     LogicOp->eraseFromParent();
635439d628a0SDimitry Andric 
635539d628a0SDimitry Andric     // Depending on the conditon we have to either replace the true or the false
635639d628a0SDimitry Andric     // successor of the original branch instruction.
635739d628a0SDimitry Andric     if (Opc == Instruction::And)
635839d628a0SDimitry Andric       Br1->setSuccessor(0, TmpBB);
635939d628a0SDimitry Andric     else
636039d628a0SDimitry Andric       Br1->setSuccessor(1, TmpBB);
636139d628a0SDimitry Andric 
636239d628a0SDimitry Andric     // Fill in the new basic block.
636339d628a0SDimitry Andric     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
636439d628a0SDimitry Andric     if (auto *I = dyn_cast<Instruction>(Cond2)) {
636539d628a0SDimitry Andric       I->removeFromParent();
636639d628a0SDimitry Andric       I->insertBefore(Br2);
636739d628a0SDimitry Andric     }
636839d628a0SDimitry Andric 
636939d628a0SDimitry Andric     // Update PHI nodes in both successors. The original BB needs to be
637039d628a0SDimitry Andric     // replaced in one succesor's PHI nodes, because the branch comes now from
637139d628a0SDimitry Andric     // the newly generated BB (NewBB). In the other successor we need to add one
637239d628a0SDimitry Andric     // incoming edge to the PHI nodes, because both branch instructions target
637339d628a0SDimitry Andric     // now the same successor. Depending on the original branch condition
637439d628a0SDimitry Andric     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
6375d88c1a5aSDimitry Andric     // we perform the correct update for the PHI nodes.
637639d628a0SDimitry Andric     // This doesn't change the successor order of the just created branch
637739d628a0SDimitry Andric     // instruction (or any other instruction).
637839d628a0SDimitry Andric     if (Opc == Instruction::Or)
637939d628a0SDimitry Andric       std::swap(TBB, FBB);
638039d628a0SDimitry Andric 
638139d628a0SDimitry Andric     // Replace the old BB with the new BB.
638239d628a0SDimitry Andric     for (auto &I : *TBB) {
638339d628a0SDimitry Andric       PHINode *PN = dyn_cast<PHINode>(&I);
638439d628a0SDimitry Andric       if (!PN)
638539d628a0SDimitry Andric         break;
638639d628a0SDimitry Andric       int i;
638739d628a0SDimitry Andric       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
638839d628a0SDimitry Andric         PN->setIncomingBlock(i, TmpBB);
638939d628a0SDimitry Andric     }
639039d628a0SDimitry Andric 
639139d628a0SDimitry Andric     // Add another incoming edge form the new BB.
639239d628a0SDimitry Andric     for (auto &I : *FBB) {
639339d628a0SDimitry Andric       PHINode *PN = dyn_cast<PHINode>(&I);
639439d628a0SDimitry Andric       if (!PN)
639539d628a0SDimitry Andric         break;
639639d628a0SDimitry Andric       auto *Val = PN->getIncomingValueForBlock(&BB);
639739d628a0SDimitry Andric       PN->addIncoming(Val, TmpBB);
639839d628a0SDimitry Andric     }
639939d628a0SDimitry Andric 
640039d628a0SDimitry Andric     // Update the branch weights (from SelectionDAGBuilder::
640139d628a0SDimitry Andric     // FindMergedConditions).
640239d628a0SDimitry Andric     if (Opc == Instruction::Or) {
640339d628a0SDimitry Andric       // Codegen X | Y as:
640439d628a0SDimitry Andric       // BB1:
640539d628a0SDimitry Andric       //   jmp_if_X TBB
640639d628a0SDimitry Andric       //   jmp TmpBB
640739d628a0SDimitry Andric       // TmpBB:
640839d628a0SDimitry Andric       //   jmp_if_Y TBB
640939d628a0SDimitry Andric       //   jmp FBB
641039d628a0SDimitry Andric       //
641139d628a0SDimitry Andric 
641239d628a0SDimitry Andric       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
641339d628a0SDimitry Andric       // The requirement is that
641439d628a0SDimitry Andric       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
641539d628a0SDimitry Andric       //     = TrueProb for orignal BB.
641639d628a0SDimitry Andric       // Assuming the orignal weights are A and B, one choice is to set BB1's
641739d628a0SDimitry Andric       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
641839d628a0SDimitry Andric       // assumes that
641939d628a0SDimitry Andric       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
642039d628a0SDimitry Andric       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
642139d628a0SDimitry Andric       // TmpBB, but the math is more complicated.
642239d628a0SDimitry Andric       uint64_t TrueWeight, FalseWeight;
64233ca95b02SDimitry Andric       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
642439d628a0SDimitry Andric         uint64_t NewTrueWeight = TrueWeight;
642539d628a0SDimitry Andric         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
642639d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
642739d628a0SDimitry Andric         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
642839d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
642939d628a0SDimitry Andric 
643039d628a0SDimitry Andric         NewTrueWeight = TrueWeight;
643139d628a0SDimitry Andric         NewFalseWeight = 2 * FalseWeight;
643239d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
643339d628a0SDimitry Andric         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
643439d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
643539d628a0SDimitry Andric       }
643639d628a0SDimitry Andric     } else {
643739d628a0SDimitry Andric       // Codegen X & Y as:
643839d628a0SDimitry Andric       // BB1:
643939d628a0SDimitry Andric       //   jmp_if_X TmpBB
644039d628a0SDimitry Andric       //   jmp FBB
644139d628a0SDimitry Andric       // TmpBB:
644239d628a0SDimitry Andric       //   jmp_if_Y TBB
644339d628a0SDimitry Andric       //   jmp FBB
644439d628a0SDimitry Andric       //
644539d628a0SDimitry Andric       //  This requires creation of TmpBB after CurBB.
644639d628a0SDimitry Andric 
644739d628a0SDimitry Andric       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
644839d628a0SDimitry Andric       // The requirement is that
644939d628a0SDimitry Andric       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
645039d628a0SDimitry Andric       //     = FalseProb for orignal BB.
645139d628a0SDimitry Andric       // Assuming the orignal weights are A and B, one choice is to set BB1's
645239d628a0SDimitry Andric       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
645339d628a0SDimitry Andric       // assumes that
645439d628a0SDimitry Andric       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
645539d628a0SDimitry Andric       uint64_t TrueWeight, FalseWeight;
64563ca95b02SDimitry Andric       if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
645739d628a0SDimitry Andric         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
645839d628a0SDimitry Andric         uint64_t NewFalseWeight = FalseWeight;
645939d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
646039d628a0SDimitry Andric         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
646139d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
646239d628a0SDimitry Andric 
646339d628a0SDimitry Andric         NewTrueWeight = 2 * TrueWeight;
646439d628a0SDimitry Andric         NewFalseWeight = FalseWeight;
646539d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
646639d628a0SDimitry Andric         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
646739d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
646839d628a0SDimitry Andric       }
646939d628a0SDimitry Andric     }
647039d628a0SDimitry Andric 
647139d628a0SDimitry Andric     // Note: No point in getting fancy here, since the DT info is never
6472ff0cc061SDimitry Andric     // available to CodeGenPrepare.
647339d628a0SDimitry Andric     ModifiedDT = true;
647439d628a0SDimitry Andric 
647539d628a0SDimitry Andric     MadeChange = true;
647639d628a0SDimitry Andric 
647739d628a0SDimitry Andric     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
647839d628a0SDimitry Andric           TmpBB->dump());
647939d628a0SDimitry Andric   }
648039d628a0SDimitry Andric   return MadeChange;
648139d628a0SDimitry Andric }
6482