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/CodeGen/Passes.h"
1791bc56edSDimitry Andric #include "llvm/ADT/DenseMap.h"
1891bc56edSDimitry Andric #include "llvm/ADT/SmallSet.h"
1991bc56edSDimitry Andric #include "llvm/ADT/Statistic.h"
2091bc56edSDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
21ff0cc061SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
2239d628a0SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
2391bc56edSDimitry Andric #include "llvm/IR/CallSite.h"
2491bc56edSDimitry Andric #include "llvm/IR/Constants.h"
2591bc56edSDimitry Andric #include "llvm/IR/DataLayout.h"
2691bc56edSDimitry Andric #include "llvm/IR/DerivedTypes.h"
2791bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
2891bc56edSDimitry Andric #include "llvm/IR/Function.h"
2991bc56edSDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
3091bc56edSDimitry Andric #include "llvm/IR/IRBuilder.h"
3191bc56edSDimitry Andric #include "llvm/IR/InlineAsm.h"
3291bc56edSDimitry Andric #include "llvm/IR/Instructions.h"
3391bc56edSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
3439d628a0SDimitry Andric #include "llvm/IR/MDBuilder.h"
3591bc56edSDimitry Andric #include "llvm/IR/PatternMatch.h"
36ff0cc061SDimitry Andric #include "llvm/IR/Statepoint.h"
3791bc56edSDimitry Andric #include "llvm/IR/ValueHandle.h"
3891bc56edSDimitry Andric #include "llvm/IR/ValueMap.h"
3991bc56edSDimitry Andric #include "llvm/Pass.h"
4091bc56edSDimitry Andric #include "llvm/Support/CommandLine.h"
4191bc56edSDimitry Andric #include "llvm/Support/Debug.h"
4291bc56edSDimitry Andric #include "llvm/Support/raw_ostream.h"
4391bc56edSDimitry Andric #include "llvm/Target/TargetLowering.h"
4491bc56edSDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
4591bc56edSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
4691bc56edSDimitry Andric #include "llvm/Transforms/Utils/BuildLibCalls.h"
4791bc56edSDimitry Andric #include "llvm/Transforms/Utils/BypassSlowDivision.h"
4891bc56edSDimitry Andric #include "llvm/Transforms/Utils/Local.h"
4939d628a0SDimitry Andric #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
5091bc56edSDimitry Andric using namespace llvm;
5191bc56edSDimitry Andric using namespace llvm::PatternMatch;
5291bc56edSDimitry Andric 
5391bc56edSDimitry Andric #define DEBUG_TYPE "codegenprepare"
5491bc56edSDimitry Andric 
5591bc56edSDimitry Andric STATISTIC(NumBlocksElim, "Number of blocks eliminated");
5691bc56edSDimitry Andric STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
5791bc56edSDimitry Andric STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
5891bc56edSDimitry Andric STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
5991bc56edSDimitry Andric                       "sunken Cmps");
6091bc56edSDimitry Andric STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
6191bc56edSDimitry Andric                        "of sunken Casts");
6291bc56edSDimitry Andric STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
6391bc56edSDimitry Andric                           "computations were sunk");
6491bc56edSDimitry Andric STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
6591bc56edSDimitry Andric STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
6691bc56edSDimitry Andric STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
6791bc56edSDimitry Andric STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
6891bc56edSDimitry Andric STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
6991bc56edSDimitry Andric STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
7039d628a0SDimitry Andric STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
7191bc56edSDimitry Andric 
7291bc56edSDimitry Andric static cl::opt<bool> DisableBranchOpts(
7391bc56edSDimitry Andric   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
7491bc56edSDimitry Andric   cl::desc("Disable branch optimizations in CodeGenPrepare"));
7591bc56edSDimitry Andric 
76ff0cc061SDimitry Andric static cl::opt<bool>
77ff0cc061SDimitry Andric     DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
78ff0cc061SDimitry Andric                   cl::desc("Disable GC optimizations in CodeGenPrepare"));
79ff0cc061SDimitry Andric 
8091bc56edSDimitry Andric static cl::opt<bool> DisableSelectToBranch(
8191bc56edSDimitry Andric   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
8291bc56edSDimitry Andric   cl::desc("Disable select to branch conversion."));
8391bc56edSDimitry Andric 
8491bc56edSDimitry Andric static cl::opt<bool> AddrSinkUsingGEPs(
8591bc56edSDimitry Andric   "addr-sink-using-gep", cl::Hidden, cl::init(false),
8691bc56edSDimitry Andric   cl::desc("Address sinking in CGP using GEPs."));
8791bc56edSDimitry Andric 
8891bc56edSDimitry Andric static cl::opt<bool> EnableAndCmpSinking(
8991bc56edSDimitry Andric    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
9091bc56edSDimitry Andric    cl::desc("Enable sinkinig and/cmp into branches."));
9191bc56edSDimitry Andric 
9239d628a0SDimitry Andric static cl::opt<bool> DisableStoreExtract(
9339d628a0SDimitry Andric     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
9439d628a0SDimitry Andric     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
9539d628a0SDimitry Andric 
9639d628a0SDimitry Andric static cl::opt<bool> StressStoreExtract(
9739d628a0SDimitry Andric     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
9839d628a0SDimitry Andric     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
9939d628a0SDimitry Andric 
10039d628a0SDimitry Andric static cl::opt<bool> DisableExtLdPromotion(
10139d628a0SDimitry Andric     "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
10239d628a0SDimitry Andric     cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
10339d628a0SDimitry Andric              "CodeGenPrepare"));
10439d628a0SDimitry Andric 
10539d628a0SDimitry Andric static cl::opt<bool> StressExtLdPromotion(
10639d628a0SDimitry Andric     "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
10739d628a0SDimitry Andric     cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
10839d628a0SDimitry Andric              "optimization in CodeGenPrepare"));
10939d628a0SDimitry Andric 
11091bc56edSDimitry Andric namespace {
11191bc56edSDimitry Andric typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
11239d628a0SDimitry Andric struct TypeIsSExt {
11339d628a0SDimitry Andric   Type *Ty;
11439d628a0SDimitry Andric   bool IsSExt;
11539d628a0SDimitry Andric   TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
11639d628a0SDimitry Andric };
11739d628a0SDimitry Andric typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
11839d628a0SDimitry Andric class TypePromotionTransaction;
11991bc56edSDimitry Andric 
12091bc56edSDimitry Andric   class CodeGenPrepare : public FunctionPass {
12191bc56edSDimitry Andric     /// TLI - Keep a pointer of a TargetLowering to consult for determining
12291bc56edSDimitry Andric     /// transformation profitability.
12391bc56edSDimitry Andric     const TargetMachine *TM;
12491bc56edSDimitry Andric     const TargetLowering *TLI;
12539d628a0SDimitry Andric     const TargetTransformInfo *TTI;
12691bc56edSDimitry Andric     const TargetLibraryInfo *TLInfo;
12791bc56edSDimitry Andric 
12891bc56edSDimitry Andric     /// CurInstIterator - As we scan instructions optimizing them, this is the
12991bc56edSDimitry Andric     /// next instruction to optimize.  Xforms that can invalidate this should
13091bc56edSDimitry Andric     /// update it.
13191bc56edSDimitry Andric     BasicBlock::iterator CurInstIterator;
13291bc56edSDimitry Andric 
13391bc56edSDimitry Andric     /// Keeps track of non-local addresses that have been sunk into a block.
13491bc56edSDimitry Andric     /// This allows us to avoid inserting duplicate code for blocks with
13591bc56edSDimitry Andric     /// multiple load/stores of the same address.
13691bc56edSDimitry Andric     ValueMap<Value*, Value*> SunkAddrs;
13791bc56edSDimitry Andric 
1388f0fd8f6SDimitry Andric     /// Keeps track of all instructions inserted for the current function.
1398f0fd8f6SDimitry Andric     SetOfInstrs InsertedInsts;
14091bc56edSDimitry Andric     /// Keeps track of the type of the related instruction before their
14191bc56edSDimitry Andric     /// promotion for the current function.
14291bc56edSDimitry Andric     InstrToOrigTy PromotedInsts;
14391bc56edSDimitry Andric 
144ff0cc061SDimitry Andric     /// ModifiedDT - If CFG is modified in anyway.
14591bc56edSDimitry Andric     bool ModifiedDT;
14691bc56edSDimitry Andric 
14791bc56edSDimitry Andric     /// OptSize - True if optimizing for size.
14891bc56edSDimitry Andric     bool OptSize;
14991bc56edSDimitry Andric 
15091bc56edSDimitry Andric   public:
15191bc56edSDimitry Andric     static char ID; // Pass identification, replacement for typeid
15291bc56edSDimitry Andric     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
15339d628a0SDimitry Andric         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
15491bc56edSDimitry Andric         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
15591bc56edSDimitry Andric       }
15691bc56edSDimitry Andric     bool runOnFunction(Function &F) override;
15791bc56edSDimitry Andric 
15891bc56edSDimitry Andric     const char *getPassName() const override { return "CodeGen Prepare"; }
15991bc56edSDimitry Andric 
16091bc56edSDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
16191bc56edSDimitry Andric       AU.addPreserved<DominatorTreeWrapperPass>();
162ff0cc061SDimitry Andric       AU.addRequired<TargetLibraryInfoWrapperPass>();
163ff0cc061SDimitry Andric       AU.addRequired<TargetTransformInfoWrapperPass>();
16491bc56edSDimitry Andric     }
16591bc56edSDimitry Andric 
16691bc56edSDimitry Andric   private:
16791bc56edSDimitry Andric     bool EliminateFallThrough(Function &F);
16891bc56edSDimitry Andric     bool EliminateMostlyEmptyBlocks(Function &F);
16991bc56edSDimitry Andric     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
17091bc56edSDimitry Andric     void EliminateMostlyEmptyBlock(BasicBlock *BB);
17139d628a0SDimitry Andric     bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
17239d628a0SDimitry Andric     bool OptimizeInst(Instruction *I, bool& ModifiedDT);
17397bc6c73SDimitry Andric     bool OptimizeMemoryInst(Instruction *I, Value *Addr,
17497bc6c73SDimitry Andric                             Type *AccessTy, unsigned AS);
17591bc56edSDimitry Andric     bool OptimizeInlineAsmInst(CallInst *CS);
17639d628a0SDimitry Andric     bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
17739d628a0SDimitry Andric     bool MoveExtToFormExtLoad(Instruction *&I);
17891bc56edSDimitry Andric     bool OptimizeExtUses(Instruction *I);
17991bc56edSDimitry Andric     bool OptimizeSelectInst(SelectInst *SI);
18091bc56edSDimitry Andric     bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
18139d628a0SDimitry Andric     bool OptimizeExtractElementInst(Instruction *Inst);
18291bc56edSDimitry Andric     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
18391bc56edSDimitry Andric     bool PlaceDbgValues(Function &F);
18491bc56edSDimitry Andric     bool sinkAndCmp(Function &F);
18539d628a0SDimitry Andric     bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
18639d628a0SDimitry Andric                         Instruction *&Inst,
18739d628a0SDimitry Andric                         const SmallVectorImpl<Instruction *> &Exts,
188ff0cc061SDimitry Andric                         unsigned CreatedInstCost);
18939d628a0SDimitry Andric     bool splitBranchCondition(Function &F);
190ff0cc061SDimitry Andric     bool simplifyOffsetableRelocate(Instruction &I);
19191bc56edSDimitry Andric   };
1923dac3a9bSDimitry Andric }
19391bc56edSDimitry Andric 
19491bc56edSDimitry Andric char CodeGenPrepare::ID = 0;
19591bc56edSDimitry Andric INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
19691bc56edSDimitry Andric                    "Optimize for code generation", false, false)
19791bc56edSDimitry Andric 
19891bc56edSDimitry Andric FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
19991bc56edSDimitry Andric   return new CodeGenPrepare(TM);
20091bc56edSDimitry Andric }
20191bc56edSDimitry Andric 
20291bc56edSDimitry Andric bool CodeGenPrepare::runOnFunction(Function &F) {
20391bc56edSDimitry Andric   if (skipOptnoneFunction(F))
20491bc56edSDimitry Andric     return false;
20591bc56edSDimitry Andric 
20691bc56edSDimitry Andric   bool EverMadeChange = false;
20791bc56edSDimitry Andric   // Clear per function information.
2088f0fd8f6SDimitry Andric   InsertedInsts.clear();
20991bc56edSDimitry Andric   PromotedInsts.clear();
21091bc56edSDimitry Andric 
21191bc56edSDimitry Andric   ModifiedDT = false;
21239d628a0SDimitry Andric   if (TM)
213ff0cc061SDimitry Andric     TLI = TM->getSubtargetImpl(F)->getTargetLowering();
214ff0cc061SDimitry Andric   TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
215ff0cc061SDimitry Andric   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
216ff0cc061SDimitry Andric   OptSize = F.hasFnAttribute(Attribute::OptimizeForSize);
21791bc56edSDimitry Andric 
21891bc56edSDimitry Andric   /// This optimization identifies DIV instructions that can be
21991bc56edSDimitry Andric   /// profitably bypassed and carried out with a shorter, faster divide.
22091bc56edSDimitry Andric   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
22191bc56edSDimitry Andric     const DenseMap<unsigned int, unsigned int> &BypassWidths =
22291bc56edSDimitry Andric        TLI->getBypassSlowDivWidths();
22391bc56edSDimitry Andric     for (Function::iterator I = F.begin(); I != F.end(); I++)
22491bc56edSDimitry Andric       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
22591bc56edSDimitry Andric   }
22691bc56edSDimitry Andric 
22791bc56edSDimitry Andric   // Eliminate blocks that contain only PHI nodes and an
22891bc56edSDimitry Andric   // unconditional branch.
22991bc56edSDimitry Andric   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
23091bc56edSDimitry Andric 
23191bc56edSDimitry Andric   // llvm.dbg.value is far away from the value then iSel may not be able
23291bc56edSDimitry Andric   // handle it properly. iSel will drop llvm.dbg.value if it can not
23391bc56edSDimitry Andric   // find a node corresponding to the value.
23491bc56edSDimitry Andric   EverMadeChange |= PlaceDbgValues(F);
23591bc56edSDimitry Andric 
23691bc56edSDimitry Andric   // If there is a mask, compare against zero, and branch that can be combined
23791bc56edSDimitry Andric   // into a single target instruction, push the mask and compare into branch
23891bc56edSDimitry Andric   // users. Do this before OptimizeBlock -> OptimizeInst ->
23991bc56edSDimitry Andric   // OptimizeCmpExpression, which perturbs the pattern being searched for.
24039d628a0SDimitry Andric   if (!DisableBranchOpts) {
24191bc56edSDimitry Andric     EverMadeChange |= sinkAndCmp(F);
24239d628a0SDimitry Andric     EverMadeChange |= splitBranchCondition(F);
24339d628a0SDimitry Andric   }
24491bc56edSDimitry Andric 
24591bc56edSDimitry Andric   bool MadeChange = true;
24691bc56edSDimitry Andric   while (MadeChange) {
24791bc56edSDimitry Andric     MadeChange = false;
24891bc56edSDimitry Andric     for (Function::iterator I = F.begin(); I != F.end(); ) {
24991bc56edSDimitry Andric       BasicBlock *BB = I++;
25039d628a0SDimitry Andric       bool ModifiedDTOnIteration = false;
25139d628a0SDimitry Andric       MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
25239d628a0SDimitry Andric 
25339d628a0SDimitry Andric       // Restart BB iteration if the dominator tree of the Function was changed
25439d628a0SDimitry Andric       if (ModifiedDTOnIteration)
25539d628a0SDimitry Andric         break;
25691bc56edSDimitry Andric     }
25791bc56edSDimitry Andric     EverMadeChange |= MadeChange;
25891bc56edSDimitry Andric   }
25991bc56edSDimitry Andric 
26091bc56edSDimitry Andric   SunkAddrs.clear();
26191bc56edSDimitry Andric 
26291bc56edSDimitry Andric   if (!DisableBranchOpts) {
26391bc56edSDimitry Andric     MadeChange = false;
26491bc56edSDimitry Andric     SmallPtrSet<BasicBlock*, 8> WorkList;
26539d628a0SDimitry Andric     for (BasicBlock &BB : F) {
26639d628a0SDimitry Andric       SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
26739d628a0SDimitry Andric       MadeChange |= ConstantFoldTerminator(&BB, true);
26891bc56edSDimitry Andric       if (!MadeChange) continue;
26991bc56edSDimitry Andric 
27091bc56edSDimitry Andric       for (SmallVectorImpl<BasicBlock*>::iterator
27191bc56edSDimitry Andric              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
27291bc56edSDimitry Andric         if (pred_begin(*II) == pred_end(*II))
27391bc56edSDimitry Andric           WorkList.insert(*II);
27491bc56edSDimitry Andric     }
27591bc56edSDimitry Andric 
27691bc56edSDimitry Andric     // Delete the dead blocks and any of their dead successors.
27791bc56edSDimitry Andric     MadeChange |= !WorkList.empty();
27891bc56edSDimitry Andric     while (!WorkList.empty()) {
27991bc56edSDimitry Andric       BasicBlock *BB = *WorkList.begin();
28091bc56edSDimitry Andric       WorkList.erase(BB);
28191bc56edSDimitry Andric       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
28291bc56edSDimitry Andric 
28391bc56edSDimitry Andric       DeleteDeadBlock(BB);
28491bc56edSDimitry Andric 
28591bc56edSDimitry Andric       for (SmallVectorImpl<BasicBlock*>::iterator
28691bc56edSDimitry Andric              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
28791bc56edSDimitry Andric         if (pred_begin(*II) == pred_end(*II))
28891bc56edSDimitry Andric           WorkList.insert(*II);
28991bc56edSDimitry Andric     }
29091bc56edSDimitry Andric 
29191bc56edSDimitry Andric     // Merge pairs of basic blocks with unconditional branches, connected by
29291bc56edSDimitry Andric     // a single edge.
29391bc56edSDimitry Andric     if (EverMadeChange || MadeChange)
29491bc56edSDimitry Andric       MadeChange |= EliminateFallThrough(F);
29591bc56edSDimitry Andric 
29691bc56edSDimitry Andric     EverMadeChange |= MadeChange;
29791bc56edSDimitry Andric   }
29891bc56edSDimitry Andric 
299ff0cc061SDimitry Andric   if (!DisableGCOpts) {
300ff0cc061SDimitry Andric     SmallVector<Instruction *, 2> Statepoints;
301ff0cc061SDimitry Andric     for (BasicBlock &BB : F)
302ff0cc061SDimitry Andric       for (Instruction &I : BB)
303ff0cc061SDimitry Andric         if (isStatepoint(I))
304ff0cc061SDimitry Andric           Statepoints.push_back(&I);
305ff0cc061SDimitry Andric     for (auto &I : Statepoints)
306ff0cc061SDimitry Andric       EverMadeChange |= simplifyOffsetableRelocate(*I);
307ff0cc061SDimitry Andric   }
30891bc56edSDimitry Andric 
30991bc56edSDimitry Andric   return EverMadeChange;
31091bc56edSDimitry Andric }
31191bc56edSDimitry Andric 
31291bc56edSDimitry Andric /// EliminateFallThrough - Merge basic blocks which are connected
31391bc56edSDimitry Andric /// by a single edge, where one of the basic blocks has a single successor
31491bc56edSDimitry Andric /// pointing to the other basic block, which has a single predecessor.
31591bc56edSDimitry Andric bool CodeGenPrepare::EliminateFallThrough(Function &F) {
31691bc56edSDimitry Andric   bool Changed = false;
31791bc56edSDimitry Andric   // Scan all of the blocks in the function, except for the entry block.
31891bc56edSDimitry Andric   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
31991bc56edSDimitry Andric     BasicBlock *BB = I++;
32091bc56edSDimitry Andric     // If the destination block has a single pred, then this is a trivial
32191bc56edSDimitry Andric     // edge, just collapse it.
32291bc56edSDimitry Andric     BasicBlock *SinglePred = BB->getSinglePredecessor();
32391bc56edSDimitry Andric 
32491bc56edSDimitry Andric     // Don't merge if BB's address is taken.
32591bc56edSDimitry Andric     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
32691bc56edSDimitry Andric 
32791bc56edSDimitry Andric     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
32891bc56edSDimitry Andric     if (Term && !Term->isConditional()) {
32991bc56edSDimitry Andric       Changed = true;
33091bc56edSDimitry Andric       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
33191bc56edSDimitry Andric       // Remember if SinglePred was the entry block of the function.
33291bc56edSDimitry Andric       // If so, we will need to move BB back to the entry position.
33391bc56edSDimitry Andric       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
334ff0cc061SDimitry Andric       MergeBasicBlockIntoOnlyPred(BB, nullptr);
33591bc56edSDimitry Andric 
33691bc56edSDimitry Andric       if (isEntry && BB != &BB->getParent()->getEntryBlock())
33791bc56edSDimitry Andric         BB->moveBefore(&BB->getParent()->getEntryBlock());
33891bc56edSDimitry Andric 
33991bc56edSDimitry Andric       // We have erased a block. Update the iterator.
34091bc56edSDimitry Andric       I = BB;
34191bc56edSDimitry Andric     }
34291bc56edSDimitry Andric   }
34391bc56edSDimitry Andric   return Changed;
34491bc56edSDimitry Andric }
34591bc56edSDimitry Andric 
34691bc56edSDimitry Andric /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
34791bc56edSDimitry Andric /// debug info directives, and an unconditional branch.  Passes before isel
34891bc56edSDimitry Andric /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
34991bc56edSDimitry Andric /// isel.  Start by eliminating these blocks so we can split them the way we
35091bc56edSDimitry Andric /// want them.
35191bc56edSDimitry Andric bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
35291bc56edSDimitry Andric   bool MadeChange = false;
35391bc56edSDimitry Andric   // Note that this intentionally skips the entry block.
35491bc56edSDimitry Andric   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
35591bc56edSDimitry Andric     BasicBlock *BB = I++;
35691bc56edSDimitry Andric 
35791bc56edSDimitry Andric     // If this block doesn't end with an uncond branch, ignore it.
35891bc56edSDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
35991bc56edSDimitry Andric     if (!BI || !BI->isUnconditional())
36091bc56edSDimitry Andric       continue;
36191bc56edSDimitry Andric 
36291bc56edSDimitry Andric     // If the instruction before the branch (skipping debug info) isn't a phi
36391bc56edSDimitry Andric     // node, then other stuff is happening here.
36491bc56edSDimitry Andric     BasicBlock::iterator BBI = BI;
36591bc56edSDimitry Andric     if (BBI != BB->begin()) {
36691bc56edSDimitry Andric       --BBI;
36791bc56edSDimitry Andric       while (isa<DbgInfoIntrinsic>(BBI)) {
36891bc56edSDimitry Andric         if (BBI == BB->begin())
36991bc56edSDimitry Andric           break;
37091bc56edSDimitry Andric         --BBI;
37191bc56edSDimitry Andric       }
37291bc56edSDimitry Andric       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
37391bc56edSDimitry Andric         continue;
37491bc56edSDimitry Andric     }
37591bc56edSDimitry Andric 
37691bc56edSDimitry Andric     // Do not break infinite loops.
37791bc56edSDimitry Andric     BasicBlock *DestBB = BI->getSuccessor(0);
37891bc56edSDimitry Andric     if (DestBB == BB)
37991bc56edSDimitry Andric       continue;
38091bc56edSDimitry Andric 
38191bc56edSDimitry Andric     if (!CanMergeBlocks(BB, DestBB))
38291bc56edSDimitry Andric       continue;
38391bc56edSDimitry Andric 
38491bc56edSDimitry Andric     EliminateMostlyEmptyBlock(BB);
38591bc56edSDimitry Andric     MadeChange = true;
38691bc56edSDimitry Andric   }
38791bc56edSDimitry Andric   return MadeChange;
38891bc56edSDimitry Andric }
38991bc56edSDimitry Andric 
39091bc56edSDimitry Andric /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
39191bc56edSDimitry Andric /// single uncond branch between them, and BB contains no other non-phi
39291bc56edSDimitry Andric /// instructions.
39391bc56edSDimitry Andric bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
39491bc56edSDimitry Andric                                     const BasicBlock *DestBB) const {
39591bc56edSDimitry Andric   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
39691bc56edSDimitry Andric   // the successor.  If there are more complex condition (e.g. preheaders),
39791bc56edSDimitry Andric   // don't mess around with them.
39891bc56edSDimitry Andric   BasicBlock::const_iterator BBI = BB->begin();
39991bc56edSDimitry Andric   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
40091bc56edSDimitry Andric     for (const User *U : PN->users()) {
40191bc56edSDimitry Andric       const Instruction *UI = cast<Instruction>(U);
40291bc56edSDimitry Andric       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
40391bc56edSDimitry Andric         return false;
40491bc56edSDimitry Andric       // If User is inside DestBB block and it is a PHINode then check
40591bc56edSDimitry Andric       // incoming value. If incoming value is not from BB then this is
40691bc56edSDimitry Andric       // a complex condition (e.g. preheaders) we want to avoid here.
40791bc56edSDimitry Andric       if (UI->getParent() == DestBB) {
40891bc56edSDimitry Andric         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
40991bc56edSDimitry Andric           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
41091bc56edSDimitry Andric             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
41191bc56edSDimitry Andric             if (Insn && Insn->getParent() == BB &&
41291bc56edSDimitry Andric                 Insn->getParent() != UPN->getIncomingBlock(I))
41391bc56edSDimitry Andric               return false;
41491bc56edSDimitry Andric           }
41591bc56edSDimitry Andric       }
41691bc56edSDimitry Andric     }
41791bc56edSDimitry Andric   }
41891bc56edSDimitry Andric 
41991bc56edSDimitry Andric   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
42091bc56edSDimitry Andric   // and DestBB may have conflicting incoming values for the block.  If so, we
42191bc56edSDimitry Andric   // can't merge the block.
42291bc56edSDimitry Andric   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
42391bc56edSDimitry Andric   if (!DestBBPN) return true;  // no conflict.
42491bc56edSDimitry Andric 
42591bc56edSDimitry Andric   // Collect the preds of BB.
42691bc56edSDimitry Andric   SmallPtrSet<const BasicBlock*, 16> BBPreds;
42791bc56edSDimitry Andric   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
42891bc56edSDimitry Andric     // It is faster to get preds from a PHI than with pred_iterator.
42991bc56edSDimitry Andric     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
43091bc56edSDimitry Andric       BBPreds.insert(BBPN->getIncomingBlock(i));
43191bc56edSDimitry Andric   } else {
43291bc56edSDimitry Andric     BBPreds.insert(pred_begin(BB), pred_end(BB));
43391bc56edSDimitry Andric   }
43491bc56edSDimitry Andric 
43591bc56edSDimitry Andric   // Walk the preds of DestBB.
43691bc56edSDimitry Andric   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
43791bc56edSDimitry Andric     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
43891bc56edSDimitry Andric     if (BBPreds.count(Pred)) {   // Common predecessor?
43991bc56edSDimitry Andric       BBI = DestBB->begin();
44091bc56edSDimitry Andric       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
44191bc56edSDimitry Andric         const Value *V1 = PN->getIncomingValueForBlock(Pred);
44291bc56edSDimitry Andric         const Value *V2 = PN->getIncomingValueForBlock(BB);
44391bc56edSDimitry Andric 
44491bc56edSDimitry Andric         // If V2 is a phi node in BB, look up what the mapped value will be.
44591bc56edSDimitry Andric         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
44691bc56edSDimitry Andric           if (V2PN->getParent() == BB)
44791bc56edSDimitry Andric             V2 = V2PN->getIncomingValueForBlock(Pred);
44891bc56edSDimitry Andric 
44991bc56edSDimitry Andric         // If there is a conflict, bail out.
45091bc56edSDimitry Andric         if (V1 != V2) return false;
45191bc56edSDimitry Andric       }
45291bc56edSDimitry Andric     }
45391bc56edSDimitry Andric   }
45491bc56edSDimitry Andric 
45591bc56edSDimitry Andric   return true;
45691bc56edSDimitry Andric }
45791bc56edSDimitry Andric 
45891bc56edSDimitry Andric 
45991bc56edSDimitry Andric /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
46091bc56edSDimitry Andric /// an unconditional branch in it.
46191bc56edSDimitry Andric void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
46291bc56edSDimitry Andric   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
46391bc56edSDimitry Andric   BasicBlock *DestBB = BI->getSuccessor(0);
46491bc56edSDimitry Andric 
46591bc56edSDimitry Andric   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
46691bc56edSDimitry Andric 
46791bc56edSDimitry Andric   // If the destination block has a single pred, then this is a trivial edge,
46891bc56edSDimitry Andric   // just collapse it.
46991bc56edSDimitry Andric   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
47091bc56edSDimitry Andric     if (SinglePred != DestBB) {
47191bc56edSDimitry Andric       // Remember if SinglePred was the entry block of the function.  If so, we
47291bc56edSDimitry Andric       // will need to move BB back to the entry position.
47391bc56edSDimitry Andric       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
474ff0cc061SDimitry Andric       MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
47591bc56edSDimitry Andric 
47691bc56edSDimitry Andric       if (isEntry && BB != &BB->getParent()->getEntryBlock())
47791bc56edSDimitry Andric         BB->moveBefore(&BB->getParent()->getEntryBlock());
47891bc56edSDimitry Andric 
47991bc56edSDimitry Andric       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
48091bc56edSDimitry Andric       return;
48191bc56edSDimitry Andric     }
48291bc56edSDimitry Andric   }
48391bc56edSDimitry Andric 
48491bc56edSDimitry Andric   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
48591bc56edSDimitry Andric   // to handle the new incoming edges it is about to have.
48691bc56edSDimitry Andric   PHINode *PN;
48791bc56edSDimitry Andric   for (BasicBlock::iterator BBI = DestBB->begin();
48891bc56edSDimitry Andric        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
48991bc56edSDimitry Andric     // Remove the incoming value for BB, and remember it.
49091bc56edSDimitry Andric     Value *InVal = PN->removeIncomingValue(BB, false);
49191bc56edSDimitry Andric 
49291bc56edSDimitry Andric     // Two options: either the InVal is a phi node defined in BB or it is some
49391bc56edSDimitry Andric     // value that dominates BB.
49491bc56edSDimitry Andric     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
49591bc56edSDimitry Andric     if (InValPhi && InValPhi->getParent() == BB) {
49691bc56edSDimitry Andric       // Add all of the input values of the input PHI as inputs of this phi.
49791bc56edSDimitry Andric       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
49891bc56edSDimitry Andric         PN->addIncoming(InValPhi->getIncomingValue(i),
49991bc56edSDimitry Andric                         InValPhi->getIncomingBlock(i));
50091bc56edSDimitry Andric     } else {
50191bc56edSDimitry Andric       // Otherwise, add one instance of the dominating value for each edge that
50291bc56edSDimitry Andric       // we will be adding.
50391bc56edSDimitry Andric       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
50491bc56edSDimitry Andric         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
50591bc56edSDimitry Andric           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
50691bc56edSDimitry Andric       } else {
50791bc56edSDimitry Andric         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
50891bc56edSDimitry Andric           PN->addIncoming(InVal, *PI);
50991bc56edSDimitry Andric       }
51091bc56edSDimitry Andric     }
51191bc56edSDimitry Andric   }
51291bc56edSDimitry Andric 
51391bc56edSDimitry Andric   // The PHIs are now updated, change everything that refers to BB to use
51491bc56edSDimitry Andric   // DestBB and remove BB.
51591bc56edSDimitry Andric   BB->replaceAllUsesWith(DestBB);
51691bc56edSDimitry Andric   BB->eraseFromParent();
51791bc56edSDimitry Andric   ++NumBlocksElim;
51891bc56edSDimitry Andric 
51991bc56edSDimitry Andric   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
52091bc56edSDimitry Andric }
52191bc56edSDimitry Andric 
522ff0cc061SDimitry Andric // Computes a map of base pointer relocation instructions to corresponding
523ff0cc061SDimitry Andric // derived pointer relocation instructions given a vector of all relocate calls
524ff0cc061SDimitry Andric static void computeBaseDerivedRelocateMap(
525ff0cc061SDimitry Andric     const SmallVectorImpl<User *> &AllRelocateCalls,
526ff0cc061SDimitry Andric     DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
527ff0cc061SDimitry Andric         RelocateInstMap) {
528ff0cc061SDimitry Andric   // Collect information in two maps: one primarily for locating the base object
529ff0cc061SDimitry Andric   // while filling the second map; the second map is the final structure holding
530ff0cc061SDimitry Andric   // a mapping between Base and corresponding Derived relocate calls
531ff0cc061SDimitry Andric   DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
532ff0cc061SDimitry Andric   for (auto &U : AllRelocateCalls) {
533ff0cc061SDimitry Andric     GCRelocateOperands ThisRelocate(U);
534ff0cc061SDimitry Andric     IntrinsicInst *I = cast<IntrinsicInst>(U);
535ff0cc061SDimitry Andric     auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
536ff0cc061SDimitry Andric                             ThisRelocate.getDerivedPtrIndex());
537ff0cc061SDimitry Andric     RelocateIdxMap.insert(std::make_pair(K, I));
538ff0cc061SDimitry Andric   }
539ff0cc061SDimitry Andric   for (auto &Item : RelocateIdxMap) {
540ff0cc061SDimitry Andric     std::pair<unsigned, unsigned> Key = Item.first;
541ff0cc061SDimitry Andric     if (Key.first == Key.second)
542ff0cc061SDimitry Andric       // Base relocation: nothing to insert
543ff0cc061SDimitry Andric       continue;
544ff0cc061SDimitry Andric 
545ff0cc061SDimitry Andric     IntrinsicInst *I = Item.second;
546ff0cc061SDimitry Andric     auto BaseKey = std::make_pair(Key.first, Key.first);
547ff0cc061SDimitry Andric 
548ff0cc061SDimitry Andric     // We're iterating over RelocateIdxMap so we cannot modify it.
549ff0cc061SDimitry Andric     auto MaybeBase = RelocateIdxMap.find(BaseKey);
550ff0cc061SDimitry Andric     if (MaybeBase == RelocateIdxMap.end())
551ff0cc061SDimitry Andric       // TODO: We might want to insert a new base object relocate and gep off
552ff0cc061SDimitry Andric       // that, if there are enough derived object relocates.
553ff0cc061SDimitry Andric       continue;
554ff0cc061SDimitry Andric 
555ff0cc061SDimitry Andric     RelocateInstMap[MaybeBase->second].push_back(I);
556ff0cc061SDimitry Andric   }
557ff0cc061SDimitry Andric }
558ff0cc061SDimitry Andric 
559ff0cc061SDimitry Andric // Accepts a GEP and extracts the operands into a vector provided they're all
560ff0cc061SDimitry Andric // small integer constants
561ff0cc061SDimitry Andric static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
562ff0cc061SDimitry Andric                                           SmallVectorImpl<Value *> &OffsetV) {
563ff0cc061SDimitry Andric   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
564ff0cc061SDimitry Andric     // Only accept small constant integer operands
565ff0cc061SDimitry Andric     auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
566ff0cc061SDimitry Andric     if (!Op || Op->getZExtValue() > 20)
567ff0cc061SDimitry Andric       return false;
568ff0cc061SDimitry Andric   }
569ff0cc061SDimitry Andric 
570ff0cc061SDimitry Andric   for (unsigned i = 1; i < GEP->getNumOperands(); i++)
571ff0cc061SDimitry Andric     OffsetV.push_back(GEP->getOperand(i));
572ff0cc061SDimitry Andric   return true;
573ff0cc061SDimitry Andric }
574ff0cc061SDimitry Andric 
575ff0cc061SDimitry Andric // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
576ff0cc061SDimitry Andric // replace, computes a replacement, and affects it.
577ff0cc061SDimitry Andric static bool
578ff0cc061SDimitry Andric simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
579ff0cc061SDimitry Andric                           const SmallVectorImpl<IntrinsicInst *> &Targets) {
580ff0cc061SDimitry Andric   bool MadeChange = false;
581ff0cc061SDimitry Andric   for (auto &ToReplace : Targets) {
582ff0cc061SDimitry Andric     GCRelocateOperands MasterRelocate(RelocatedBase);
583ff0cc061SDimitry Andric     GCRelocateOperands ThisRelocate(ToReplace);
584ff0cc061SDimitry Andric 
585ff0cc061SDimitry Andric     assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
586ff0cc061SDimitry Andric            "Not relocating a derived object of the original base object");
587ff0cc061SDimitry Andric     if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
588ff0cc061SDimitry Andric       // A duplicate relocate call. TODO: coalesce duplicates.
589ff0cc061SDimitry Andric       continue;
590ff0cc061SDimitry Andric     }
591ff0cc061SDimitry Andric 
592ff0cc061SDimitry Andric     Value *Base = ThisRelocate.getBasePtr();
593ff0cc061SDimitry Andric     auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
594ff0cc061SDimitry Andric     if (!Derived || Derived->getPointerOperand() != Base)
595ff0cc061SDimitry Andric       continue;
596ff0cc061SDimitry Andric 
597ff0cc061SDimitry Andric     SmallVector<Value *, 2> OffsetV;
598ff0cc061SDimitry Andric     if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
599ff0cc061SDimitry Andric       continue;
600ff0cc061SDimitry Andric 
601ff0cc061SDimitry Andric     // Create a Builder and replace the target callsite with a gep
602ff0cc061SDimitry Andric     assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
603ff0cc061SDimitry Andric 
604ff0cc061SDimitry Andric     // Insert after RelocatedBase
605ff0cc061SDimitry Andric     IRBuilder<> Builder(RelocatedBase->getNextNode());
606ff0cc061SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
607ff0cc061SDimitry Andric 
608ff0cc061SDimitry Andric     // If gc_relocate does not match the actual type, cast it to the right type.
609ff0cc061SDimitry Andric     // In theory, there must be a bitcast after gc_relocate if the type does not
610ff0cc061SDimitry Andric     // match, and we should reuse it to get the derived pointer. But it could be
611ff0cc061SDimitry Andric     // cases like this:
612ff0cc061SDimitry Andric     // bb1:
613ff0cc061SDimitry Andric     //  ...
614ff0cc061SDimitry Andric     //  %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
615ff0cc061SDimitry Andric     //  br label %merge
616ff0cc061SDimitry Andric     //
617ff0cc061SDimitry Andric     // bb2:
618ff0cc061SDimitry Andric     //  ...
619ff0cc061SDimitry Andric     //  %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
620ff0cc061SDimitry Andric     //  br label %merge
621ff0cc061SDimitry Andric     //
622ff0cc061SDimitry Andric     // merge:
623ff0cc061SDimitry Andric     //  %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
624ff0cc061SDimitry Andric     //  %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
625ff0cc061SDimitry Andric     //
626ff0cc061SDimitry Andric     // In this case, we can not find the bitcast any more. So we insert a new bitcast
627ff0cc061SDimitry Andric     // no matter there is already one or not. In this way, we can handle all cases, and
628ff0cc061SDimitry Andric     // the extra bitcast should be optimized away in later passes.
629ff0cc061SDimitry Andric     Instruction *ActualRelocatedBase = RelocatedBase;
630ff0cc061SDimitry Andric     if (RelocatedBase->getType() != Base->getType()) {
631ff0cc061SDimitry Andric       ActualRelocatedBase =
632ff0cc061SDimitry Andric           cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
633ff0cc061SDimitry Andric     }
634ff0cc061SDimitry Andric     Value *Replacement = Builder.CreateGEP(
635ff0cc061SDimitry Andric         Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
636ff0cc061SDimitry Andric     Instruction *ReplacementInst = cast<Instruction>(Replacement);
637ff0cc061SDimitry Andric     Replacement->takeName(ToReplace);
638ff0cc061SDimitry Andric     // If the newly generated derived pointer's type does not match the original derived
639ff0cc061SDimitry Andric     // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
640ff0cc061SDimitry Andric     Instruction *ActualReplacement = ReplacementInst;
641ff0cc061SDimitry Andric     if (ReplacementInst->getType() != ToReplace->getType()) {
642ff0cc061SDimitry Andric       ActualReplacement =
643ff0cc061SDimitry Andric           cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
644ff0cc061SDimitry Andric     }
645ff0cc061SDimitry Andric     ToReplace->replaceAllUsesWith(ActualReplacement);
646ff0cc061SDimitry Andric     ToReplace->eraseFromParent();
647ff0cc061SDimitry Andric 
648ff0cc061SDimitry Andric     MadeChange = true;
649ff0cc061SDimitry Andric   }
650ff0cc061SDimitry Andric   return MadeChange;
651ff0cc061SDimitry Andric }
652ff0cc061SDimitry Andric 
653ff0cc061SDimitry Andric // Turns this:
654ff0cc061SDimitry Andric //
655ff0cc061SDimitry Andric // %base = ...
656ff0cc061SDimitry Andric // %ptr = gep %base + 15
657ff0cc061SDimitry Andric // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
658ff0cc061SDimitry Andric // %base' = relocate(%tok, i32 4, i32 4)
659ff0cc061SDimitry Andric // %ptr' = relocate(%tok, i32 4, i32 5)
660ff0cc061SDimitry Andric // %val = load %ptr'
661ff0cc061SDimitry Andric //
662ff0cc061SDimitry Andric // into this:
663ff0cc061SDimitry Andric //
664ff0cc061SDimitry Andric // %base = ...
665ff0cc061SDimitry Andric // %ptr = gep %base + 15
666ff0cc061SDimitry Andric // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
667ff0cc061SDimitry Andric // %base' = gc.relocate(%tok, i32 4, i32 4)
668ff0cc061SDimitry Andric // %ptr' = gep %base' + 15
669ff0cc061SDimitry Andric // %val = load %ptr'
670ff0cc061SDimitry Andric bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
671ff0cc061SDimitry Andric   bool MadeChange = false;
672ff0cc061SDimitry Andric   SmallVector<User *, 2> AllRelocateCalls;
673ff0cc061SDimitry Andric 
674ff0cc061SDimitry Andric   for (auto *U : I.users())
675ff0cc061SDimitry Andric     if (isGCRelocate(dyn_cast<Instruction>(U)))
676ff0cc061SDimitry Andric       // Collect all the relocate calls associated with a statepoint
677ff0cc061SDimitry Andric       AllRelocateCalls.push_back(U);
678ff0cc061SDimitry Andric 
679ff0cc061SDimitry Andric   // We need atleast one base pointer relocation + one derived pointer
680ff0cc061SDimitry Andric   // relocation to mangle
681ff0cc061SDimitry Andric   if (AllRelocateCalls.size() < 2)
682ff0cc061SDimitry Andric     return false;
683ff0cc061SDimitry Andric 
684ff0cc061SDimitry Andric   // RelocateInstMap is a mapping from the base relocate instruction to the
685ff0cc061SDimitry Andric   // corresponding derived relocate instructions
686ff0cc061SDimitry Andric   DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
687ff0cc061SDimitry Andric   computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
688ff0cc061SDimitry Andric   if (RelocateInstMap.empty())
689ff0cc061SDimitry Andric     return false;
690ff0cc061SDimitry Andric 
691ff0cc061SDimitry Andric   for (auto &Item : RelocateInstMap)
692ff0cc061SDimitry Andric     // Item.first is the RelocatedBase to offset against
693ff0cc061SDimitry Andric     // Item.second is the vector of Targets to replace
694ff0cc061SDimitry Andric     MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
695ff0cc061SDimitry Andric   return MadeChange;
696ff0cc061SDimitry Andric }
697ff0cc061SDimitry Andric 
69891bc56edSDimitry Andric /// SinkCast - Sink the specified cast instruction into its user blocks
69991bc56edSDimitry Andric static bool SinkCast(CastInst *CI) {
70091bc56edSDimitry Andric   BasicBlock *DefBB = CI->getParent();
70191bc56edSDimitry Andric 
70291bc56edSDimitry Andric   /// InsertedCasts - Only insert a cast in each block once.
70391bc56edSDimitry Andric   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
70491bc56edSDimitry Andric 
70591bc56edSDimitry Andric   bool MadeChange = false;
70691bc56edSDimitry Andric   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
70791bc56edSDimitry Andric        UI != E; ) {
70891bc56edSDimitry Andric     Use &TheUse = UI.getUse();
70991bc56edSDimitry Andric     Instruction *User = cast<Instruction>(*UI);
71091bc56edSDimitry Andric 
71191bc56edSDimitry Andric     // Figure out which BB this cast is used in.  For PHI's this is the
71291bc56edSDimitry Andric     // appropriate predecessor block.
71391bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
71491bc56edSDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(User)) {
71591bc56edSDimitry Andric       UserBB = PN->getIncomingBlock(TheUse);
71691bc56edSDimitry Andric     }
71791bc56edSDimitry Andric 
71891bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
71991bc56edSDimitry Andric     ++UI;
72091bc56edSDimitry Andric 
72191bc56edSDimitry Andric     // If this user is in the same block as the cast, don't change the cast.
72291bc56edSDimitry Andric     if (UserBB == DefBB) continue;
72391bc56edSDimitry Andric 
72491bc56edSDimitry Andric     // If we have already inserted a cast into this block, use it.
72591bc56edSDimitry Andric     CastInst *&InsertedCast = InsertedCasts[UserBB];
72691bc56edSDimitry Andric 
72791bc56edSDimitry Andric     if (!InsertedCast) {
72891bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
72991bc56edSDimitry Andric       InsertedCast =
73091bc56edSDimitry Andric         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
73191bc56edSDimitry Andric                          InsertPt);
73291bc56edSDimitry Andric     }
73391bc56edSDimitry Andric 
73491bc56edSDimitry Andric     // Replace a use of the cast with a use of the new cast.
73591bc56edSDimitry Andric     TheUse = InsertedCast;
736ff0cc061SDimitry Andric     MadeChange = true;
73791bc56edSDimitry Andric     ++NumCastUses;
73891bc56edSDimitry Andric   }
73991bc56edSDimitry Andric 
74091bc56edSDimitry Andric   // If we removed all uses, nuke the cast.
74191bc56edSDimitry Andric   if (CI->use_empty()) {
74291bc56edSDimitry Andric     CI->eraseFromParent();
74391bc56edSDimitry Andric     MadeChange = true;
74491bc56edSDimitry Andric   }
74591bc56edSDimitry Andric 
74691bc56edSDimitry Andric   return MadeChange;
74791bc56edSDimitry Andric }
74891bc56edSDimitry Andric 
74991bc56edSDimitry Andric /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
75091bc56edSDimitry Andric /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
75191bc56edSDimitry Andric /// sink it into user blocks to reduce the number of virtual
75291bc56edSDimitry Andric /// registers that must be created and coalesced.
75391bc56edSDimitry Andric ///
75491bc56edSDimitry Andric /// Return true if any changes are made.
75591bc56edSDimitry Andric ///
75691bc56edSDimitry Andric static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
75791bc56edSDimitry Andric   // If this is a noop copy,
75891bc56edSDimitry Andric   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
75991bc56edSDimitry Andric   EVT DstVT = TLI.getValueType(CI->getType());
76091bc56edSDimitry Andric 
76191bc56edSDimitry Andric   // This is an fp<->int conversion?
76291bc56edSDimitry Andric   if (SrcVT.isInteger() != DstVT.isInteger())
76391bc56edSDimitry Andric     return false;
76491bc56edSDimitry Andric 
76591bc56edSDimitry Andric   // If this is an extension, it will be a zero or sign extension, which
76691bc56edSDimitry Andric   // isn't a noop.
76791bc56edSDimitry Andric   if (SrcVT.bitsLT(DstVT)) return false;
76891bc56edSDimitry Andric 
76991bc56edSDimitry Andric   // If these values will be promoted, find out what they will be promoted
77091bc56edSDimitry Andric   // to.  This helps us consider truncates on PPC as noop copies when they
77191bc56edSDimitry Andric   // are.
77291bc56edSDimitry Andric   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
77391bc56edSDimitry Andric       TargetLowering::TypePromoteInteger)
77491bc56edSDimitry Andric     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
77591bc56edSDimitry Andric   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
77691bc56edSDimitry Andric       TargetLowering::TypePromoteInteger)
77791bc56edSDimitry Andric     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
77891bc56edSDimitry Andric 
77991bc56edSDimitry Andric   // If, after promotion, these are the same types, this is a noop copy.
78091bc56edSDimitry Andric   if (SrcVT != DstVT)
78191bc56edSDimitry Andric     return false;
78291bc56edSDimitry Andric 
78391bc56edSDimitry Andric   return SinkCast(CI);
78491bc56edSDimitry Andric }
78591bc56edSDimitry Andric 
786ff0cc061SDimitry Andric /// CombineUAddWithOverflow - try to combine CI into a call to the
787ff0cc061SDimitry Andric /// llvm.uadd.with.overflow intrinsic if possible.
788ff0cc061SDimitry Andric ///
789ff0cc061SDimitry Andric /// Return true if any changes were made.
790ff0cc061SDimitry Andric static bool CombineUAddWithOverflow(CmpInst *CI) {
791ff0cc061SDimitry Andric   Value *A, *B;
792ff0cc061SDimitry Andric   Instruction *AddI;
793ff0cc061SDimitry Andric   if (!match(CI,
794ff0cc061SDimitry Andric              m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
795ff0cc061SDimitry Andric     return false;
796ff0cc061SDimitry Andric 
797ff0cc061SDimitry Andric   Type *Ty = AddI->getType();
798ff0cc061SDimitry Andric   if (!isa<IntegerType>(Ty))
799ff0cc061SDimitry Andric     return false;
800ff0cc061SDimitry Andric 
801ff0cc061SDimitry Andric   // We don't want to move around uses of condition values this late, so we we
802ff0cc061SDimitry Andric   // check if it is legal to create the call to the intrinsic in the basic
803ff0cc061SDimitry Andric   // block containing the icmp:
804ff0cc061SDimitry Andric 
805ff0cc061SDimitry Andric   if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
806ff0cc061SDimitry Andric     return false;
807ff0cc061SDimitry Andric 
808ff0cc061SDimitry Andric #ifndef NDEBUG
809ff0cc061SDimitry Andric   // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
810ff0cc061SDimitry Andric   // for now:
811ff0cc061SDimitry Andric   if (AddI->hasOneUse())
812ff0cc061SDimitry Andric     assert(*AddI->user_begin() == CI && "expected!");
813ff0cc061SDimitry Andric #endif
814ff0cc061SDimitry Andric 
815ff0cc061SDimitry Andric   Module *M = CI->getParent()->getParent()->getParent();
816ff0cc061SDimitry Andric   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
817ff0cc061SDimitry Andric 
818ff0cc061SDimitry Andric   auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
819ff0cc061SDimitry Andric 
820ff0cc061SDimitry Andric   auto *UAddWithOverflow =
821ff0cc061SDimitry Andric       CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
822ff0cc061SDimitry Andric   auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
823ff0cc061SDimitry Andric   auto *Overflow =
824ff0cc061SDimitry Andric       ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
825ff0cc061SDimitry Andric 
826ff0cc061SDimitry Andric   CI->replaceAllUsesWith(Overflow);
827ff0cc061SDimitry Andric   AddI->replaceAllUsesWith(UAdd);
828ff0cc061SDimitry Andric   CI->eraseFromParent();
829ff0cc061SDimitry Andric   AddI->eraseFromParent();
830ff0cc061SDimitry Andric   return true;
831ff0cc061SDimitry Andric }
832ff0cc061SDimitry Andric 
833ff0cc061SDimitry Andric /// SinkCmpExpression - Sink the given CmpInst into user blocks to reduce
83491bc56edSDimitry Andric /// the number of virtual registers that must be created and coalesced.  This is
83591bc56edSDimitry Andric /// a clear win except on targets with multiple condition code registers
83691bc56edSDimitry Andric ///  (PowerPC), where it might lose; some adjustment may be wanted there.
83791bc56edSDimitry Andric ///
83891bc56edSDimitry Andric /// Return true if any changes are made.
839ff0cc061SDimitry Andric static bool SinkCmpExpression(CmpInst *CI) {
84091bc56edSDimitry Andric   BasicBlock *DefBB = CI->getParent();
84191bc56edSDimitry Andric 
84291bc56edSDimitry Andric   /// InsertedCmp - Only insert a cmp in each block once.
84391bc56edSDimitry Andric   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
84491bc56edSDimitry Andric 
84591bc56edSDimitry Andric   bool MadeChange = false;
84691bc56edSDimitry Andric   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
84791bc56edSDimitry Andric        UI != E; ) {
84891bc56edSDimitry Andric     Use &TheUse = UI.getUse();
84991bc56edSDimitry Andric     Instruction *User = cast<Instruction>(*UI);
85091bc56edSDimitry Andric 
85191bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
85291bc56edSDimitry Andric     ++UI;
85391bc56edSDimitry Andric 
85491bc56edSDimitry Andric     // Don't bother for PHI nodes.
85591bc56edSDimitry Andric     if (isa<PHINode>(User))
85691bc56edSDimitry Andric       continue;
85791bc56edSDimitry Andric 
85891bc56edSDimitry Andric     // Figure out which BB this cmp is used in.
85991bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
86091bc56edSDimitry Andric 
86191bc56edSDimitry Andric     // If this user is in the same block as the cmp, don't change the cmp.
86291bc56edSDimitry Andric     if (UserBB == DefBB) continue;
86391bc56edSDimitry Andric 
86491bc56edSDimitry Andric     // If we have already inserted a cmp into this block, use it.
86591bc56edSDimitry Andric     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
86691bc56edSDimitry Andric 
86791bc56edSDimitry Andric     if (!InsertedCmp) {
86891bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
86991bc56edSDimitry Andric       InsertedCmp =
87091bc56edSDimitry Andric         CmpInst::Create(CI->getOpcode(),
87191bc56edSDimitry Andric                         CI->getPredicate(),  CI->getOperand(0),
87291bc56edSDimitry Andric                         CI->getOperand(1), "", InsertPt);
87391bc56edSDimitry Andric     }
87491bc56edSDimitry Andric 
87591bc56edSDimitry Andric     // Replace a use of the cmp with a use of the new cmp.
87691bc56edSDimitry Andric     TheUse = InsertedCmp;
877ff0cc061SDimitry Andric     MadeChange = true;
87891bc56edSDimitry Andric     ++NumCmpUses;
87991bc56edSDimitry Andric   }
88091bc56edSDimitry Andric 
88191bc56edSDimitry Andric   // If we removed all uses, nuke the cmp.
882ff0cc061SDimitry Andric   if (CI->use_empty()) {
88391bc56edSDimitry Andric     CI->eraseFromParent();
884ff0cc061SDimitry Andric     MadeChange = true;
885ff0cc061SDimitry Andric   }
88691bc56edSDimitry Andric 
88791bc56edSDimitry Andric   return MadeChange;
88891bc56edSDimitry Andric }
88991bc56edSDimitry Andric 
890ff0cc061SDimitry Andric static bool OptimizeCmpExpression(CmpInst *CI) {
891ff0cc061SDimitry Andric   if (SinkCmpExpression(CI))
892ff0cc061SDimitry Andric     return true;
893ff0cc061SDimitry Andric 
894ff0cc061SDimitry Andric   if (CombineUAddWithOverflow(CI))
895ff0cc061SDimitry Andric     return true;
896ff0cc061SDimitry Andric 
897ff0cc061SDimitry Andric   return false;
898ff0cc061SDimitry Andric }
899ff0cc061SDimitry Andric 
90091bc56edSDimitry Andric /// isExtractBitsCandidateUse - Check if the candidates could
90191bc56edSDimitry Andric /// be combined with shift instruction, which includes:
90291bc56edSDimitry Andric /// 1. Truncate instruction
90391bc56edSDimitry Andric /// 2. And instruction and the imm is a mask of the low bits:
90491bc56edSDimitry Andric /// imm & (imm+1) == 0
90591bc56edSDimitry Andric static bool isExtractBitsCandidateUse(Instruction *User) {
90691bc56edSDimitry Andric   if (!isa<TruncInst>(User)) {
90791bc56edSDimitry Andric     if (User->getOpcode() != Instruction::And ||
90891bc56edSDimitry Andric         !isa<ConstantInt>(User->getOperand(1)))
90991bc56edSDimitry Andric       return false;
91091bc56edSDimitry Andric 
91191bc56edSDimitry Andric     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
91291bc56edSDimitry Andric 
91391bc56edSDimitry Andric     if ((Cimm & (Cimm + 1)).getBoolValue())
91491bc56edSDimitry Andric       return false;
91591bc56edSDimitry Andric   }
91691bc56edSDimitry Andric   return true;
91791bc56edSDimitry Andric }
91891bc56edSDimitry Andric 
91991bc56edSDimitry Andric /// SinkShiftAndTruncate - sink both shift and truncate instruction
92091bc56edSDimitry Andric /// to the use of truncate's BB.
92191bc56edSDimitry Andric static bool
92291bc56edSDimitry Andric SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
92391bc56edSDimitry Andric                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
92491bc56edSDimitry Andric                      const TargetLowering &TLI) {
92591bc56edSDimitry Andric   BasicBlock *UserBB = User->getParent();
92691bc56edSDimitry Andric   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
92791bc56edSDimitry Andric   TruncInst *TruncI = dyn_cast<TruncInst>(User);
92891bc56edSDimitry Andric   bool MadeChange = false;
92991bc56edSDimitry Andric 
93091bc56edSDimitry Andric   for (Value::user_iterator TruncUI = TruncI->user_begin(),
93191bc56edSDimitry Andric                             TruncE = TruncI->user_end();
93291bc56edSDimitry Andric        TruncUI != TruncE;) {
93391bc56edSDimitry Andric 
93491bc56edSDimitry Andric     Use &TruncTheUse = TruncUI.getUse();
93591bc56edSDimitry Andric     Instruction *TruncUser = cast<Instruction>(*TruncUI);
93691bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
93791bc56edSDimitry Andric 
93891bc56edSDimitry Andric     ++TruncUI;
93991bc56edSDimitry Andric 
94091bc56edSDimitry Andric     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
94191bc56edSDimitry Andric     if (!ISDOpcode)
94291bc56edSDimitry Andric       continue;
94391bc56edSDimitry Andric 
94439d628a0SDimitry Andric     // If the use is actually a legal node, there will not be an
94539d628a0SDimitry Andric     // implicit truncate.
94639d628a0SDimitry Andric     // FIXME: always querying the result type is just an
94739d628a0SDimitry Andric     // approximation; some nodes' legality is determined by the
94839d628a0SDimitry Andric     // operand or other means. There's no good way to find out though.
94939d628a0SDimitry Andric     if (TLI.isOperationLegalOrCustom(
95039d628a0SDimitry Andric             ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
95191bc56edSDimitry Andric       continue;
95291bc56edSDimitry Andric 
95391bc56edSDimitry Andric     // Don't bother for PHI nodes.
95491bc56edSDimitry Andric     if (isa<PHINode>(TruncUser))
95591bc56edSDimitry Andric       continue;
95691bc56edSDimitry Andric 
95791bc56edSDimitry Andric     BasicBlock *TruncUserBB = TruncUser->getParent();
95891bc56edSDimitry Andric 
95991bc56edSDimitry Andric     if (UserBB == TruncUserBB)
96091bc56edSDimitry Andric       continue;
96191bc56edSDimitry Andric 
96291bc56edSDimitry Andric     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
96391bc56edSDimitry Andric     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
96491bc56edSDimitry Andric 
96591bc56edSDimitry Andric     if (!InsertedShift && !InsertedTrunc) {
96691bc56edSDimitry Andric       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
96791bc56edSDimitry Andric       // Sink the shift
96891bc56edSDimitry Andric       if (ShiftI->getOpcode() == Instruction::AShr)
96991bc56edSDimitry Andric         InsertedShift =
97091bc56edSDimitry Andric             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
97191bc56edSDimitry Andric       else
97291bc56edSDimitry Andric         InsertedShift =
97391bc56edSDimitry Andric             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
97491bc56edSDimitry Andric 
97591bc56edSDimitry Andric       // Sink the trunc
97691bc56edSDimitry Andric       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
97791bc56edSDimitry Andric       TruncInsertPt++;
97891bc56edSDimitry Andric 
97991bc56edSDimitry Andric       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
98091bc56edSDimitry Andric                                        TruncI->getType(), "", TruncInsertPt);
98191bc56edSDimitry Andric 
98291bc56edSDimitry Andric       MadeChange = true;
98391bc56edSDimitry Andric 
98491bc56edSDimitry Andric       TruncTheUse = InsertedTrunc;
98591bc56edSDimitry Andric     }
98691bc56edSDimitry Andric   }
98791bc56edSDimitry Andric   return MadeChange;
98891bc56edSDimitry Andric }
98991bc56edSDimitry Andric 
99091bc56edSDimitry Andric /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
99191bc56edSDimitry Andric /// the uses could potentially be combined with this shift instruction and
99291bc56edSDimitry Andric /// generate BitExtract instruction. It will only be applied if the architecture
99391bc56edSDimitry Andric /// supports BitExtract instruction. Here is an example:
99491bc56edSDimitry Andric /// BB1:
99591bc56edSDimitry Andric ///   %x.extract.shift = lshr i64 %arg1, 32
99691bc56edSDimitry Andric /// BB2:
99791bc56edSDimitry Andric ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
99891bc56edSDimitry Andric /// ==>
99991bc56edSDimitry Andric ///
100091bc56edSDimitry Andric /// BB2:
100191bc56edSDimitry Andric ///   %x.extract.shift.1 = lshr i64 %arg1, 32
100291bc56edSDimitry Andric ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
100391bc56edSDimitry Andric ///
100491bc56edSDimitry Andric /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
100591bc56edSDimitry Andric /// instruction.
100691bc56edSDimitry Andric /// Return true if any changes are made.
100791bc56edSDimitry Andric static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
100891bc56edSDimitry Andric                                 const TargetLowering &TLI) {
100991bc56edSDimitry Andric   BasicBlock *DefBB = ShiftI->getParent();
101091bc56edSDimitry Andric 
101191bc56edSDimitry Andric   /// Only insert instructions in each block once.
101291bc56edSDimitry Andric   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
101391bc56edSDimitry Andric 
101491bc56edSDimitry Andric   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
101591bc56edSDimitry Andric 
101691bc56edSDimitry Andric   bool MadeChange = false;
101791bc56edSDimitry Andric   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
101891bc56edSDimitry Andric        UI != E;) {
101991bc56edSDimitry Andric     Use &TheUse = UI.getUse();
102091bc56edSDimitry Andric     Instruction *User = cast<Instruction>(*UI);
102191bc56edSDimitry Andric     // Preincrement use iterator so we don't invalidate it.
102291bc56edSDimitry Andric     ++UI;
102391bc56edSDimitry Andric 
102491bc56edSDimitry Andric     // Don't bother for PHI nodes.
102591bc56edSDimitry Andric     if (isa<PHINode>(User))
102691bc56edSDimitry Andric       continue;
102791bc56edSDimitry Andric 
102891bc56edSDimitry Andric     if (!isExtractBitsCandidateUse(User))
102991bc56edSDimitry Andric       continue;
103091bc56edSDimitry Andric 
103191bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
103291bc56edSDimitry Andric 
103391bc56edSDimitry Andric     if (UserBB == DefBB) {
103491bc56edSDimitry Andric       // If the shift and truncate instruction are in the same BB. The use of
103591bc56edSDimitry Andric       // the truncate(TruncUse) may still introduce another truncate if not
103691bc56edSDimitry Andric       // legal. In this case, we would like to sink both shift and truncate
103791bc56edSDimitry Andric       // instruction to the BB of TruncUse.
103891bc56edSDimitry Andric       // for example:
103991bc56edSDimitry Andric       // BB1:
104091bc56edSDimitry Andric       // i64 shift.result = lshr i64 opnd, imm
104191bc56edSDimitry Andric       // trunc.result = trunc shift.result to i16
104291bc56edSDimitry Andric       //
104391bc56edSDimitry Andric       // BB2:
104491bc56edSDimitry Andric       //   ----> We will have an implicit truncate here if the architecture does
104591bc56edSDimitry Andric       //   not have i16 compare.
104691bc56edSDimitry Andric       // cmp i16 trunc.result, opnd2
104791bc56edSDimitry Andric       //
104891bc56edSDimitry Andric       if (isa<TruncInst>(User) && shiftIsLegal
104991bc56edSDimitry Andric           // If the type of the truncate is legal, no trucate will be
105091bc56edSDimitry Andric           // introduced in other basic blocks.
105191bc56edSDimitry Andric           && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
105291bc56edSDimitry Andric         MadeChange =
105391bc56edSDimitry Andric             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
105491bc56edSDimitry Andric 
105591bc56edSDimitry Andric       continue;
105691bc56edSDimitry Andric     }
105791bc56edSDimitry Andric     // If we have already inserted a shift into this block, use it.
105891bc56edSDimitry Andric     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
105991bc56edSDimitry Andric 
106091bc56edSDimitry Andric     if (!InsertedShift) {
106191bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
106291bc56edSDimitry Andric 
106391bc56edSDimitry Andric       if (ShiftI->getOpcode() == Instruction::AShr)
106491bc56edSDimitry Andric         InsertedShift =
106591bc56edSDimitry Andric             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
106691bc56edSDimitry Andric       else
106791bc56edSDimitry Andric         InsertedShift =
106891bc56edSDimitry Andric             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
106991bc56edSDimitry Andric 
107091bc56edSDimitry Andric       MadeChange = true;
107191bc56edSDimitry Andric     }
107291bc56edSDimitry Andric 
107391bc56edSDimitry Andric     // Replace a use of the shift with a use of the new shift.
107491bc56edSDimitry Andric     TheUse = InsertedShift;
107591bc56edSDimitry Andric   }
107691bc56edSDimitry Andric 
107791bc56edSDimitry Andric   // If we removed all uses, nuke the shift.
107891bc56edSDimitry Andric   if (ShiftI->use_empty())
107991bc56edSDimitry Andric     ShiftI->eraseFromParent();
108091bc56edSDimitry Andric 
108191bc56edSDimitry Andric   return MadeChange;
108291bc56edSDimitry Andric }
108391bc56edSDimitry Andric 
108439d628a0SDimitry Andric //  ScalarizeMaskedLoad() translates masked load intrinsic, like
108539d628a0SDimitry Andric // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
108639d628a0SDimitry Andric //                               <16 x i1> %mask, <16 x i32> %passthru)
108739d628a0SDimitry Andric // to a chain of basic blocks, whith loading element one-by-one if
108839d628a0SDimitry Andric // the appropriate mask bit is set
108939d628a0SDimitry Andric //
109039d628a0SDimitry Andric //  %1 = bitcast i8* %addr to i32*
109139d628a0SDimitry Andric //  %2 = extractelement <16 x i1> %mask, i32 0
109239d628a0SDimitry Andric //  %3 = icmp eq i1 %2, true
109339d628a0SDimitry Andric //  br i1 %3, label %cond.load, label %else
109439d628a0SDimitry Andric //
109539d628a0SDimitry Andric //cond.load:                                        ; preds = %0
109639d628a0SDimitry Andric //  %4 = getelementptr i32* %1, i32 0
109739d628a0SDimitry Andric //  %5 = load i32* %4
109839d628a0SDimitry Andric //  %6 = insertelement <16 x i32> undef, i32 %5, i32 0
109939d628a0SDimitry Andric //  br label %else
110039d628a0SDimitry Andric //
110139d628a0SDimitry Andric //else:                                             ; preds = %0, %cond.load
110239d628a0SDimitry Andric //  %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
110339d628a0SDimitry Andric //  %7 = extractelement <16 x i1> %mask, i32 1
110439d628a0SDimitry Andric //  %8 = icmp eq i1 %7, true
110539d628a0SDimitry Andric //  br i1 %8, label %cond.load1, label %else2
110639d628a0SDimitry Andric //
110739d628a0SDimitry Andric //cond.load1:                                       ; preds = %else
110839d628a0SDimitry Andric //  %9 = getelementptr i32* %1, i32 1
110939d628a0SDimitry Andric //  %10 = load i32* %9
111039d628a0SDimitry Andric //  %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
111139d628a0SDimitry Andric //  br label %else2
111239d628a0SDimitry Andric //
111339d628a0SDimitry Andric //else2:                                            ; preds = %else, %cond.load1
111439d628a0SDimitry Andric //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
111539d628a0SDimitry Andric //  %12 = extractelement <16 x i1> %mask, i32 2
111639d628a0SDimitry Andric //  %13 = icmp eq i1 %12, true
111739d628a0SDimitry Andric //  br i1 %13, label %cond.load4, label %else5
111839d628a0SDimitry Andric //
111939d628a0SDimitry Andric static void ScalarizeMaskedLoad(CallInst *CI) {
112039d628a0SDimitry Andric   Value *Ptr  = CI->getArgOperand(0);
112139d628a0SDimitry Andric   Value *Src0 = CI->getArgOperand(3);
112239d628a0SDimitry Andric   Value *Mask = CI->getArgOperand(2);
112339d628a0SDimitry Andric   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
112439d628a0SDimitry Andric   Type *EltTy = VecType->getElementType();
112539d628a0SDimitry Andric 
112639d628a0SDimitry Andric   assert(VecType && "Unexpected return type of masked load intrinsic");
112739d628a0SDimitry Andric 
112839d628a0SDimitry Andric   IRBuilder<> Builder(CI->getContext());
112939d628a0SDimitry Andric   Instruction *InsertPt = CI;
113039d628a0SDimitry Andric   BasicBlock *IfBlock = CI->getParent();
113139d628a0SDimitry Andric   BasicBlock *CondBlock = nullptr;
113239d628a0SDimitry Andric   BasicBlock *PrevIfBlock = CI->getParent();
113339d628a0SDimitry Andric   Builder.SetInsertPoint(InsertPt);
113439d628a0SDimitry Andric 
113539d628a0SDimitry Andric   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
113639d628a0SDimitry Andric 
113739d628a0SDimitry Andric   // Bitcast %addr fron i8* to EltTy*
113839d628a0SDimitry Andric   Type *NewPtrType =
113939d628a0SDimitry Andric     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
114039d628a0SDimitry Andric   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
114139d628a0SDimitry Andric   Value *UndefVal = UndefValue::get(VecType);
114239d628a0SDimitry Andric 
114339d628a0SDimitry Andric   // The result vector
114439d628a0SDimitry Andric   Value *VResult = UndefVal;
114539d628a0SDimitry Andric 
114639d628a0SDimitry Andric   PHINode *Phi = nullptr;
114739d628a0SDimitry Andric   Value *PrevPhi = UndefVal;
114839d628a0SDimitry Andric 
114939d628a0SDimitry Andric   unsigned VectorWidth = VecType->getNumElements();
115039d628a0SDimitry Andric   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
115139d628a0SDimitry Andric 
115239d628a0SDimitry Andric     // Fill the "else" block, created in the previous iteration
115339d628a0SDimitry Andric     //
115439d628a0SDimitry Andric     //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
115539d628a0SDimitry Andric     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
115639d628a0SDimitry Andric     //  %to_load = icmp eq i1 %mask_1, true
115739d628a0SDimitry Andric     //  br i1 %to_load, label %cond.load, label %else
115839d628a0SDimitry Andric     //
115939d628a0SDimitry Andric     if (Idx > 0) {
116039d628a0SDimitry Andric       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
116139d628a0SDimitry Andric       Phi->addIncoming(VResult, CondBlock);
116239d628a0SDimitry Andric       Phi->addIncoming(PrevPhi, PrevIfBlock);
116339d628a0SDimitry Andric       PrevPhi = Phi;
116439d628a0SDimitry Andric       VResult = Phi;
116539d628a0SDimitry Andric     }
116639d628a0SDimitry Andric 
116739d628a0SDimitry Andric     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
116839d628a0SDimitry Andric     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
116939d628a0SDimitry Andric                                     ConstantInt::get(Predicate->getType(), 1));
117039d628a0SDimitry Andric 
117139d628a0SDimitry Andric     // Create "cond" block
117239d628a0SDimitry Andric     //
117339d628a0SDimitry Andric     //  %EltAddr = getelementptr i32* %1, i32 0
117439d628a0SDimitry Andric     //  %Elt = load i32* %EltAddr
117539d628a0SDimitry Andric     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
117639d628a0SDimitry Andric     //
117739d628a0SDimitry Andric     CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
117839d628a0SDimitry Andric     Builder.SetInsertPoint(InsertPt);
117939d628a0SDimitry Andric 
1180ff0cc061SDimitry Andric     Value *Gep =
1181ff0cc061SDimitry Andric         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
118239d628a0SDimitry Andric     LoadInst* Load = Builder.CreateLoad(Gep, false);
118339d628a0SDimitry Andric     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
118439d628a0SDimitry Andric 
118539d628a0SDimitry Andric     // Create "else" block, fill it in the next iteration
118639d628a0SDimitry Andric     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
118739d628a0SDimitry Andric     Builder.SetInsertPoint(InsertPt);
118839d628a0SDimitry Andric     Instruction *OldBr = IfBlock->getTerminator();
118939d628a0SDimitry Andric     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
119039d628a0SDimitry Andric     OldBr->eraseFromParent();
119139d628a0SDimitry Andric     PrevIfBlock = IfBlock;
119239d628a0SDimitry Andric     IfBlock = NewIfBlock;
119339d628a0SDimitry Andric   }
119439d628a0SDimitry Andric 
119539d628a0SDimitry Andric   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
119639d628a0SDimitry Andric   Phi->addIncoming(VResult, CondBlock);
119739d628a0SDimitry Andric   Phi->addIncoming(PrevPhi, PrevIfBlock);
119839d628a0SDimitry Andric   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
119939d628a0SDimitry Andric   CI->replaceAllUsesWith(NewI);
120091bc56edSDimitry Andric   CI->eraseFromParent();
120191bc56edSDimitry Andric }
120291bc56edSDimitry Andric 
120339d628a0SDimitry Andric //  ScalarizeMaskedStore() translates masked store intrinsic, like
120439d628a0SDimitry Andric // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
120539d628a0SDimitry Andric //                               <16 x i1> %mask)
120639d628a0SDimitry Andric // to a chain of basic blocks, that stores element one-by-one if
120739d628a0SDimitry Andric // the appropriate mask bit is set
120839d628a0SDimitry Andric //
120939d628a0SDimitry Andric //   %1 = bitcast i8* %addr to i32*
121039d628a0SDimitry Andric //   %2 = extractelement <16 x i1> %mask, i32 0
121139d628a0SDimitry Andric //   %3 = icmp eq i1 %2, true
121239d628a0SDimitry Andric //   br i1 %3, label %cond.store, label %else
121339d628a0SDimitry Andric //
121439d628a0SDimitry Andric // cond.store:                                       ; preds = %0
121539d628a0SDimitry Andric //   %4 = extractelement <16 x i32> %val, i32 0
121639d628a0SDimitry Andric //   %5 = getelementptr i32* %1, i32 0
121739d628a0SDimitry Andric //   store i32 %4, i32* %5
121839d628a0SDimitry Andric //   br label %else
121939d628a0SDimitry Andric //
122039d628a0SDimitry Andric // else:                                             ; preds = %0, %cond.store
122139d628a0SDimitry Andric //   %6 = extractelement <16 x i1> %mask, i32 1
122239d628a0SDimitry Andric //   %7 = icmp eq i1 %6, true
122339d628a0SDimitry Andric //   br i1 %7, label %cond.store1, label %else2
122439d628a0SDimitry Andric //
122539d628a0SDimitry Andric // cond.store1:                                      ; preds = %else
122639d628a0SDimitry Andric //   %8 = extractelement <16 x i32> %val, i32 1
122739d628a0SDimitry Andric //   %9 = getelementptr i32* %1, i32 1
122839d628a0SDimitry Andric //   store i32 %8, i32* %9
122939d628a0SDimitry Andric //   br label %else2
123039d628a0SDimitry Andric //   . . .
123139d628a0SDimitry Andric static void ScalarizeMaskedStore(CallInst *CI) {
123239d628a0SDimitry Andric   Value *Ptr  = CI->getArgOperand(1);
123339d628a0SDimitry Andric   Value *Src = CI->getArgOperand(0);
123439d628a0SDimitry Andric   Value *Mask = CI->getArgOperand(3);
123539d628a0SDimitry Andric 
123639d628a0SDimitry Andric   VectorType *VecType = dyn_cast<VectorType>(Src->getType());
123739d628a0SDimitry Andric   Type *EltTy = VecType->getElementType();
123839d628a0SDimitry Andric 
123939d628a0SDimitry Andric   assert(VecType && "Unexpected data type in masked store intrinsic");
124039d628a0SDimitry Andric 
124139d628a0SDimitry Andric   IRBuilder<> Builder(CI->getContext());
124239d628a0SDimitry Andric   Instruction *InsertPt = CI;
124339d628a0SDimitry Andric   BasicBlock *IfBlock = CI->getParent();
124439d628a0SDimitry Andric   Builder.SetInsertPoint(InsertPt);
124539d628a0SDimitry Andric   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
124639d628a0SDimitry Andric 
124739d628a0SDimitry Andric   // Bitcast %addr fron i8* to EltTy*
124839d628a0SDimitry Andric   Type *NewPtrType =
124939d628a0SDimitry Andric     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
125039d628a0SDimitry Andric   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
125139d628a0SDimitry Andric 
125239d628a0SDimitry Andric   unsigned VectorWidth = VecType->getNumElements();
125339d628a0SDimitry Andric   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
125439d628a0SDimitry Andric 
125539d628a0SDimitry Andric     // Fill the "else" block, created in the previous iteration
125639d628a0SDimitry Andric     //
125739d628a0SDimitry Andric     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
125839d628a0SDimitry Andric     //  %to_store = icmp eq i1 %mask_1, true
125939d628a0SDimitry Andric     //  br i1 %to_load, label %cond.store, label %else
126039d628a0SDimitry Andric     //
126139d628a0SDimitry Andric     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
126239d628a0SDimitry Andric     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
126339d628a0SDimitry Andric                                     ConstantInt::get(Predicate->getType(), 1));
126439d628a0SDimitry Andric 
126539d628a0SDimitry Andric     // Create "cond" block
126639d628a0SDimitry Andric     //
126739d628a0SDimitry Andric     //  %OneElt = extractelement <16 x i32> %Src, i32 Idx
126839d628a0SDimitry Andric     //  %EltAddr = getelementptr i32* %1, i32 0
126939d628a0SDimitry Andric     //  %store i32 %OneElt, i32* %EltAddr
127039d628a0SDimitry Andric     //
127139d628a0SDimitry Andric     BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
127239d628a0SDimitry Andric     Builder.SetInsertPoint(InsertPt);
127339d628a0SDimitry Andric 
127439d628a0SDimitry Andric     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1275ff0cc061SDimitry Andric     Value *Gep =
1276ff0cc061SDimitry Andric         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
127739d628a0SDimitry Andric     Builder.CreateStore(OneElt, Gep);
127839d628a0SDimitry Andric 
127939d628a0SDimitry Andric     // Create "else" block, fill it in the next iteration
128039d628a0SDimitry Andric     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
128139d628a0SDimitry Andric     Builder.SetInsertPoint(InsertPt);
128239d628a0SDimitry Andric     Instruction *OldBr = IfBlock->getTerminator();
128339d628a0SDimitry Andric     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
128439d628a0SDimitry Andric     OldBr->eraseFromParent();
128539d628a0SDimitry Andric     IfBlock = NewIfBlock;
128639d628a0SDimitry Andric   }
128739d628a0SDimitry Andric   CI->eraseFromParent();
128839d628a0SDimitry Andric }
128939d628a0SDimitry Andric 
129039d628a0SDimitry Andric bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
129191bc56edSDimitry Andric   BasicBlock *BB = CI->getParent();
129291bc56edSDimitry Andric 
129391bc56edSDimitry Andric   // Lower inline assembly if we can.
129491bc56edSDimitry Andric   // If we found an inline asm expession, and if the target knows how to
129591bc56edSDimitry Andric   // lower it to normal LLVM code, do so now.
129691bc56edSDimitry Andric   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
129791bc56edSDimitry Andric     if (TLI->ExpandInlineAsm(CI)) {
129891bc56edSDimitry Andric       // Avoid invalidating the iterator.
129991bc56edSDimitry Andric       CurInstIterator = BB->begin();
130091bc56edSDimitry Andric       // Avoid processing instructions out of order, which could cause
130191bc56edSDimitry Andric       // reuse before a value is defined.
130291bc56edSDimitry Andric       SunkAddrs.clear();
130391bc56edSDimitry Andric       return true;
130491bc56edSDimitry Andric     }
130591bc56edSDimitry Andric     // Sink address computing for memory operands into the block.
130691bc56edSDimitry Andric     if (OptimizeInlineAsmInst(CI))
130791bc56edSDimitry Andric       return true;
130891bc56edSDimitry Andric   }
130991bc56edSDimitry Andric 
1310ff0cc061SDimitry Andric   const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
1311ff0cc061SDimitry Andric 
1312ff0cc061SDimitry Andric   // Align the pointer arguments to this call if the target thinks it's a good
1313ff0cc061SDimitry Andric   // idea
1314ff0cc061SDimitry Andric   unsigned MinSize, PrefAlign;
1315ff0cc061SDimitry Andric   if (TLI && TD && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
1316ff0cc061SDimitry Andric     for (auto &Arg : CI->arg_operands()) {
1317ff0cc061SDimitry Andric       // We want to align both objects whose address is used directly and
1318ff0cc061SDimitry Andric       // objects whose address is used in casts and GEPs, though it only makes
1319ff0cc061SDimitry Andric       // sense for GEPs if the offset is a multiple of the desired alignment and
1320ff0cc061SDimitry Andric       // if size - offset meets the size threshold.
1321ff0cc061SDimitry Andric       if (!Arg->getType()->isPointerTy())
1322ff0cc061SDimitry Andric         continue;
1323ff0cc061SDimitry Andric       APInt Offset(TD->getPointerSizeInBits(
1324ff0cc061SDimitry Andric                      cast<PointerType>(Arg->getType())->getAddressSpace()), 0);
1325ff0cc061SDimitry Andric       Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*TD, Offset);
1326ff0cc061SDimitry Andric       uint64_t Offset2 = Offset.getLimitedValue();
1327ff0cc061SDimitry Andric       if ((Offset2 & (PrefAlign-1)) != 0)
1328ff0cc061SDimitry Andric         continue;
1329ff0cc061SDimitry Andric       AllocaInst *AI;
1330ff0cc061SDimitry Andric       if ((AI = dyn_cast<AllocaInst>(Val)) &&
1331ff0cc061SDimitry Andric           AI->getAlignment() < PrefAlign &&
1332ff0cc061SDimitry Andric           TD->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
1333ff0cc061SDimitry Andric         AI->setAlignment(PrefAlign);
1334ff0cc061SDimitry Andric       // Global variables can only be aligned if they are defined in this
1335ff0cc061SDimitry Andric       // object (i.e. they are uniquely initialized in this object), and
1336ff0cc061SDimitry Andric       // over-aligning global variables that have an explicit section is
1337ff0cc061SDimitry Andric       // forbidden.
1338ff0cc061SDimitry Andric       GlobalVariable *GV;
1339ff0cc061SDimitry Andric       if ((GV = dyn_cast<GlobalVariable>(Val)) &&
1340ff0cc061SDimitry Andric           GV->hasUniqueInitializer() &&
1341ff0cc061SDimitry Andric           !GV->hasSection() &&
1342ff0cc061SDimitry Andric           GV->getAlignment() < PrefAlign &&
1343ff0cc061SDimitry Andric           TD->getTypeAllocSize(
1344ff0cc061SDimitry Andric             GV->getType()->getElementType()) >= MinSize + Offset2)
1345ff0cc061SDimitry Andric         GV->setAlignment(PrefAlign);
1346ff0cc061SDimitry Andric     }
1347ff0cc061SDimitry Andric     // If this is a memcpy (or similar) then we may be able to improve the
1348ff0cc061SDimitry Andric     // alignment
1349ff0cc061SDimitry Andric     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
1350ff0cc061SDimitry Andric       unsigned Align = getKnownAlignment(MI->getDest(), *TD);
1351ff0cc061SDimitry Andric       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
1352ff0cc061SDimitry Andric         Align = std::min(Align, getKnownAlignment(MTI->getSource(), *TD));
1353ff0cc061SDimitry Andric       if (Align > MI->getAlignment())
1354ff0cc061SDimitry Andric         MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1355ff0cc061SDimitry Andric     }
1356ff0cc061SDimitry Andric   }
1357ff0cc061SDimitry Andric 
135891bc56edSDimitry Andric   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
135939d628a0SDimitry Andric   if (II) {
136039d628a0SDimitry Andric     switch (II->getIntrinsicID()) {
136139d628a0SDimitry Andric     default: break;
136239d628a0SDimitry Andric     case Intrinsic::objectsize: {
136339d628a0SDimitry Andric       // Lower all uses of llvm.objectsize.*
136491bc56edSDimitry Andric       bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
136591bc56edSDimitry Andric       Type *ReturnTy = CI->getType();
136691bc56edSDimitry Andric       Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
136791bc56edSDimitry Andric 
136891bc56edSDimitry Andric       // Substituting this can cause recursive simplifications, which can
136991bc56edSDimitry Andric       // invalidate our iterator.  Use a WeakVH to hold onto it in case this
137091bc56edSDimitry Andric       // happens.
137191bc56edSDimitry Andric       WeakVH IterHandle(CurInstIterator);
137291bc56edSDimitry Andric 
137391bc56edSDimitry Andric       replaceAndRecursivelySimplify(CI, RetVal,
1374ff0cc061SDimitry Andric                                     TLInfo, nullptr);
137591bc56edSDimitry Andric 
137691bc56edSDimitry Andric       // If the iterator instruction was recursively deleted, start over at the
137791bc56edSDimitry Andric       // start of the block.
137891bc56edSDimitry Andric       if (IterHandle != CurInstIterator) {
137991bc56edSDimitry Andric         CurInstIterator = BB->begin();
138091bc56edSDimitry Andric         SunkAddrs.clear();
138191bc56edSDimitry Andric       }
138291bc56edSDimitry Andric       return true;
138391bc56edSDimitry Andric     }
138439d628a0SDimitry Andric     case Intrinsic::masked_load: {
138539d628a0SDimitry Andric       // Scalarize unsupported vector masked load
138639d628a0SDimitry Andric       if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
138739d628a0SDimitry Andric         ScalarizeMaskedLoad(CI);
138839d628a0SDimitry Andric         ModifiedDT = true;
138939d628a0SDimitry Andric         return true;
139039d628a0SDimitry Andric       }
139139d628a0SDimitry Andric       return false;
139239d628a0SDimitry Andric     }
139339d628a0SDimitry Andric     case Intrinsic::masked_store: {
139439d628a0SDimitry Andric       if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
139539d628a0SDimitry Andric         ScalarizeMaskedStore(CI);
139639d628a0SDimitry Andric         ModifiedDT = true;
139739d628a0SDimitry Andric         return true;
139839d628a0SDimitry Andric       }
139939d628a0SDimitry Andric       return false;
140039d628a0SDimitry Andric     }
1401ff0cc061SDimitry Andric     case Intrinsic::aarch64_stlxr:
1402ff0cc061SDimitry Andric     case Intrinsic::aarch64_stxr: {
1403ff0cc061SDimitry Andric       ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1404ff0cc061SDimitry Andric       if (!ExtVal || !ExtVal->hasOneUse() ||
1405ff0cc061SDimitry Andric           ExtVal->getParent() == CI->getParent())
1406ff0cc061SDimitry Andric         return false;
1407ff0cc061SDimitry Andric       // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1408ff0cc061SDimitry Andric       ExtVal->moveBefore(CI);
14098f0fd8f6SDimitry Andric       // Mark this instruction as "inserted by CGP", so that other
14108f0fd8f6SDimitry Andric       // optimizations don't touch it.
14118f0fd8f6SDimitry Andric       InsertedInsts.insert(ExtVal);
1412ff0cc061SDimitry Andric       return true;
1413ff0cc061SDimitry Andric     }
141439d628a0SDimitry Andric     }
141591bc56edSDimitry Andric 
141639d628a0SDimitry Andric     if (TLI) {
141797bc6c73SDimitry Andric       // Unknown address space.
141897bc6c73SDimitry Andric       // TODO: Target hook to pick which address space the intrinsic cares
141997bc6c73SDimitry Andric       // about?
142097bc6c73SDimitry Andric       unsigned AddrSpace = ~0u;
142191bc56edSDimitry Andric       SmallVector<Value*, 2> PtrOps;
142291bc56edSDimitry Andric       Type *AccessTy;
142397bc6c73SDimitry Andric       if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
142491bc56edSDimitry Andric         while (!PtrOps.empty())
142597bc6c73SDimitry Andric           if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
142691bc56edSDimitry Andric             return true;
142791bc56edSDimitry Andric     }
142839d628a0SDimitry Andric   }
142991bc56edSDimitry Andric 
143091bc56edSDimitry Andric   // From here on out we're working with named functions.
143191bc56edSDimitry Andric   if (!CI->getCalledFunction()) return false;
143291bc56edSDimitry Andric 
143391bc56edSDimitry Andric   // Lower all default uses of _chk calls.  This is very similar
143491bc56edSDimitry Andric   // to what InstCombineCalls does, but here we are only lowering calls
143539d628a0SDimitry Andric   // to fortified library functions (e.g. __memcpy_chk) that have the default
143639d628a0SDimitry Andric   // "don't know" as the objectsize.  Anything else should be left alone.
1437ff0cc061SDimitry Andric   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
143839d628a0SDimitry Andric   if (Value *V = Simplifier.optimizeCall(CI)) {
143939d628a0SDimitry Andric     CI->replaceAllUsesWith(V);
144039d628a0SDimitry Andric     CI->eraseFromParent();
144139d628a0SDimitry Andric     return true;
144239d628a0SDimitry Andric   }
144339d628a0SDimitry Andric   return false;
144491bc56edSDimitry Andric }
144591bc56edSDimitry Andric 
144691bc56edSDimitry Andric /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
144791bc56edSDimitry Andric /// instructions to the predecessor to enable tail call optimizations. The
144891bc56edSDimitry Andric /// case it is currently looking for is:
144991bc56edSDimitry Andric /// @code
145091bc56edSDimitry Andric /// bb0:
145191bc56edSDimitry Andric ///   %tmp0 = tail call i32 @f0()
145291bc56edSDimitry Andric ///   br label %return
145391bc56edSDimitry Andric /// bb1:
145491bc56edSDimitry Andric ///   %tmp1 = tail call i32 @f1()
145591bc56edSDimitry Andric ///   br label %return
145691bc56edSDimitry Andric /// bb2:
145791bc56edSDimitry Andric ///   %tmp2 = tail call i32 @f2()
145891bc56edSDimitry Andric ///   br label %return
145991bc56edSDimitry Andric /// return:
146091bc56edSDimitry Andric ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
146191bc56edSDimitry Andric ///   ret i32 %retval
146291bc56edSDimitry Andric /// @endcode
146391bc56edSDimitry Andric ///
146491bc56edSDimitry Andric /// =>
146591bc56edSDimitry Andric ///
146691bc56edSDimitry Andric /// @code
146791bc56edSDimitry Andric /// bb0:
146891bc56edSDimitry Andric ///   %tmp0 = tail call i32 @f0()
146991bc56edSDimitry Andric ///   ret i32 %tmp0
147091bc56edSDimitry Andric /// bb1:
147191bc56edSDimitry Andric ///   %tmp1 = tail call i32 @f1()
147291bc56edSDimitry Andric ///   ret i32 %tmp1
147391bc56edSDimitry Andric /// bb2:
147491bc56edSDimitry Andric ///   %tmp2 = tail call i32 @f2()
147591bc56edSDimitry Andric ///   ret i32 %tmp2
147691bc56edSDimitry Andric /// @endcode
147791bc56edSDimitry Andric bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
147891bc56edSDimitry Andric   if (!TLI)
147991bc56edSDimitry Andric     return false;
148091bc56edSDimitry Andric 
148191bc56edSDimitry Andric   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
148291bc56edSDimitry Andric   if (!RI)
148391bc56edSDimitry Andric     return false;
148491bc56edSDimitry Andric 
148591bc56edSDimitry Andric   PHINode *PN = nullptr;
148691bc56edSDimitry Andric   BitCastInst *BCI = nullptr;
148791bc56edSDimitry Andric   Value *V = RI->getReturnValue();
148891bc56edSDimitry Andric   if (V) {
148991bc56edSDimitry Andric     BCI = dyn_cast<BitCastInst>(V);
149091bc56edSDimitry Andric     if (BCI)
149191bc56edSDimitry Andric       V = BCI->getOperand(0);
149291bc56edSDimitry Andric 
149391bc56edSDimitry Andric     PN = dyn_cast<PHINode>(V);
149491bc56edSDimitry Andric     if (!PN)
149591bc56edSDimitry Andric       return false;
149691bc56edSDimitry Andric   }
149791bc56edSDimitry Andric 
149891bc56edSDimitry Andric   if (PN && PN->getParent() != BB)
149991bc56edSDimitry Andric     return false;
150091bc56edSDimitry Andric 
150191bc56edSDimitry Andric   // It's not safe to eliminate the sign / zero extension of the return value.
150291bc56edSDimitry Andric   // See llvm::isInTailCallPosition().
150391bc56edSDimitry Andric   const Function *F = BB->getParent();
150491bc56edSDimitry Andric   AttributeSet CallerAttrs = F->getAttributes();
150591bc56edSDimitry Andric   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
150691bc56edSDimitry Andric       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
150791bc56edSDimitry Andric     return false;
150891bc56edSDimitry Andric 
150991bc56edSDimitry Andric   // Make sure there are no instructions between the PHI and return, or that the
151091bc56edSDimitry Andric   // return is the first instruction in the block.
151191bc56edSDimitry Andric   if (PN) {
151291bc56edSDimitry Andric     BasicBlock::iterator BI = BB->begin();
151391bc56edSDimitry Andric     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
151491bc56edSDimitry Andric     if (&*BI == BCI)
151591bc56edSDimitry Andric       // Also skip over the bitcast.
151691bc56edSDimitry Andric       ++BI;
151791bc56edSDimitry Andric     if (&*BI != RI)
151891bc56edSDimitry Andric       return false;
151991bc56edSDimitry Andric   } else {
152091bc56edSDimitry Andric     BasicBlock::iterator BI = BB->begin();
152191bc56edSDimitry Andric     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
152291bc56edSDimitry Andric     if (&*BI != RI)
152391bc56edSDimitry Andric       return false;
152491bc56edSDimitry Andric   }
152591bc56edSDimitry Andric 
152691bc56edSDimitry Andric   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
152791bc56edSDimitry Andric   /// call.
152891bc56edSDimitry Andric   SmallVector<CallInst*, 4> TailCalls;
152991bc56edSDimitry Andric   if (PN) {
153091bc56edSDimitry Andric     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
153191bc56edSDimitry Andric       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
153291bc56edSDimitry Andric       // Make sure the phi value is indeed produced by the tail call.
153391bc56edSDimitry Andric       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
153491bc56edSDimitry Andric           TLI->mayBeEmittedAsTailCall(CI))
153591bc56edSDimitry Andric         TailCalls.push_back(CI);
153691bc56edSDimitry Andric     }
153791bc56edSDimitry Andric   } else {
153891bc56edSDimitry Andric     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
153991bc56edSDimitry Andric     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
154039d628a0SDimitry Andric       if (!VisitedBBs.insert(*PI).second)
154191bc56edSDimitry Andric         continue;
154291bc56edSDimitry Andric 
154391bc56edSDimitry Andric       BasicBlock::InstListType &InstList = (*PI)->getInstList();
154491bc56edSDimitry Andric       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
154591bc56edSDimitry Andric       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
154691bc56edSDimitry Andric       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
154791bc56edSDimitry Andric       if (RI == RE)
154891bc56edSDimitry Andric         continue;
154991bc56edSDimitry Andric 
155091bc56edSDimitry Andric       CallInst *CI = dyn_cast<CallInst>(&*RI);
155191bc56edSDimitry Andric       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
155291bc56edSDimitry Andric         TailCalls.push_back(CI);
155391bc56edSDimitry Andric     }
155491bc56edSDimitry Andric   }
155591bc56edSDimitry Andric 
155691bc56edSDimitry Andric   bool Changed = false;
155791bc56edSDimitry Andric   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
155891bc56edSDimitry Andric     CallInst *CI = TailCalls[i];
155991bc56edSDimitry Andric     CallSite CS(CI);
156091bc56edSDimitry Andric 
156191bc56edSDimitry Andric     // Conservatively require the attributes of the call to match those of the
156291bc56edSDimitry Andric     // return. Ignore noalias because it doesn't affect the call sequence.
156391bc56edSDimitry Andric     AttributeSet CalleeAttrs = CS.getAttributes();
156491bc56edSDimitry Andric     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
156591bc56edSDimitry Andric           removeAttribute(Attribute::NoAlias) !=
156691bc56edSDimitry Andric         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
156791bc56edSDimitry Andric           removeAttribute(Attribute::NoAlias))
156891bc56edSDimitry Andric       continue;
156991bc56edSDimitry Andric 
157091bc56edSDimitry Andric     // Make sure the call instruction is followed by an unconditional branch to
157191bc56edSDimitry Andric     // the return block.
157291bc56edSDimitry Andric     BasicBlock *CallBB = CI->getParent();
157391bc56edSDimitry Andric     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
157491bc56edSDimitry Andric     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
157591bc56edSDimitry Andric       continue;
157691bc56edSDimitry Andric 
157791bc56edSDimitry Andric     // Duplicate the return into CallBB.
157891bc56edSDimitry Andric     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
157991bc56edSDimitry Andric     ModifiedDT = Changed = true;
158091bc56edSDimitry Andric     ++NumRetsDup;
158191bc56edSDimitry Andric   }
158291bc56edSDimitry Andric 
158391bc56edSDimitry Andric   // If we eliminated all predecessors of the block, delete the block now.
158491bc56edSDimitry Andric   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
158591bc56edSDimitry Andric     BB->eraseFromParent();
158691bc56edSDimitry Andric 
158791bc56edSDimitry Andric   return Changed;
158891bc56edSDimitry Andric }
158991bc56edSDimitry Andric 
159091bc56edSDimitry Andric //===----------------------------------------------------------------------===//
159191bc56edSDimitry Andric // Memory Optimization
159291bc56edSDimitry Andric //===----------------------------------------------------------------------===//
159391bc56edSDimitry Andric 
159491bc56edSDimitry Andric namespace {
159591bc56edSDimitry Andric 
159691bc56edSDimitry Andric /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
159791bc56edSDimitry Andric /// which holds actual Value*'s for register values.
159891bc56edSDimitry Andric struct ExtAddrMode : public TargetLowering::AddrMode {
159991bc56edSDimitry Andric   Value *BaseReg;
160091bc56edSDimitry Andric   Value *ScaledReg;
160191bc56edSDimitry Andric   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
160291bc56edSDimitry Andric   void print(raw_ostream &OS) const;
160391bc56edSDimitry Andric   void dump() const;
160491bc56edSDimitry Andric 
160591bc56edSDimitry Andric   bool operator==(const ExtAddrMode& O) const {
160691bc56edSDimitry Andric     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
160791bc56edSDimitry Andric            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
160891bc56edSDimitry Andric            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
160991bc56edSDimitry Andric   }
161091bc56edSDimitry Andric };
161191bc56edSDimitry Andric 
161291bc56edSDimitry Andric #ifndef NDEBUG
161391bc56edSDimitry Andric static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
161491bc56edSDimitry Andric   AM.print(OS);
161591bc56edSDimitry Andric   return OS;
161691bc56edSDimitry Andric }
161791bc56edSDimitry Andric #endif
161891bc56edSDimitry Andric 
161991bc56edSDimitry Andric void ExtAddrMode::print(raw_ostream &OS) const {
162091bc56edSDimitry Andric   bool NeedPlus = false;
162191bc56edSDimitry Andric   OS << "[";
162291bc56edSDimitry Andric   if (BaseGV) {
162391bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
162491bc56edSDimitry Andric        << "GV:";
162591bc56edSDimitry Andric     BaseGV->printAsOperand(OS, /*PrintType=*/false);
162691bc56edSDimitry Andric     NeedPlus = true;
162791bc56edSDimitry Andric   }
162891bc56edSDimitry Andric 
162991bc56edSDimitry Andric   if (BaseOffs) {
163091bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
163191bc56edSDimitry Andric        << BaseOffs;
163291bc56edSDimitry Andric     NeedPlus = true;
163391bc56edSDimitry Andric   }
163491bc56edSDimitry Andric 
163591bc56edSDimitry Andric   if (BaseReg) {
163691bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
163791bc56edSDimitry Andric        << "Base:";
163891bc56edSDimitry Andric     BaseReg->printAsOperand(OS, /*PrintType=*/false);
163991bc56edSDimitry Andric     NeedPlus = true;
164091bc56edSDimitry Andric   }
164191bc56edSDimitry Andric   if (Scale) {
164291bc56edSDimitry Andric     OS << (NeedPlus ? " + " : "")
164391bc56edSDimitry Andric        << Scale << "*";
164491bc56edSDimitry Andric     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
164591bc56edSDimitry Andric   }
164691bc56edSDimitry Andric 
164791bc56edSDimitry Andric   OS << ']';
164891bc56edSDimitry Andric }
164991bc56edSDimitry Andric 
165091bc56edSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
165191bc56edSDimitry Andric void ExtAddrMode::dump() const {
165291bc56edSDimitry Andric   print(dbgs());
165391bc56edSDimitry Andric   dbgs() << '\n';
165491bc56edSDimitry Andric }
165591bc56edSDimitry Andric #endif
165691bc56edSDimitry Andric 
165791bc56edSDimitry Andric /// \brief This class provides transaction based operation on the IR.
165891bc56edSDimitry Andric /// Every change made through this class is recorded in the internal state and
165991bc56edSDimitry Andric /// can be undone (rollback) until commit is called.
166091bc56edSDimitry Andric class TypePromotionTransaction {
166191bc56edSDimitry Andric 
166291bc56edSDimitry Andric   /// \brief This represents the common interface of the individual transaction.
166391bc56edSDimitry Andric   /// Each class implements the logic for doing one specific modification on
166491bc56edSDimitry Andric   /// the IR via the TypePromotionTransaction.
166591bc56edSDimitry Andric   class TypePromotionAction {
166691bc56edSDimitry Andric   protected:
166791bc56edSDimitry Andric     /// The Instruction modified.
166891bc56edSDimitry Andric     Instruction *Inst;
166991bc56edSDimitry Andric 
167091bc56edSDimitry Andric   public:
167191bc56edSDimitry Andric     /// \brief Constructor of the action.
167291bc56edSDimitry Andric     /// The constructor performs the related action on the IR.
167391bc56edSDimitry Andric     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
167491bc56edSDimitry Andric 
167591bc56edSDimitry Andric     virtual ~TypePromotionAction() {}
167691bc56edSDimitry Andric 
167791bc56edSDimitry Andric     /// \brief Undo the modification done by this action.
167891bc56edSDimitry Andric     /// When this method is called, the IR must be in the same state as it was
167991bc56edSDimitry Andric     /// before this action was applied.
168091bc56edSDimitry Andric     /// \pre Undoing the action works if and only if the IR is in the exact same
168191bc56edSDimitry Andric     /// state as it was directly after this action was applied.
168291bc56edSDimitry Andric     virtual void undo() = 0;
168391bc56edSDimitry Andric 
168491bc56edSDimitry Andric     /// \brief Advocate every change made by this action.
168591bc56edSDimitry Andric     /// When the results on the IR of the action are to be kept, it is important
168691bc56edSDimitry Andric     /// to call this function, otherwise hidden information may be kept forever.
168791bc56edSDimitry Andric     virtual void commit() {
168891bc56edSDimitry Andric       // Nothing to be done, this action is not doing anything.
168991bc56edSDimitry Andric     }
169091bc56edSDimitry Andric   };
169191bc56edSDimitry Andric 
169291bc56edSDimitry Andric   /// \brief Utility to remember the position of an instruction.
169391bc56edSDimitry Andric   class InsertionHandler {
169491bc56edSDimitry Andric     /// Position of an instruction.
169591bc56edSDimitry Andric     /// Either an instruction:
169691bc56edSDimitry Andric     /// - Is the first in a basic block: BB is used.
169791bc56edSDimitry Andric     /// - Has a previous instructon: PrevInst is used.
169891bc56edSDimitry Andric     union {
169991bc56edSDimitry Andric       Instruction *PrevInst;
170091bc56edSDimitry Andric       BasicBlock *BB;
170191bc56edSDimitry Andric     } Point;
170291bc56edSDimitry Andric     /// Remember whether or not the instruction had a previous instruction.
170391bc56edSDimitry Andric     bool HasPrevInstruction;
170491bc56edSDimitry Andric 
170591bc56edSDimitry Andric   public:
170691bc56edSDimitry Andric     /// \brief Record the position of \p Inst.
170791bc56edSDimitry Andric     InsertionHandler(Instruction *Inst) {
170891bc56edSDimitry Andric       BasicBlock::iterator It = Inst;
170991bc56edSDimitry Andric       HasPrevInstruction = (It != (Inst->getParent()->begin()));
171091bc56edSDimitry Andric       if (HasPrevInstruction)
171191bc56edSDimitry Andric         Point.PrevInst = --It;
171291bc56edSDimitry Andric       else
171391bc56edSDimitry Andric         Point.BB = Inst->getParent();
171491bc56edSDimitry Andric     }
171591bc56edSDimitry Andric 
171691bc56edSDimitry Andric     /// \brief Insert \p Inst at the recorded position.
171791bc56edSDimitry Andric     void insert(Instruction *Inst) {
171891bc56edSDimitry Andric       if (HasPrevInstruction) {
171991bc56edSDimitry Andric         if (Inst->getParent())
172091bc56edSDimitry Andric           Inst->removeFromParent();
172191bc56edSDimitry Andric         Inst->insertAfter(Point.PrevInst);
172291bc56edSDimitry Andric       } else {
172391bc56edSDimitry Andric         Instruction *Position = Point.BB->getFirstInsertionPt();
172491bc56edSDimitry Andric         if (Inst->getParent())
172591bc56edSDimitry Andric           Inst->moveBefore(Position);
172691bc56edSDimitry Andric         else
172791bc56edSDimitry Andric           Inst->insertBefore(Position);
172891bc56edSDimitry Andric       }
172991bc56edSDimitry Andric     }
173091bc56edSDimitry Andric   };
173191bc56edSDimitry Andric 
173291bc56edSDimitry Andric   /// \brief Move an instruction before another.
173391bc56edSDimitry Andric   class InstructionMoveBefore : public TypePromotionAction {
173491bc56edSDimitry Andric     /// Original position of the instruction.
173591bc56edSDimitry Andric     InsertionHandler Position;
173691bc56edSDimitry Andric 
173791bc56edSDimitry Andric   public:
173891bc56edSDimitry Andric     /// \brief Move \p Inst before \p Before.
173991bc56edSDimitry Andric     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
174091bc56edSDimitry Andric         : TypePromotionAction(Inst), Position(Inst) {
174191bc56edSDimitry Andric       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
174291bc56edSDimitry Andric       Inst->moveBefore(Before);
174391bc56edSDimitry Andric     }
174491bc56edSDimitry Andric 
174591bc56edSDimitry Andric     /// \brief Move the instruction back to its original position.
174691bc56edSDimitry Andric     void undo() override {
174791bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
174891bc56edSDimitry Andric       Position.insert(Inst);
174991bc56edSDimitry Andric     }
175091bc56edSDimitry Andric   };
175191bc56edSDimitry Andric 
175291bc56edSDimitry Andric   /// \brief Set the operand of an instruction with a new value.
175391bc56edSDimitry Andric   class OperandSetter : public TypePromotionAction {
175491bc56edSDimitry Andric     /// Original operand of the instruction.
175591bc56edSDimitry Andric     Value *Origin;
175691bc56edSDimitry Andric     /// Index of the modified instruction.
175791bc56edSDimitry Andric     unsigned Idx;
175891bc56edSDimitry Andric 
175991bc56edSDimitry Andric   public:
176091bc56edSDimitry Andric     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
176191bc56edSDimitry Andric     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
176291bc56edSDimitry Andric         : TypePromotionAction(Inst), Idx(Idx) {
176391bc56edSDimitry Andric       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
176491bc56edSDimitry Andric                    << "for:" << *Inst << "\n"
176591bc56edSDimitry Andric                    << "with:" << *NewVal << "\n");
176691bc56edSDimitry Andric       Origin = Inst->getOperand(Idx);
176791bc56edSDimitry Andric       Inst->setOperand(Idx, NewVal);
176891bc56edSDimitry Andric     }
176991bc56edSDimitry Andric 
177091bc56edSDimitry Andric     /// \brief Restore the original value of the instruction.
177191bc56edSDimitry Andric     void undo() override {
177291bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
177391bc56edSDimitry Andric                    << "for: " << *Inst << "\n"
177491bc56edSDimitry Andric                    << "with: " << *Origin << "\n");
177591bc56edSDimitry Andric       Inst->setOperand(Idx, Origin);
177691bc56edSDimitry Andric     }
177791bc56edSDimitry Andric   };
177891bc56edSDimitry Andric 
177991bc56edSDimitry Andric   /// \brief Hide the operands of an instruction.
178091bc56edSDimitry Andric   /// Do as if this instruction was not using any of its operands.
178191bc56edSDimitry Andric   class OperandsHider : public TypePromotionAction {
178291bc56edSDimitry Andric     /// The list of original operands.
178391bc56edSDimitry Andric     SmallVector<Value *, 4> OriginalValues;
178491bc56edSDimitry Andric 
178591bc56edSDimitry Andric   public:
178691bc56edSDimitry Andric     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
178791bc56edSDimitry Andric     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
178891bc56edSDimitry Andric       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
178991bc56edSDimitry Andric       unsigned NumOpnds = Inst->getNumOperands();
179091bc56edSDimitry Andric       OriginalValues.reserve(NumOpnds);
179191bc56edSDimitry Andric       for (unsigned It = 0; It < NumOpnds; ++It) {
179291bc56edSDimitry Andric         // Save the current operand.
179391bc56edSDimitry Andric         Value *Val = Inst->getOperand(It);
179491bc56edSDimitry Andric         OriginalValues.push_back(Val);
179591bc56edSDimitry Andric         // Set a dummy one.
179691bc56edSDimitry Andric         // We could use OperandSetter here, but that would implied an overhead
179791bc56edSDimitry Andric         // that we are not willing to pay.
179891bc56edSDimitry Andric         Inst->setOperand(It, UndefValue::get(Val->getType()));
179991bc56edSDimitry Andric       }
180091bc56edSDimitry Andric     }
180191bc56edSDimitry Andric 
180291bc56edSDimitry Andric     /// \brief Restore the original list of uses.
180391bc56edSDimitry Andric     void undo() override {
180491bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
180591bc56edSDimitry Andric       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
180691bc56edSDimitry Andric         Inst->setOperand(It, OriginalValues[It]);
180791bc56edSDimitry Andric     }
180891bc56edSDimitry Andric   };
180991bc56edSDimitry Andric 
181091bc56edSDimitry Andric   /// \brief Build a truncate instruction.
181191bc56edSDimitry Andric   class TruncBuilder : public TypePromotionAction {
181239d628a0SDimitry Andric     Value *Val;
181391bc56edSDimitry Andric   public:
181491bc56edSDimitry Andric     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
181591bc56edSDimitry Andric     /// result.
181691bc56edSDimitry Andric     /// trunc Opnd to Ty.
181791bc56edSDimitry Andric     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
181891bc56edSDimitry Andric       IRBuilder<> Builder(Opnd);
181939d628a0SDimitry Andric       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
182039d628a0SDimitry Andric       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
182191bc56edSDimitry Andric     }
182291bc56edSDimitry Andric 
182339d628a0SDimitry Andric     /// \brief Get the built value.
182439d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
182591bc56edSDimitry Andric 
182691bc56edSDimitry Andric     /// \brief Remove the built instruction.
182791bc56edSDimitry Andric     void undo() override {
182839d628a0SDimitry Andric       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
182939d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
183039d628a0SDimitry Andric         IVal->eraseFromParent();
183191bc56edSDimitry Andric     }
183291bc56edSDimitry Andric   };
183391bc56edSDimitry Andric 
183491bc56edSDimitry Andric   /// \brief Build a sign extension instruction.
183591bc56edSDimitry Andric   class SExtBuilder : public TypePromotionAction {
183639d628a0SDimitry Andric     Value *Val;
183791bc56edSDimitry Andric   public:
183891bc56edSDimitry Andric     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
183991bc56edSDimitry Andric     /// result.
184091bc56edSDimitry Andric     /// sext Opnd to Ty.
184191bc56edSDimitry Andric     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
184239d628a0SDimitry Andric         : TypePromotionAction(InsertPt) {
184391bc56edSDimitry Andric       IRBuilder<> Builder(InsertPt);
184439d628a0SDimitry Andric       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
184539d628a0SDimitry Andric       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
184691bc56edSDimitry Andric     }
184791bc56edSDimitry Andric 
184839d628a0SDimitry Andric     /// \brief Get the built value.
184939d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
185091bc56edSDimitry Andric 
185191bc56edSDimitry Andric     /// \brief Remove the built instruction.
185291bc56edSDimitry Andric     void undo() override {
185339d628a0SDimitry Andric       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
185439d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
185539d628a0SDimitry Andric         IVal->eraseFromParent();
185639d628a0SDimitry Andric     }
185739d628a0SDimitry Andric   };
185839d628a0SDimitry Andric 
185939d628a0SDimitry Andric   /// \brief Build a zero extension instruction.
186039d628a0SDimitry Andric   class ZExtBuilder : public TypePromotionAction {
186139d628a0SDimitry Andric     Value *Val;
186239d628a0SDimitry Andric   public:
186339d628a0SDimitry Andric     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
186439d628a0SDimitry Andric     /// result.
186539d628a0SDimitry Andric     /// zext Opnd to Ty.
186639d628a0SDimitry Andric     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
186739d628a0SDimitry Andric         : TypePromotionAction(InsertPt) {
186839d628a0SDimitry Andric       IRBuilder<> Builder(InsertPt);
186939d628a0SDimitry Andric       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
187039d628a0SDimitry Andric       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
187139d628a0SDimitry Andric     }
187239d628a0SDimitry Andric 
187339d628a0SDimitry Andric     /// \brief Get the built value.
187439d628a0SDimitry Andric     Value *getBuiltValue() { return Val; }
187539d628a0SDimitry Andric 
187639d628a0SDimitry Andric     /// \brief Remove the built instruction.
187739d628a0SDimitry Andric     void undo() override {
187839d628a0SDimitry Andric       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
187939d628a0SDimitry Andric       if (Instruction *IVal = dyn_cast<Instruction>(Val))
188039d628a0SDimitry Andric         IVal->eraseFromParent();
188191bc56edSDimitry Andric     }
188291bc56edSDimitry Andric   };
188391bc56edSDimitry Andric 
188491bc56edSDimitry Andric   /// \brief Mutate an instruction to another type.
188591bc56edSDimitry Andric   class TypeMutator : public TypePromotionAction {
188691bc56edSDimitry Andric     /// Record the original type.
188791bc56edSDimitry Andric     Type *OrigTy;
188891bc56edSDimitry Andric 
188991bc56edSDimitry Andric   public:
189091bc56edSDimitry Andric     /// \brief Mutate the type of \p Inst into \p NewTy.
189191bc56edSDimitry Andric     TypeMutator(Instruction *Inst, Type *NewTy)
189291bc56edSDimitry Andric         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
189391bc56edSDimitry Andric       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
189491bc56edSDimitry Andric                    << "\n");
189591bc56edSDimitry Andric       Inst->mutateType(NewTy);
189691bc56edSDimitry Andric     }
189791bc56edSDimitry Andric 
189891bc56edSDimitry Andric     /// \brief Mutate the instruction back to its original type.
189991bc56edSDimitry Andric     void undo() override {
190091bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
190191bc56edSDimitry Andric                    << "\n");
190291bc56edSDimitry Andric       Inst->mutateType(OrigTy);
190391bc56edSDimitry Andric     }
190491bc56edSDimitry Andric   };
190591bc56edSDimitry Andric 
190691bc56edSDimitry Andric   /// \brief Replace the uses of an instruction by another instruction.
190791bc56edSDimitry Andric   class UsesReplacer : public TypePromotionAction {
190891bc56edSDimitry Andric     /// Helper structure to keep track of the replaced uses.
190991bc56edSDimitry Andric     struct InstructionAndIdx {
191091bc56edSDimitry Andric       /// The instruction using the instruction.
191191bc56edSDimitry Andric       Instruction *Inst;
191291bc56edSDimitry Andric       /// The index where this instruction is used for Inst.
191391bc56edSDimitry Andric       unsigned Idx;
191491bc56edSDimitry Andric       InstructionAndIdx(Instruction *Inst, unsigned Idx)
191591bc56edSDimitry Andric           : Inst(Inst), Idx(Idx) {}
191691bc56edSDimitry Andric     };
191791bc56edSDimitry Andric 
191891bc56edSDimitry Andric     /// Keep track of the original uses (pair Instruction, Index).
191991bc56edSDimitry Andric     SmallVector<InstructionAndIdx, 4> OriginalUses;
192091bc56edSDimitry Andric     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
192191bc56edSDimitry Andric 
192291bc56edSDimitry Andric   public:
192391bc56edSDimitry Andric     /// \brief Replace all the use of \p Inst by \p New.
192491bc56edSDimitry Andric     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
192591bc56edSDimitry Andric       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
192691bc56edSDimitry Andric                    << "\n");
192791bc56edSDimitry Andric       // Record the original uses.
192891bc56edSDimitry Andric       for (Use &U : Inst->uses()) {
192991bc56edSDimitry Andric         Instruction *UserI = cast<Instruction>(U.getUser());
193091bc56edSDimitry Andric         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
193191bc56edSDimitry Andric       }
193291bc56edSDimitry Andric       // Now, we can replace the uses.
193391bc56edSDimitry Andric       Inst->replaceAllUsesWith(New);
193491bc56edSDimitry Andric     }
193591bc56edSDimitry Andric 
193691bc56edSDimitry Andric     /// \brief Reassign the original uses of Inst to Inst.
193791bc56edSDimitry Andric     void undo() override {
193891bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
193991bc56edSDimitry Andric       for (use_iterator UseIt = OriginalUses.begin(),
194091bc56edSDimitry Andric                         EndIt = OriginalUses.end();
194191bc56edSDimitry Andric            UseIt != EndIt; ++UseIt) {
194291bc56edSDimitry Andric         UseIt->Inst->setOperand(UseIt->Idx, Inst);
194391bc56edSDimitry Andric       }
194491bc56edSDimitry Andric     }
194591bc56edSDimitry Andric   };
194691bc56edSDimitry Andric 
194791bc56edSDimitry Andric   /// \brief Remove an instruction from the IR.
194891bc56edSDimitry Andric   class InstructionRemover : public TypePromotionAction {
194991bc56edSDimitry Andric     /// Original position of the instruction.
195091bc56edSDimitry Andric     InsertionHandler Inserter;
195191bc56edSDimitry Andric     /// Helper structure to hide all the link to the instruction. In other
195291bc56edSDimitry Andric     /// words, this helps to do as if the instruction was removed.
195391bc56edSDimitry Andric     OperandsHider Hider;
195491bc56edSDimitry Andric     /// Keep track of the uses replaced, if any.
195591bc56edSDimitry Andric     UsesReplacer *Replacer;
195691bc56edSDimitry Andric 
195791bc56edSDimitry Andric   public:
195891bc56edSDimitry Andric     /// \brief Remove all reference of \p Inst and optinally replace all its
195991bc56edSDimitry Andric     /// uses with New.
196091bc56edSDimitry Andric     /// \pre If !Inst->use_empty(), then New != nullptr
196191bc56edSDimitry Andric     InstructionRemover(Instruction *Inst, Value *New = nullptr)
196291bc56edSDimitry Andric         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
196391bc56edSDimitry Andric           Replacer(nullptr) {
196491bc56edSDimitry Andric       if (New)
196591bc56edSDimitry Andric         Replacer = new UsesReplacer(Inst, New);
196691bc56edSDimitry Andric       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
196791bc56edSDimitry Andric       Inst->removeFromParent();
196891bc56edSDimitry Andric     }
196991bc56edSDimitry Andric 
1970ff0cc061SDimitry Andric     ~InstructionRemover() override { delete Replacer; }
197191bc56edSDimitry Andric 
197291bc56edSDimitry Andric     /// \brief Really remove the instruction.
197391bc56edSDimitry Andric     void commit() override { delete Inst; }
197491bc56edSDimitry Andric 
197591bc56edSDimitry Andric     /// \brief Resurrect the instruction and reassign it to the proper uses if
197691bc56edSDimitry Andric     /// new value was provided when build this action.
197791bc56edSDimitry Andric     void undo() override {
197891bc56edSDimitry Andric       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
197991bc56edSDimitry Andric       Inserter.insert(Inst);
198091bc56edSDimitry Andric       if (Replacer)
198191bc56edSDimitry Andric         Replacer->undo();
198291bc56edSDimitry Andric       Hider.undo();
198391bc56edSDimitry Andric     }
198491bc56edSDimitry Andric   };
198591bc56edSDimitry Andric 
198691bc56edSDimitry Andric public:
198791bc56edSDimitry Andric   /// Restoration point.
198891bc56edSDimitry Andric   /// The restoration point is a pointer to an action instead of an iterator
198991bc56edSDimitry Andric   /// because the iterator may be invalidated but not the pointer.
199091bc56edSDimitry Andric   typedef const TypePromotionAction *ConstRestorationPt;
199191bc56edSDimitry Andric   /// Advocate every changes made in that transaction.
199291bc56edSDimitry Andric   void commit();
199391bc56edSDimitry Andric   /// Undo all the changes made after the given point.
199491bc56edSDimitry Andric   void rollback(ConstRestorationPt Point);
199591bc56edSDimitry Andric   /// Get the current restoration point.
199691bc56edSDimitry Andric   ConstRestorationPt getRestorationPoint() const;
199791bc56edSDimitry Andric 
199891bc56edSDimitry Andric   /// \name API for IR modification with state keeping to support rollback.
199991bc56edSDimitry Andric   /// @{
200091bc56edSDimitry Andric   /// Same as Instruction::setOperand.
200191bc56edSDimitry Andric   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
200291bc56edSDimitry Andric   /// Same as Instruction::eraseFromParent.
200391bc56edSDimitry Andric   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
200491bc56edSDimitry Andric   /// Same as Value::replaceAllUsesWith.
200591bc56edSDimitry Andric   void replaceAllUsesWith(Instruction *Inst, Value *New);
200691bc56edSDimitry Andric   /// Same as Value::mutateType.
200791bc56edSDimitry Andric   void mutateType(Instruction *Inst, Type *NewTy);
200891bc56edSDimitry Andric   /// Same as IRBuilder::createTrunc.
200939d628a0SDimitry Andric   Value *createTrunc(Instruction *Opnd, Type *Ty);
201091bc56edSDimitry Andric   /// Same as IRBuilder::createSExt.
201139d628a0SDimitry Andric   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
201239d628a0SDimitry Andric   /// Same as IRBuilder::createZExt.
201339d628a0SDimitry Andric   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
201491bc56edSDimitry Andric   /// Same as Instruction::moveBefore.
201591bc56edSDimitry Andric   void moveBefore(Instruction *Inst, Instruction *Before);
201691bc56edSDimitry Andric   /// @}
201791bc56edSDimitry Andric 
201891bc56edSDimitry Andric private:
201991bc56edSDimitry Andric   /// The ordered list of actions made so far.
202091bc56edSDimitry Andric   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
202191bc56edSDimitry Andric   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
202291bc56edSDimitry Andric };
202391bc56edSDimitry Andric 
202491bc56edSDimitry Andric void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
202591bc56edSDimitry Andric                                           Value *NewVal) {
202691bc56edSDimitry Andric   Actions.push_back(
202791bc56edSDimitry Andric       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
202891bc56edSDimitry Andric }
202991bc56edSDimitry Andric 
203091bc56edSDimitry Andric void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
203191bc56edSDimitry Andric                                                 Value *NewVal) {
203291bc56edSDimitry Andric   Actions.push_back(
203391bc56edSDimitry Andric       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
203491bc56edSDimitry Andric }
203591bc56edSDimitry Andric 
203691bc56edSDimitry Andric void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
203791bc56edSDimitry Andric                                                   Value *New) {
203891bc56edSDimitry Andric   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
203991bc56edSDimitry Andric }
204091bc56edSDimitry Andric 
204191bc56edSDimitry Andric void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
204291bc56edSDimitry Andric   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
204391bc56edSDimitry Andric }
204491bc56edSDimitry Andric 
204539d628a0SDimitry Andric Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
204691bc56edSDimitry Andric                                              Type *Ty) {
204791bc56edSDimitry Andric   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
204839d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
204991bc56edSDimitry Andric   Actions.push_back(std::move(Ptr));
205039d628a0SDimitry Andric   return Val;
205191bc56edSDimitry Andric }
205291bc56edSDimitry Andric 
205339d628a0SDimitry Andric Value *TypePromotionTransaction::createSExt(Instruction *Inst,
205491bc56edSDimitry Andric                                             Value *Opnd, Type *Ty) {
205591bc56edSDimitry Andric   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
205639d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
205791bc56edSDimitry Andric   Actions.push_back(std::move(Ptr));
205839d628a0SDimitry Andric   return Val;
205939d628a0SDimitry Andric }
206039d628a0SDimitry Andric 
206139d628a0SDimitry Andric Value *TypePromotionTransaction::createZExt(Instruction *Inst,
206239d628a0SDimitry Andric                                             Value *Opnd, Type *Ty) {
206339d628a0SDimitry Andric   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
206439d628a0SDimitry Andric   Value *Val = Ptr->getBuiltValue();
206539d628a0SDimitry Andric   Actions.push_back(std::move(Ptr));
206639d628a0SDimitry Andric   return Val;
206791bc56edSDimitry Andric }
206891bc56edSDimitry Andric 
206991bc56edSDimitry Andric void TypePromotionTransaction::moveBefore(Instruction *Inst,
207091bc56edSDimitry Andric                                           Instruction *Before) {
207191bc56edSDimitry Andric   Actions.push_back(
207291bc56edSDimitry Andric       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
207391bc56edSDimitry Andric }
207491bc56edSDimitry Andric 
207591bc56edSDimitry Andric TypePromotionTransaction::ConstRestorationPt
207691bc56edSDimitry Andric TypePromotionTransaction::getRestorationPoint() const {
207791bc56edSDimitry Andric   return !Actions.empty() ? Actions.back().get() : nullptr;
207891bc56edSDimitry Andric }
207991bc56edSDimitry Andric 
208091bc56edSDimitry Andric void TypePromotionTransaction::commit() {
208191bc56edSDimitry Andric   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
208291bc56edSDimitry Andric        ++It)
208391bc56edSDimitry Andric     (*It)->commit();
208491bc56edSDimitry Andric   Actions.clear();
208591bc56edSDimitry Andric }
208691bc56edSDimitry Andric 
208791bc56edSDimitry Andric void TypePromotionTransaction::rollback(
208891bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt Point) {
208991bc56edSDimitry Andric   while (!Actions.empty() && Point != Actions.back().get()) {
209091bc56edSDimitry Andric     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
209191bc56edSDimitry Andric     Curr->undo();
209291bc56edSDimitry Andric   }
209391bc56edSDimitry Andric }
209491bc56edSDimitry Andric 
209591bc56edSDimitry Andric /// \brief A helper class for matching addressing modes.
209691bc56edSDimitry Andric ///
209791bc56edSDimitry Andric /// This encapsulates the logic for matching the target-legal addressing modes.
209891bc56edSDimitry Andric class AddressingModeMatcher {
209991bc56edSDimitry Andric   SmallVectorImpl<Instruction*> &AddrModeInsts;
2100ff0cc061SDimitry Andric   const TargetMachine &TM;
210191bc56edSDimitry Andric   const TargetLowering &TLI;
210291bc56edSDimitry Andric 
210391bc56edSDimitry Andric   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
210491bc56edSDimitry Andric   /// the memory instruction that we're computing this address for.
210591bc56edSDimitry Andric   Type *AccessTy;
210697bc6c73SDimitry Andric   unsigned AddrSpace;
210791bc56edSDimitry Andric   Instruction *MemoryInst;
210891bc56edSDimitry Andric 
210991bc56edSDimitry Andric   /// AddrMode - This is the addressing mode that we're building up.  This is
211091bc56edSDimitry Andric   /// part of the return value of this addressing mode matching stuff.
211191bc56edSDimitry Andric   ExtAddrMode &AddrMode;
211291bc56edSDimitry Andric 
21138f0fd8f6SDimitry Andric   /// The instructions inserted by other CodeGenPrepare optimizations.
21148f0fd8f6SDimitry Andric   const SetOfInstrs &InsertedInsts;
211591bc56edSDimitry Andric   /// A map from the instructions to their type before promotion.
211691bc56edSDimitry Andric   InstrToOrigTy &PromotedInsts;
211791bc56edSDimitry Andric   /// The ongoing transaction where every action should be registered.
211891bc56edSDimitry Andric   TypePromotionTransaction &TPT;
211991bc56edSDimitry Andric 
212091bc56edSDimitry Andric   /// IgnoreProfitability - This is set to true when we should not do
212191bc56edSDimitry Andric   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
212291bc56edSDimitry Andric   /// always returns true.
212391bc56edSDimitry Andric   bool IgnoreProfitability;
212491bc56edSDimitry Andric 
212591bc56edSDimitry Andric   AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
212697bc6c73SDimitry Andric                         const TargetMachine &TM, Type *AT, unsigned AS,
212797bc6c73SDimitry Andric                         Instruction *MI, ExtAddrMode &AM,
21288f0fd8f6SDimitry Andric                         const SetOfInstrs &InsertedInsts,
212991bc56edSDimitry Andric                         InstrToOrigTy &PromotedInsts,
213091bc56edSDimitry Andric                         TypePromotionTransaction &TPT)
2131ff0cc061SDimitry Andric       : AddrModeInsts(AMI), TM(TM),
2132ff0cc061SDimitry Andric         TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2133ff0cc061SDimitry Andric                  ->getTargetLowering()),
213497bc6c73SDimitry Andric         AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
21358f0fd8f6SDimitry Andric         InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT) {
213691bc56edSDimitry Andric     IgnoreProfitability = false;
213791bc56edSDimitry Andric   }
213891bc56edSDimitry Andric public:
213991bc56edSDimitry Andric 
214091bc56edSDimitry Andric   /// Match - Find the maximal addressing mode that a load/store of V can fold,
214191bc56edSDimitry Andric   /// give an access type of AccessTy.  This returns a list of involved
214291bc56edSDimitry Andric   /// instructions in AddrModeInsts.
21438f0fd8f6SDimitry Andric   /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
214491bc56edSDimitry Andric   /// optimizations.
214591bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
214691bc56edSDimitry Andric   /// \p The ongoing transaction where every action should be registered.
214797bc6c73SDimitry Andric   static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
214891bc56edSDimitry Andric                            Instruction *MemoryInst,
214991bc56edSDimitry Andric                            SmallVectorImpl<Instruction*> &AddrModeInsts,
2150ff0cc061SDimitry Andric                            const TargetMachine &TM,
21518f0fd8f6SDimitry Andric                            const SetOfInstrs &InsertedInsts,
215291bc56edSDimitry Andric                            InstrToOrigTy &PromotedInsts,
215391bc56edSDimitry Andric                            TypePromotionTransaction &TPT) {
215491bc56edSDimitry Andric     ExtAddrMode Result;
215591bc56edSDimitry Andric 
215697bc6c73SDimitry Andric     bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
21578f0fd8f6SDimitry Andric                                          MemoryInst, Result, InsertedInsts,
215891bc56edSDimitry Andric                                          PromotedInsts, TPT).MatchAddr(V, 0);
215991bc56edSDimitry Andric     (void)Success; assert(Success && "Couldn't select *anything*?");
216091bc56edSDimitry Andric     return Result;
216191bc56edSDimitry Andric   }
216291bc56edSDimitry Andric private:
216391bc56edSDimitry Andric   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
216491bc56edSDimitry Andric   bool MatchAddr(Value *V, unsigned Depth);
216591bc56edSDimitry Andric   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
216691bc56edSDimitry Andric                           bool *MovedAway = nullptr);
216791bc56edSDimitry Andric   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
216891bc56edSDimitry Andric                                             ExtAddrMode &AMBefore,
216991bc56edSDimitry Andric                                             ExtAddrMode &AMAfter);
217091bc56edSDimitry Andric   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2171ff0cc061SDimitry Andric   bool IsPromotionProfitable(unsigned NewCost, unsigned OldCost,
217291bc56edSDimitry Andric                              Value *PromotedOperand) const;
217391bc56edSDimitry Andric };
217491bc56edSDimitry Andric 
217591bc56edSDimitry Andric /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
217691bc56edSDimitry Andric /// Return true and update AddrMode if this addr mode is legal for the target,
217791bc56edSDimitry Andric /// false if not.
217891bc56edSDimitry Andric bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
217991bc56edSDimitry Andric                                              unsigned Depth) {
218091bc56edSDimitry Andric   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
218191bc56edSDimitry Andric   // mode.  Just process that directly.
218291bc56edSDimitry Andric   if (Scale == 1)
218391bc56edSDimitry Andric     return MatchAddr(ScaleReg, Depth);
218491bc56edSDimitry Andric 
218591bc56edSDimitry Andric   // If the scale is 0, it takes nothing to add this.
218691bc56edSDimitry Andric   if (Scale == 0)
218791bc56edSDimitry Andric     return true;
218891bc56edSDimitry Andric 
218991bc56edSDimitry Andric   // If we already have a scale of this value, we can add to it, otherwise, we
219091bc56edSDimitry Andric   // need an available scale field.
219191bc56edSDimitry Andric   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
219291bc56edSDimitry Andric     return false;
219391bc56edSDimitry Andric 
219491bc56edSDimitry Andric   ExtAddrMode TestAddrMode = AddrMode;
219591bc56edSDimitry Andric 
219691bc56edSDimitry Andric   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
219791bc56edSDimitry Andric   // [A+B + A*7] -> [B+A*8].
219891bc56edSDimitry Andric   TestAddrMode.Scale += Scale;
219991bc56edSDimitry Andric   TestAddrMode.ScaledReg = ScaleReg;
220091bc56edSDimitry Andric 
220191bc56edSDimitry Andric   // If the new address isn't legal, bail out.
220297bc6c73SDimitry Andric   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy, AddrSpace))
220391bc56edSDimitry Andric     return false;
220491bc56edSDimitry Andric 
220591bc56edSDimitry Andric   // It was legal, so commit it.
220691bc56edSDimitry Andric   AddrMode = TestAddrMode;
220791bc56edSDimitry Andric 
220891bc56edSDimitry Andric   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
220991bc56edSDimitry Andric   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
221091bc56edSDimitry Andric   // X*Scale + C*Scale to addr mode.
221191bc56edSDimitry Andric   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
221291bc56edSDimitry Andric   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
221391bc56edSDimitry Andric       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
221491bc56edSDimitry Andric     TestAddrMode.ScaledReg = AddLHS;
221591bc56edSDimitry Andric     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
221691bc56edSDimitry Andric 
221791bc56edSDimitry Andric     // If this addressing mode is legal, commit it and remember that we folded
221891bc56edSDimitry Andric     // this instruction.
221997bc6c73SDimitry Andric     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy, AddrSpace)) {
222091bc56edSDimitry Andric       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
222191bc56edSDimitry Andric       AddrMode = TestAddrMode;
222291bc56edSDimitry Andric       return true;
222391bc56edSDimitry Andric     }
222491bc56edSDimitry Andric   }
222591bc56edSDimitry Andric 
222691bc56edSDimitry Andric   // Otherwise, not (x+c)*scale, just return what we have.
222791bc56edSDimitry Andric   return true;
222891bc56edSDimitry Andric }
222991bc56edSDimitry Andric 
223091bc56edSDimitry Andric /// MightBeFoldableInst - This is a little filter, which returns true if an
223191bc56edSDimitry Andric /// addressing computation involving I might be folded into a load/store
223291bc56edSDimitry Andric /// accessing it.  This doesn't need to be perfect, but needs to accept at least
223391bc56edSDimitry Andric /// the set of instructions that MatchOperationAddr can.
223491bc56edSDimitry Andric static bool MightBeFoldableInst(Instruction *I) {
223591bc56edSDimitry Andric   switch (I->getOpcode()) {
223691bc56edSDimitry Andric   case Instruction::BitCast:
223791bc56edSDimitry Andric   case Instruction::AddrSpaceCast:
223891bc56edSDimitry Andric     // Don't touch identity bitcasts.
223991bc56edSDimitry Andric     if (I->getType() == I->getOperand(0)->getType())
224091bc56edSDimitry Andric       return false;
224191bc56edSDimitry Andric     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
224291bc56edSDimitry Andric   case Instruction::PtrToInt:
224391bc56edSDimitry Andric     // PtrToInt is always a noop, as we know that the int type is pointer sized.
224491bc56edSDimitry Andric     return true;
224591bc56edSDimitry Andric   case Instruction::IntToPtr:
224691bc56edSDimitry Andric     // We know the input is intptr_t, so this is foldable.
224791bc56edSDimitry Andric     return true;
224891bc56edSDimitry Andric   case Instruction::Add:
224991bc56edSDimitry Andric     return true;
225091bc56edSDimitry Andric   case Instruction::Mul:
225191bc56edSDimitry Andric   case Instruction::Shl:
225291bc56edSDimitry Andric     // Can only handle X*C and X << C.
225391bc56edSDimitry Andric     return isa<ConstantInt>(I->getOperand(1));
225491bc56edSDimitry Andric   case Instruction::GetElementPtr:
225591bc56edSDimitry Andric     return true;
225691bc56edSDimitry Andric   default:
225791bc56edSDimitry Andric     return false;
225891bc56edSDimitry Andric   }
225991bc56edSDimitry Andric }
226091bc56edSDimitry Andric 
226139d628a0SDimitry Andric /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
226239d628a0SDimitry Andric /// \note \p Val is assumed to be the product of some type promotion.
226339d628a0SDimitry Andric /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
226439d628a0SDimitry Andric /// to be legal, as the non-promoted value would have had the same state.
226539d628a0SDimitry Andric static bool isPromotedInstructionLegal(const TargetLowering &TLI, Value *Val) {
226639d628a0SDimitry Andric   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
226739d628a0SDimitry Andric   if (!PromotedInst)
226839d628a0SDimitry Andric     return false;
226939d628a0SDimitry Andric   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
227039d628a0SDimitry Andric   // If the ISDOpcode is undefined, it was undefined before the promotion.
227139d628a0SDimitry Andric   if (!ISDOpcode)
227239d628a0SDimitry Andric     return true;
227339d628a0SDimitry Andric   // Otherwise, check if the promoted instruction is legal or not.
227439d628a0SDimitry Andric   return TLI.isOperationLegalOrCustom(
227539d628a0SDimitry Andric       ISDOpcode, TLI.getValueType(PromotedInst->getType()));
227639d628a0SDimitry Andric }
227739d628a0SDimitry Andric 
227891bc56edSDimitry Andric /// \brief Hepler class to perform type promotion.
227991bc56edSDimitry Andric class TypePromotionHelper {
228039d628a0SDimitry Andric   /// \brief Utility function to check whether or not a sign or zero extension
228139d628a0SDimitry Andric   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
228239d628a0SDimitry Andric   /// either using the operands of \p Inst or promoting \p Inst.
228339d628a0SDimitry Andric   /// The type of the extension is defined by \p IsSExt.
228491bc56edSDimitry Andric   /// In other words, check if:
228539d628a0SDimitry Andric   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
228691bc56edSDimitry Andric   /// #1 Promotion applies:
228739d628a0SDimitry Andric   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
228891bc56edSDimitry Andric   /// #2 Operand reuses:
228939d628a0SDimitry Andric   /// ext opnd1 to ConsideredExtType.
229091bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
229139d628a0SDimitry Andric   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
229239d628a0SDimitry Andric                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
229391bc56edSDimitry Andric 
229491bc56edSDimitry Andric   /// \brief Utility function to determine if \p OpIdx should be promoted when
229591bc56edSDimitry Andric   /// promoting \p Inst.
229639d628a0SDimitry Andric   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
229791bc56edSDimitry Andric     if (isa<SelectInst>(Inst) && OpIdx == 0)
229891bc56edSDimitry Andric       return false;
229991bc56edSDimitry Andric     return true;
230091bc56edSDimitry Andric   }
230191bc56edSDimitry Andric 
230239d628a0SDimitry Andric   /// \brief Utility function to promote the operand of \p Ext when this
230339d628a0SDimitry Andric   /// operand is a promotable trunc or sext or zext.
230491bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
2305ff0cc061SDimitry Andric   /// \p CreatedInstsCost[out] contains the cost of all instructions
230639d628a0SDimitry Andric   /// created to promote the operand of Ext.
230739d628a0SDimitry Andric   /// Newly added extensions are inserted in \p Exts.
230839d628a0SDimitry Andric   /// Newly added truncates are inserted in \p Truncs.
230991bc56edSDimitry Andric   /// Should never be called directly.
231039d628a0SDimitry Andric   /// \return The promoted value which is used instead of Ext.
231139d628a0SDimitry Andric   static Value *promoteOperandForTruncAndAnyExt(
231239d628a0SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
2313ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
231439d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
2315ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
231691bc56edSDimitry Andric 
231739d628a0SDimitry Andric   /// \brief Utility function to promote the operand of \p Ext when this
231891bc56edSDimitry Andric   /// operand is promotable and is not a supported trunc or sext.
231991bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
2320ff0cc061SDimitry Andric   /// \p CreatedInstsCost[out] contains the cost of all the instructions
232139d628a0SDimitry Andric   /// created to promote the operand of Ext.
232239d628a0SDimitry Andric   /// Newly added extensions are inserted in \p Exts.
232339d628a0SDimitry Andric   /// Newly added truncates are inserted in \p Truncs.
232491bc56edSDimitry Andric   /// Should never be called directly.
232539d628a0SDimitry Andric   /// \return The promoted value which is used instead of Ext.
2326ff0cc061SDimitry Andric   static Value *promoteOperandForOther(Instruction *Ext,
2327ff0cc061SDimitry Andric                                        TypePromotionTransaction &TPT,
2328ff0cc061SDimitry Andric                                        InstrToOrigTy &PromotedInsts,
2329ff0cc061SDimitry Andric                                        unsigned &CreatedInstsCost,
233039d628a0SDimitry Andric                                        SmallVectorImpl<Instruction *> *Exts,
2331ff0cc061SDimitry Andric                                        SmallVectorImpl<Instruction *> *Truncs,
2332ff0cc061SDimitry Andric                                        const TargetLowering &TLI, bool IsSExt);
233339d628a0SDimitry Andric 
233439d628a0SDimitry Andric   /// \see promoteOperandForOther.
2335ff0cc061SDimitry Andric   static Value *signExtendOperandForOther(
2336ff0cc061SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
2337ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
233839d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
2339ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2340ff0cc061SDimitry Andric     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2341ff0cc061SDimitry Andric                                   Exts, Truncs, TLI, true);
234239d628a0SDimitry Andric   }
234339d628a0SDimitry Andric 
234439d628a0SDimitry Andric   /// \see promoteOperandForOther.
2345ff0cc061SDimitry Andric   static Value *zeroExtendOperandForOther(
2346ff0cc061SDimitry Andric       Instruction *Ext, TypePromotionTransaction &TPT,
2347ff0cc061SDimitry Andric       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
234839d628a0SDimitry Andric       SmallVectorImpl<Instruction *> *Exts,
2349ff0cc061SDimitry Andric       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2350ff0cc061SDimitry Andric     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2351ff0cc061SDimitry Andric                                   Exts, Truncs, TLI, false);
235239d628a0SDimitry Andric   }
235391bc56edSDimitry Andric 
235491bc56edSDimitry Andric public:
235539d628a0SDimitry Andric   /// Type for the utility function that promotes the operand of Ext.
235639d628a0SDimitry Andric   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
2357ff0cc061SDimitry Andric                            InstrToOrigTy &PromotedInsts,
2358ff0cc061SDimitry Andric                            unsigned &CreatedInstsCost,
235939d628a0SDimitry Andric                            SmallVectorImpl<Instruction *> *Exts,
2360ff0cc061SDimitry Andric                            SmallVectorImpl<Instruction *> *Truncs,
2361ff0cc061SDimitry Andric                            const TargetLowering &TLI);
236239d628a0SDimitry Andric   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
236339d628a0SDimitry Andric   /// action to promote the operand of \p Ext instead of using Ext.
236491bc56edSDimitry Andric   /// \return NULL if no promotable action is possible with the current
236591bc56edSDimitry Andric   /// sign extension.
23668f0fd8f6SDimitry Andric   /// \p InsertedInsts keeps track of all the instructions inserted by the
23678f0fd8f6SDimitry Andric   /// other CodeGenPrepare optimizations. This information is important
236891bc56edSDimitry Andric   /// because we do not want to promote these instructions as CodeGenPrepare
236991bc56edSDimitry Andric   /// will reinsert them later. Thus creating an infinite loop: create/remove.
237091bc56edSDimitry Andric   /// \p PromotedInsts maps the instructions to their type before promotion.
23718f0fd8f6SDimitry Andric   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
237291bc56edSDimitry Andric                           const TargetLowering &TLI,
237391bc56edSDimitry Andric                           const InstrToOrigTy &PromotedInsts);
237491bc56edSDimitry Andric };
237591bc56edSDimitry Andric 
237691bc56edSDimitry Andric bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
237739d628a0SDimitry Andric                                         Type *ConsideredExtType,
237839d628a0SDimitry Andric                                         const InstrToOrigTy &PromotedInsts,
237939d628a0SDimitry Andric                                         bool IsSExt) {
238039d628a0SDimitry Andric   // The promotion helper does not know how to deal with vector types yet.
238139d628a0SDimitry Andric   // To be able to fix that, we would need to fix the places where we
238239d628a0SDimitry Andric   // statically extend, e.g., constants and such.
238339d628a0SDimitry Andric   if (Inst->getType()->isVectorTy())
238439d628a0SDimitry Andric     return false;
238539d628a0SDimitry Andric 
238639d628a0SDimitry Andric   // We can always get through zext.
238739d628a0SDimitry Andric   if (isa<ZExtInst>(Inst))
238839d628a0SDimitry Andric     return true;
238939d628a0SDimitry Andric 
239039d628a0SDimitry Andric   // sext(sext) is ok too.
239139d628a0SDimitry Andric   if (IsSExt && isa<SExtInst>(Inst))
239291bc56edSDimitry Andric     return true;
239391bc56edSDimitry Andric 
239491bc56edSDimitry Andric   // We can get through binary operator, if it is legal. In other words, the
239591bc56edSDimitry Andric   // binary operator must have a nuw or nsw flag.
239691bc56edSDimitry Andric   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
239791bc56edSDimitry Andric   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
239839d628a0SDimitry Andric       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
239939d628a0SDimitry Andric        (IsSExt && BinOp->hasNoSignedWrap())))
240091bc56edSDimitry Andric     return true;
240191bc56edSDimitry Andric 
240291bc56edSDimitry Andric   // Check if we can do the following simplification.
240339d628a0SDimitry Andric   // ext(trunc(opnd)) --> ext(opnd)
240491bc56edSDimitry Andric   if (!isa<TruncInst>(Inst))
240591bc56edSDimitry Andric     return false;
240691bc56edSDimitry Andric 
240791bc56edSDimitry Andric   Value *OpndVal = Inst->getOperand(0);
240839d628a0SDimitry Andric   // Check if we can use this operand in the extension.
240939d628a0SDimitry Andric   // If the type is larger than the result type of the extension,
241091bc56edSDimitry Andric   // we cannot.
241139d628a0SDimitry Andric   if (!OpndVal->getType()->isIntegerTy() ||
241239d628a0SDimitry Andric       OpndVal->getType()->getIntegerBitWidth() >
241339d628a0SDimitry Andric           ConsideredExtType->getIntegerBitWidth())
241491bc56edSDimitry Andric     return false;
241591bc56edSDimitry Andric 
241691bc56edSDimitry Andric   // If the operand of the truncate is not an instruction, we will not have
241791bc56edSDimitry Andric   // any information on the dropped bits.
241891bc56edSDimitry Andric   // (Actually we could for constant but it is not worth the extra logic).
241991bc56edSDimitry Andric   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
242091bc56edSDimitry Andric   if (!Opnd)
242191bc56edSDimitry Andric     return false;
242291bc56edSDimitry Andric 
242391bc56edSDimitry Andric   // Check if the source of the type is narrow enough.
242439d628a0SDimitry Andric   // I.e., check that trunc just drops extended bits of the same kind of
242539d628a0SDimitry Andric   // the extension.
242639d628a0SDimitry Andric   // #1 get the type of the operand and check the kind of the extended bits.
242791bc56edSDimitry Andric   const Type *OpndType;
242891bc56edSDimitry Andric   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
242939d628a0SDimitry Andric   if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
243039d628a0SDimitry Andric     OpndType = It->second.Ty;
243139d628a0SDimitry Andric   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
243239d628a0SDimitry Andric     OpndType = Opnd->getOperand(0)->getType();
243391bc56edSDimitry Andric   else
243491bc56edSDimitry Andric     return false;
243591bc56edSDimitry Andric 
243639d628a0SDimitry Andric   // #2 check that the truncate just drop extended bits.
243791bc56edSDimitry Andric   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
243891bc56edSDimitry Andric     return true;
243991bc56edSDimitry Andric 
244091bc56edSDimitry Andric   return false;
244191bc56edSDimitry Andric }
244291bc56edSDimitry Andric 
244391bc56edSDimitry Andric TypePromotionHelper::Action TypePromotionHelper::getAction(
24448f0fd8f6SDimitry Andric     Instruction *Ext, const SetOfInstrs &InsertedInsts,
244591bc56edSDimitry Andric     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
244639d628a0SDimitry Andric   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
244739d628a0SDimitry Andric          "Unexpected instruction type");
244839d628a0SDimitry Andric   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
244939d628a0SDimitry Andric   Type *ExtTy = Ext->getType();
245039d628a0SDimitry Andric   bool IsSExt = isa<SExtInst>(Ext);
245139d628a0SDimitry Andric   // If the operand of the extension is not an instruction, we cannot
245291bc56edSDimitry Andric   // get through.
245391bc56edSDimitry Andric   // If it, check we can get through.
245439d628a0SDimitry Andric   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
245591bc56edSDimitry Andric     return nullptr;
245691bc56edSDimitry Andric 
245791bc56edSDimitry Andric   // Do not promote if the operand has been added by codegenprepare.
245891bc56edSDimitry Andric   // Otherwise, it means we are undoing an optimization that is likely to be
245991bc56edSDimitry Andric   // redone, thus causing potential infinite loop.
24608f0fd8f6SDimitry Andric   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
246191bc56edSDimitry Andric     return nullptr;
246291bc56edSDimitry Andric 
246391bc56edSDimitry Andric   // SExt or Trunc instructions.
246491bc56edSDimitry Andric   // Return the related handler.
246539d628a0SDimitry Andric   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
246639d628a0SDimitry Andric       isa<ZExtInst>(ExtOpnd))
246739d628a0SDimitry Andric     return promoteOperandForTruncAndAnyExt;
246891bc56edSDimitry Andric 
246991bc56edSDimitry Andric   // Regular instruction.
247091bc56edSDimitry Andric   // Abort early if we will have to insert non-free instructions.
247139d628a0SDimitry Andric   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
247291bc56edSDimitry Andric     return nullptr;
247339d628a0SDimitry Andric   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
247491bc56edSDimitry Andric }
247591bc56edSDimitry Andric 
247639d628a0SDimitry Andric Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
247791bc56edSDimitry Andric     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
2478ff0cc061SDimitry Andric     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
247939d628a0SDimitry Andric     SmallVectorImpl<Instruction *> *Exts,
2480ff0cc061SDimitry Andric     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
248191bc56edSDimitry Andric   // By construction, the operand of SExt is an instruction. Otherwise we cannot
248291bc56edSDimitry Andric   // get through it and this method should not be called.
248391bc56edSDimitry Andric   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
248439d628a0SDimitry Andric   Value *ExtVal = SExt;
2485ff0cc061SDimitry Andric   bool HasMergedNonFreeExt = false;
248639d628a0SDimitry Andric   if (isa<ZExtInst>(SExtOpnd)) {
248739d628a0SDimitry Andric     // Replace s|zext(zext(opnd))
248839d628a0SDimitry Andric     // => zext(opnd).
2489ff0cc061SDimitry Andric     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
249039d628a0SDimitry Andric     Value *ZExt =
249139d628a0SDimitry Andric         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
249239d628a0SDimitry Andric     TPT.replaceAllUsesWith(SExt, ZExt);
249339d628a0SDimitry Andric     TPT.eraseInstruction(SExt);
249439d628a0SDimitry Andric     ExtVal = ZExt;
249539d628a0SDimitry Andric   } else {
249639d628a0SDimitry Andric     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
249739d628a0SDimitry Andric     // => z|sext(opnd).
249891bc56edSDimitry Andric     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
249939d628a0SDimitry Andric   }
2500ff0cc061SDimitry Andric   CreatedInstsCost = 0;
250191bc56edSDimitry Andric 
250291bc56edSDimitry Andric   // Remove dead code.
250391bc56edSDimitry Andric   if (SExtOpnd->use_empty())
250491bc56edSDimitry Andric     TPT.eraseInstruction(SExtOpnd);
250591bc56edSDimitry Andric 
250639d628a0SDimitry Andric   // Check if the extension is still needed.
250739d628a0SDimitry Andric   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
250839d628a0SDimitry Andric   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
2509ff0cc061SDimitry Andric     if (ExtInst) {
2510ff0cc061SDimitry Andric       if (Exts)
251139d628a0SDimitry Andric         Exts->push_back(ExtInst);
2512ff0cc061SDimitry Andric       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2513ff0cc061SDimitry Andric     }
251439d628a0SDimitry Andric     return ExtVal;
251539d628a0SDimitry Andric   }
251691bc56edSDimitry Andric 
251739d628a0SDimitry Andric   // At this point we have: ext ty opnd to ty.
251839d628a0SDimitry Andric   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
251939d628a0SDimitry Andric   Value *NextVal = ExtInst->getOperand(0);
252039d628a0SDimitry Andric   TPT.eraseInstruction(ExtInst, NextVal);
252191bc56edSDimitry Andric   return NextVal;
252291bc56edSDimitry Andric }
252391bc56edSDimitry Andric 
252439d628a0SDimitry Andric Value *TypePromotionHelper::promoteOperandForOther(
252539d628a0SDimitry Andric     Instruction *Ext, TypePromotionTransaction &TPT,
2526ff0cc061SDimitry Andric     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
252739d628a0SDimitry Andric     SmallVectorImpl<Instruction *> *Exts,
2528ff0cc061SDimitry Andric     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2529ff0cc061SDimitry Andric     bool IsSExt) {
253039d628a0SDimitry Andric   // By construction, the operand of Ext is an instruction. Otherwise we cannot
253191bc56edSDimitry Andric   // get through it and this method should not be called.
253239d628a0SDimitry Andric   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
2533ff0cc061SDimitry Andric   CreatedInstsCost = 0;
253439d628a0SDimitry Andric   if (!ExtOpnd->hasOneUse()) {
253539d628a0SDimitry Andric     // ExtOpnd will be promoted.
253639d628a0SDimitry Andric     // All its uses, but Ext, will need to use a truncated value of the
253791bc56edSDimitry Andric     // promoted version.
253891bc56edSDimitry Andric     // Create the truncate now.
253939d628a0SDimitry Andric     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
254039d628a0SDimitry Andric     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
254139d628a0SDimitry Andric       ITrunc->removeFromParent();
254291bc56edSDimitry Andric       // Insert it just after the definition.
254339d628a0SDimitry Andric       ITrunc->insertAfter(ExtOpnd);
254439d628a0SDimitry Andric       if (Truncs)
254539d628a0SDimitry Andric         Truncs->push_back(ITrunc);
254639d628a0SDimitry Andric     }
254791bc56edSDimitry Andric 
254839d628a0SDimitry Andric     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
254939d628a0SDimitry Andric     // Restore the operand of Ext (which has been replace by the previous call
255091bc56edSDimitry Andric     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
255139d628a0SDimitry Andric     TPT.setOperand(Ext, 0, ExtOpnd);
255291bc56edSDimitry Andric   }
255391bc56edSDimitry Andric 
255491bc56edSDimitry Andric   // Get through the Instruction:
255591bc56edSDimitry Andric   // 1. Update its type.
255639d628a0SDimitry Andric   // 2. Replace the uses of Ext by Inst.
255739d628a0SDimitry Andric   // 3. Extend each operand that needs to be extended.
255891bc56edSDimitry Andric 
255991bc56edSDimitry Andric   // Remember the original type of the instruction before promotion.
256091bc56edSDimitry Andric   // This is useful to know that the high bits are sign extended bits.
256139d628a0SDimitry Andric   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
256239d628a0SDimitry Andric       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
256391bc56edSDimitry Andric   // Step #1.
256439d628a0SDimitry Andric   TPT.mutateType(ExtOpnd, Ext->getType());
256591bc56edSDimitry Andric   // Step #2.
256639d628a0SDimitry Andric   TPT.replaceAllUsesWith(Ext, ExtOpnd);
256791bc56edSDimitry Andric   // Step #3.
256839d628a0SDimitry Andric   Instruction *ExtForOpnd = Ext;
256991bc56edSDimitry Andric 
257039d628a0SDimitry Andric   DEBUG(dbgs() << "Propagate Ext to operands\n");
257139d628a0SDimitry Andric   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
257291bc56edSDimitry Andric        ++OpIdx) {
257339d628a0SDimitry Andric     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
257439d628a0SDimitry Andric     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
257539d628a0SDimitry Andric         !shouldExtOperand(ExtOpnd, OpIdx)) {
257691bc56edSDimitry Andric       DEBUG(dbgs() << "No need to propagate\n");
257791bc56edSDimitry Andric       continue;
257891bc56edSDimitry Andric     }
257939d628a0SDimitry Andric     // Check if we can statically extend the operand.
258039d628a0SDimitry Andric     Value *Opnd = ExtOpnd->getOperand(OpIdx);
258191bc56edSDimitry Andric     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
258239d628a0SDimitry Andric       DEBUG(dbgs() << "Statically extend\n");
258339d628a0SDimitry Andric       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
258439d628a0SDimitry Andric       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
258539d628a0SDimitry Andric                             : Cst->getValue().zext(BitWidth);
258639d628a0SDimitry Andric       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
258791bc56edSDimitry Andric       continue;
258891bc56edSDimitry Andric     }
258991bc56edSDimitry Andric     // UndefValue are typed, so we have to statically sign extend them.
259091bc56edSDimitry Andric     if (isa<UndefValue>(Opnd)) {
259139d628a0SDimitry Andric       DEBUG(dbgs() << "Statically extend\n");
259239d628a0SDimitry Andric       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
259391bc56edSDimitry Andric       continue;
259491bc56edSDimitry Andric     }
259591bc56edSDimitry Andric 
259691bc56edSDimitry Andric     // Otherwise we have to explicity sign extend the operand.
259739d628a0SDimitry Andric     // Check if Ext was reused to extend an operand.
259839d628a0SDimitry Andric     if (!ExtForOpnd) {
259991bc56edSDimitry Andric       // If yes, create a new one.
260039d628a0SDimitry Andric       DEBUG(dbgs() << "More operands to ext\n");
260139d628a0SDimitry Andric       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
260239d628a0SDimitry Andric         : TPT.createZExt(Ext, Opnd, Ext->getType());
260339d628a0SDimitry Andric       if (!isa<Instruction>(ValForExtOpnd)) {
260439d628a0SDimitry Andric         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
260539d628a0SDimitry Andric         continue;
260639d628a0SDimitry Andric       }
260739d628a0SDimitry Andric       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
260891bc56edSDimitry Andric     }
260939d628a0SDimitry Andric     if (Exts)
261039d628a0SDimitry Andric       Exts->push_back(ExtForOpnd);
261139d628a0SDimitry Andric     TPT.setOperand(ExtForOpnd, 0, Opnd);
261291bc56edSDimitry Andric 
261391bc56edSDimitry Andric     // Move the sign extension before the insertion point.
261439d628a0SDimitry Andric     TPT.moveBefore(ExtForOpnd, ExtOpnd);
261539d628a0SDimitry Andric     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
2616ff0cc061SDimitry Andric     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
261791bc56edSDimitry Andric     // If more sext are required, new instructions will have to be created.
261839d628a0SDimitry Andric     ExtForOpnd = nullptr;
261991bc56edSDimitry Andric   }
262039d628a0SDimitry Andric   if (ExtForOpnd == Ext) {
262139d628a0SDimitry Andric     DEBUG(dbgs() << "Extension is useless now\n");
262239d628a0SDimitry Andric     TPT.eraseInstruction(Ext);
262391bc56edSDimitry Andric   }
262439d628a0SDimitry Andric   return ExtOpnd;
262591bc56edSDimitry Andric }
262691bc56edSDimitry Andric 
262791bc56edSDimitry Andric /// IsPromotionProfitable - Check whether or not promoting an instruction
262891bc56edSDimitry Andric /// to a wider type was profitable.
2629ff0cc061SDimitry Andric /// \p NewCost gives the cost of extension instructions created by the
2630ff0cc061SDimitry Andric /// promotion.
2631ff0cc061SDimitry Andric /// \p OldCost gives the cost of extension instructions before the promotion
2632ff0cc061SDimitry Andric /// plus the number of instructions that have been
2633ff0cc061SDimitry Andric /// matched in the addressing mode the promotion.
263491bc56edSDimitry Andric /// \p PromotedOperand is the value that has been promoted.
263591bc56edSDimitry Andric /// \return True if the promotion is profitable, false otherwise.
2636ff0cc061SDimitry Andric bool AddressingModeMatcher::IsPromotionProfitable(
2637ff0cc061SDimitry Andric     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2638ff0cc061SDimitry Andric   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2639ff0cc061SDimitry Andric   // The cost of the new extensions is greater than the cost of the
2640ff0cc061SDimitry Andric   // old extension plus what we folded.
264191bc56edSDimitry Andric   // This is not profitable.
2642ff0cc061SDimitry Andric   if (NewCost > OldCost)
264391bc56edSDimitry Andric     return false;
2644ff0cc061SDimitry Andric   if (NewCost < OldCost)
264591bc56edSDimitry Andric     return true;
264691bc56edSDimitry Andric   // The promotion is neutral but it may help folding the sign extension in
264791bc56edSDimitry Andric   // loads for instance.
264891bc56edSDimitry Andric   // Check that we did not create an illegal instruction.
264939d628a0SDimitry Andric   return isPromotedInstructionLegal(TLI, PromotedOperand);
265091bc56edSDimitry Andric }
265191bc56edSDimitry Andric 
265291bc56edSDimitry Andric /// MatchOperationAddr - Given an instruction or constant expr, see if we can
265391bc56edSDimitry Andric /// fold the operation into the addressing mode.  If so, update the addressing
265491bc56edSDimitry Andric /// mode and return true, otherwise return false without modifying AddrMode.
265591bc56edSDimitry Andric /// If \p MovedAway is not NULL, it contains the information of whether or
265691bc56edSDimitry Andric /// not AddrInst has to be folded into the addressing mode on success.
265791bc56edSDimitry Andric /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
265891bc56edSDimitry Andric /// because it has been moved away.
265991bc56edSDimitry Andric /// Thus AddrInst must not be added in the matched instructions.
266091bc56edSDimitry Andric /// This state can happen when AddrInst is a sext, since it may be moved away.
266191bc56edSDimitry Andric /// Therefore, AddrInst may not be valid when MovedAway is true and it must
266291bc56edSDimitry Andric /// not be referenced anymore.
266391bc56edSDimitry Andric bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
266491bc56edSDimitry Andric                                                unsigned Depth,
266591bc56edSDimitry Andric                                                bool *MovedAway) {
266691bc56edSDimitry Andric   // Avoid exponential behavior on extremely deep expression trees.
266791bc56edSDimitry Andric   if (Depth >= 5) return false;
266891bc56edSDimitry Andric 
266991bc56edSDimitry Andric   // By default, all matched instructions stay in place.
267091bc56edSDimitry Andric   if (MovedAway)
267191bc56edSDimitry Andric     *MovedAway = false;
267291bc56edSDimitry Andric 
267391bc56edSDimitry Andric   switch (Opcode) {
267491bc56edSDimitry Andric   case Instruction::PtrToInt:
267591bc56edSDimitry Andric     // PtrToInt is always a noop, as we know that the int type is pointer sized.
267691bc56edSDimitry Andric     return MatchAddr(AddrInst->getOperand(0), Depth);
267791bc56edSDimitry Andric   case Instruction::IntToPtr:
267891bc56edSDimitry Andric     // This inttoptr is a no-op if the integer type is pointer sized.
267991bc56edSDimitry Andric     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
268091bc56edSDimitry Andric         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
268191bc56edSDimitry Andric       return MatchAddr(AddrInst->getOperand(0), Depth);
268291bc56edSDimitry Andric     return false;
268391bc56edSDimitry Andric   case Instruction::BitCast:
268491bc56edSDimitry Andric     // BitCast is always a noop, and we can handle it as long as it is
268591bc56edSDimitry Andric     // int->int or pointer->pointer (we don't want int<->fp or something).
268691bc56edSDimitry Andric     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
268791bc56edSDimitry Andric          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
268891bc56edSDimitry Andric         // Don't touch identity bitcasts.  These were probably put here by LSR,
268991bc56edSDimitry Andric         // and we don't want to mess around with them.  Assume it knows what it
269091bc56edSDimitry Andric         // is doing.
269191bc56edSDimitry Andric         AddrInst->getOperand(0)->getType() != AddrInst->getType())
269291bc56edSDimitry Andric       return MatchAddr(AddrInst->getOperand(0), Depth);
269391bc56edSDimitry Andric     return false;
2694ff0cc061SDimitry Andric   case Instruction::AddrSpaceCast: {
2695ff0cc061SDimitry Andric     unsigned SrcAS
2696ff0cc061SDimitry Andric       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
2697ff0cc061SDimitry Andric     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
2698ff0cc061SDimitry Andric     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2699ff0cc061SDimitry Andric       return MatchAddr(AddrInst->getOperand(0), Depth);
2700ff0cc061SDimitry Andric     return false;
2701ff0cc061SDimitry Andric   }
270291bc56edSDimitry Andric   case Instruction::Add: {
270391bc56edSDimitry Andric     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
270491bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
270591bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
270691bc56edSDimitry Andric     // Start a transaction at this point.
270791bc56edSDimitry Andric     // The LHS may match but not the RHS.
270891bc56edSDimitry Andric     // Therefore, we need a higher level restoration point to undo partially
270991bc56edSDimitry Andric     // matched operation.
271091bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
271191bc56edSDimitry Andric         TPT.getRestorationPoint();
271291bc56edSDimitry Andric 
271391bc56edSDimitry Andric     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
271491bc56edSDimitry Andric         MatchAddr(AddrInst->getOperand(0), Depth+1))
271591bc56edSDimitry Andric       return true;
271691bc56edSDimitry Andric 
271791bc56edSDimitry Andric     // Restore the old addr mode info.
271891bc56edSDimitry Andric     AddrMode = BackupAddrMode;
271991bc56edSDimitry Andric     AddrModeInsts.resize(OldSize);
272091bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
272191bc56edSDimitry Andric 
272291bc56edSDimitry Andric     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
272391bc56edSDimitry Andric     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
272491bc56edSDimitry Andric         MatchAddr(AddrInst->getOperand(1), Depth+1))
272591bc56edSDimitry Andric       return true;
272691bc56edSDimitry Andric 
272791bc56edSDimitry Andric     // Otherwise we definitely can't merge the ADD in.
272891bc56edSDimitry Andric     AddrMode = BackupAddrMode;
272991bc56edSDimitry Andric     AddrModeInsts.resize(OldSize);
273091bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
273191bc56edSDimitry Andric     break;
273291bc56edSDimitry Andric   }
273391bc56edSDimitry Andric   //case Instruction::Or:
273491bc56edSDimitry Andric   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
273591bc56edSDimitry Andric   //break;
273691bc56edSDimitry Andric   case Instruction::Mul:
273791bc56edSDimitry Andric   case Instruction::Shl: {
273891bc56edSDimitry Andric     // Can only handle X*C and X << C.
273991bc56edSDimitry Andric     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
274091bc56edSDimitry Andric     if (!RHS)
274191bc56edSDimitry Andric       return false;
274291bc56edSDimitry Andric     int64_t Scale = RHS->getSExtValue();
274391bc56edSDimitry Andric     if (Opcode == Instruction::Shl)
274491bc56edSDimitry Andric       Scale = 1LL << Scale;
274591bc56edSDimitry Andric 
274691bc56edSDimitry Andric     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
274791bc56edSDimitry Andric   }
274891bc56edSDimitry Andric   case Instruction::GetElementPtr: {
274991bc56edSDimitry Andric     // Scan the GEP.  We check it if it contains constant offsets and at most
275091bc56edSDimitry Andric     // one variable offset.
275191bc56edSDimitry Andric     int VariableOperand = -1;
275291bc56edSDimitry Andric     unsigned VariableScale = 0;
275391bc56edSDimitry Andric 
275491bc56edSDimitry Andric     int64_t ConstantOffset = 0;
275591bc56edSDimitry Andric     const DataLayout *TD = TLI.getDataLayout();
275691bc56edSDimitry Andric     gep_type_iterator GTI = gep_type_begin(AddrInst);
275791bc56edSDimitry Andric     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
275891bc56edSDimitry Andric       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
275991bc56edSDimitry Andric         const StructLayout *SL = TD->getStructLayout(STy);
276091bc56edSDimitry Andric         unsigned Idx =
276191bc56edSDimitry Andric           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
276291bc56edSDimitry Andric         ConstantOffset += SL->getElementOffset(Idx);
276391bc56edSDimitry Andric       } else {
276491bc56edSDimitry Andric         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
276591bc56edSDimitry Andric         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
276691bc56edSDimitry Andric           ConstantOffset += CI->getSExtValue()*TypeSize;
276791bc56edSDimitry Andric         } else if (TypeSize) {  // Scales of zero don't do anything.
276891bc56edSDimitry Andric           // We only allow one variable index at the moment.
276991bc56edSDimitry Andric           if (VariableOperand != -1)
277091bc56edSDimitry Andric             return false;
277191bc56edSDimitry Andric 
277291bc56edSDimitry Andric           // Remember the variable index.
277391bc56edSDimitry Andric           VariableOperand = i;
277491bc56edSDimitry Andric           VariableScale = TypeSize;
277591bc56edSDimitry Andric         }
277691bc56edSDimitry Andric       }
277791bc56edSDimitry Andric     }
277891bc56edSDimitry Andric 
277991bc56edSDimitry Andric     // A common case is for the GEP to only do a constant offset.  In this case,
278091bc56edSDimitry Andric     // just add it to the disp field and check validity.
278191bc56edSDimitry Andric     if (VariableOperand == -1) {
278291bc56edSDimitry Andric       AddrMode.BaseOffs += ConstantOffset;
278397bc6c73SDimitry Andric       if (ConstantOffset == 0 ||
278497bc6c73SDimitry Andric           TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace)) {
278591bc56edSDimitry Andric         // Check to see if we can fold the base pointer in too.
278691bc56edSDimitry Andric         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
278791bc56edSDimitry Andric           return true;
278891bc56edSDimitry Andric       }
278991bc56edSDimitry Andric       AddrMode.BaseOffs -= ConstantOffset;
279091bc56edSDimitry Andric       return false;
279191bc56edSDimitry Andric     }
279291bc56edSDimitry Andric 
279391bc56edSDimitry Andric     // Save the valid addressing mode in case we can't match.
279491bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
279591bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
279691bc56edSDimitry Andric 
279791bc56edSDimitry Andric     // See if the scale and offset amount is valid for this target.
279891bc56edSDimitry Andric     AddrMode.BaseOffs += ConstantOffset;
279991bc56edSDimitry Andric 
280091bc56edSDimitry Andric     // Match the base operand of the GEP.
280191bc56edSDimitry Andric     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
280291bc56edSDimitry Andric       // If it couldn't be matched, just stuff the value in a register.
280391bc56edSDimitry Andric       if (AddrMode.HasBaseReg) {
280491bc56edSDimitry Andric         AddrMode = BackupAddrMode;
280591bc56edSDimitry Andric         AddrModeInsts.resize(OldSize);
280691bc56edSDimitry Andric         return false;
280791bc56edSDimitry Andric       }
280891bc56edSDimitry Andric       AddrMode.HasBaseReg = true;
280991bc56edSDimitry Andric       AddrMode.BaseReg = AddrInst->getOperand(0);
281091bc56edSDimitry Andric     }
281191bc56edSDimitry Andric 
281291bc56edSDimitry Andric     // Match the remaining variable portion of the GEP.
281391bc56edSDimitry Andric     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
281491bc56edSDimitry Andric                           Depth)) {
281591bc56edSDimitry Andric       // If it couldn't be matched, try stuffing the base into a register
281691bc56edSDimitry Andric       // instead of matching it, and retrying the match of the scale.
281791bc56edSDimitry Andric       AddrMode = BackupAddrMode;
281891bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
281991bc56edSDimitry Andric       if (AddrMode.HasBaseReg)
282091bc56edSDimitry Andric         return false;
282191bc56edSDimitry Andric       AddrMode.HasBaseReg = true;
282291bc56edSDimitry Andric       AddrMode.BaseReg = AddrInst->getOperand(0);
282391bc56edSDimitry Andric       AddrMode.BaseOffs += ConstantOffset;
282491bc56edSDimitry Andric       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
282591bc56edSDimitry Andric                             VariableScale, Depth)) {
282691bc56edSDimitry Andric         // If even that didn't work, bail.
282791bc56edSDimitry Andric         AddrMode = BackupAddrMode;
282891bc56edSDimitry Andric         AddrModeInsts.resize(OldSize);
282991bc56edSDimitry Andric         return false;
283091bc56edSDimitry Andric       }
283191bc56edSDimitry Andric     }
283291bc56edSDimitry Andric 
283391bc56edSDimitry Andric     return true;
283491bc56edSDimitry Andric   }
283539d628a0SDimitry Andric   case Instruction::SExt:
283639d628a0SDimitry Andric   case Instruction::ZExt: {
283739d628a0SDimitry Andric     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
283839d628a0SDimitry Andric     if (!Ext)
283991bc56edSDimitry Andric       return false;
284091bc56edSDimitry Andric 
284139d628a0SDimitry Andric     // Try to move this ext out of the way of the addressing mode.
284291bc56edSDimitry Andric     // Ask for a method for doing so.
284339d628a0SDimitry Andric     TypePromotionHelper::Action TPH =
28448f0fd8f6SDimitry Andric         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
284591bc56edSDimitry Andric     if (!TPH)
284691bc56edSDimitry Andric       return false;
284791bc56edSDimitry Andric 
284891bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
284991bc56edSDimitry Andric         TPT.getRestorationPoint();
2850ff0cc061SDimitry Andric     unsigned CreatedInstsCost = 0;
2851ff0cc061SDimitry Andric     unsigned ExtCost = !TLI.isExtFree(Ext);
285239d628a0SDimitry Andric     Value *PromotedOperand =
2853ff0cc061SDimitry Andric         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
285491bc56edSDimitry Andric     // SExt has been moved away.
285591bc56edSDimitry Andric     // Thus either it will be rematched later in the recursive calls or it is
285691bc56edSDimitry Andric     // gone. Anyway, we must not fold it into the addressing mode at this point.
285791bc56edSDimitry Andric     // E.g.,
285891bc56edSDimitry Andric     // op = add opnd, 1
285939d628a0SDimitry Andric     // idx = ext op
286091bc56edSDimitry Andric     // addr = gep base, idx
286191bc56edSDimitry Andric     // is now:
286239d628a0SDimitry Andric     // promotedOpnd = ext opnd            <- no match here
286391bc56edSDimitry Andric     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
286491bc56edSDimitry Andric     // addr = gep base, op                <- match
286591bc56edSDimitry Andric     if (MovedAway)
286691bc56edSDimitry Andric       *MovedAway = true;
286791bc56edSDimitry Andric 
286891bc56edSDimitry Andric     assert(PromotedOperand &&
286991bc56edSDimitry Andric            "TypePromotionHelper should have filtered out those cases");
287091bc56edSDimitry Andric 
287191bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
287291bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
287391bc56edSDimitry Andric 
287491bc56edSDimitry Andric     if (!MatchAddr(PromotedOperand, Depth) ||
2875ff0cc061SDimitry Andric         // The total of the new cost is equals to the cost of the created
2876ff0cc061SDimitry Andric         // instructions.
2877ff0cc061SDimitry Andric         // The total of the old cost is equals to the cost of the extension plus
2878ff0cc061SDimitry Andric         // what we have saved in the addressing mode.
2879ff0cc061SDimitry Andric         !IsPromotionProfitable(CreatedInstsCost,
2880ff0cc061SDimitry Andric                                ExtCost + (AddrModeInsts.size() - OldSize),
288191bc56edSDimitry Andric                                PromotedOperand)) {
288291bc56edSDimitry Andric       AddrMode = BackupAddrMode;
288391bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
288491bc56edSDimitry Andric       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
288591bc56edSDimitry Andric       TPT.rollback(LastKnownGood);
288691bc56edSDimitry Andric       return false;
288791bc56edSDimitry Andric     }
288891bc56edSDimitry Andric     return true;
288991bc56edSDimitry Andric   }
289091bc56edSDimitry Andric   }
289191bc56edSDimitry Andric   return false;
289291bc56edSDimitry Andric }
289391bc56edSDimitry Andric 
289491bc56edSDimitry Andric /// MatchAddr - If we can, try to add the value of 'Addr' into the current
289591bc56edSDimitry Andric /// addressing mode.  If Addr can't be added to AddrMode this returns false and
289691bc56edSDimitry Andric /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
289791bc56edSDimitry Andric /// or intptr_t for the target.
289891bc56edSDimitry Andric ///
289991bc56edSDimitry Andric bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
290091bc56edSDimitry Andric   // Start a transaction at this point that we will rollback if the matching
290191bc56edSDimitry Andric   // fails.
290291bc56edSDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
290391bc56edSDimitry Andric       TPT.getRestorationPoint();
290491bc56edSDimitry Andric   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
290591bc56edSDimitry Andric     // Fold in immediates if legal for the target.
290691bc56edSDimitry Andric     AddrMode.BaseOffs += CI->getSExtValue();
290797bc6c73SDimitry Andric     if (TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace))
290891bc56edSDimitry Andric       return true;
290991bc56edSDimitry Andric     AddrMode.BaseOffs -= CI->getSExtValue();
291091bc56edSDimitry Andric   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
291191bc56edSDimitry Andric     // If this is a global variable, try to fold it into the addressing mode.
291291bc56edSDimitry Andric     if (!AddrMode.BaseGV) {
291391bc56edSDimitry Andric       AddrMode.BaseGV = GV;
291497bc6c73SDimitry Andric       if (TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace))
291591bc56edSDimitry Andric         return true;
291691bc56edSDimitry Andric       AddrMode.BaseGV = nullptr;
291791bc56edSDimitry Andric     }
291891bc56edSDimitry Andric   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
291991bc56edSDimitry Andric     ExtAddrMode BackupAddrMode = AddrMode;
292091bc56edSDimitry Andric     unsigned OldSize = AddrModeInsts.size();
292191bc56edSDimitry Andric 
292291bc56edSDimitry Andric     // Check to see if it is possible to fold this operation.
292391bc56edSDimitry Andric     bool MovedAway = false;
292491bc56edSDimitry Andric     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
292591bc56edSDimitry Andric       // This instruction may have been move away. If so, there is nothing
292691bc56edSDimitry Andric       // to check here.
292791bc56edSDimitry Andric       if (MovedAway)
292891bc56edSDimitry Andric         return true;
292991bc56edSDimitry Andric       // Okay, it's possible to fold this.  Check to see if it is actually
293091bc56edSDimitry Andric       // *profitable* to do so.  We use a simple cost model to avoid increasing
293191bc56edSDimitry Andric       // register pressure too much.
293291bc56edSDimitry Andric       if (I->hasOneUse() ||
293391bc56edSDimitry Andric           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
293491bc56edSDimitry Andric         AddrModeInsts.push_back(I);
293591bc56edSDimitry Andric         return true;
293691bc56edSDimitry Andric       }
293791bc56edSDimitry Andric 
293891bc56edSDimitry Andric       // It isn't profitable to do this, roll back.
293991bc56edSDimitry Andric       //cerr << "NOT FOLDING: " << *I;
294091bc56edSDimitry Andric       AddrMode = BackupAddrMode;
294191bc56edSDimitry Andric       AddrModeInsts.resize(OldSize);
294291bc56edSDimitry Andric       TPT.rollback(LastKnownGood);
294391bc56edSDimitry Andric     }
294491bc56edSDimitry Andric   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
294591bc56edSDimitry Andric     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
294691bc56edSDimitry Andric       return true;
294791bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
294891bc56edSDimitry Andric   } else if (isa<ConstantPointerNull>(Addr)) {
294991bc56edSDimitry Andric     // Null pointer gets folded without affecting the addressing mode.
295091bc56edSDimitry Andric     return true;
295191bc56edSDimitry Andric   }
295291bc56edSDimitry Andric 
295391bc56edSDimitry Andric   // Worse case, the target should support [reg] addressing modes. :)
295491bc56edSDimitry Andric   if (!AddrMode.HasBaseReg) {
295591bc56edSDimitry Andric     AddrMode.HasBaseReg = true;
295691bc56edSDimitry Andric     AddrMode.BaseReg = Addr;
295791bc56edSDimitry Andric     // Still check for legality in case the target supports [imm] but not [i+r].
295897bc6c73SDimitry Andric     if (TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace))
295991bc56edSDimitry Andric       return true;
296091bc56edSDimitry Andric     AddrMode.HasBaseReg = false;
296191bc56edSDimitry Andric     AddrMode.BaseReg = nullptr;
296291bc56edSDimitry Andric   }
296391bc56edSDimitry Andric 
296491bc56edSDimitry Andric   // If the base register is already taken, see if we can do [r+r].
296591bc56edSDimitry Andric   if (AddrMode.Scale == 0) {
296691bc56edSDimitry Andric     AddrMode.Scale = 1;
296791bc56edSDimitry Andric     AddrMode.ScaledReg = Addr;
296897bc6c73SDimitry Andric     if (TLI.isLegalAddressingMode(AddrMode, AccessTy, AddrSpace))
296991bc56edSDimitry Andric       return true;
297091bc56edSDimitry Andric     AddrMode.Scale = 0;
297191bc56edSDimitry Andric     AddrMode.ScaledReg = nullptr;
297291bc56edSDimitry Andric   }
297391bc56edSDimitry Andric   // Couldn't match.
297491bc56edSDimitry Andric   TPT.rollback(LastKnownGood);
297591bc56edSDimitry Andric   return false;
297691bc56edSDimitry Andric }
297791bc56edSDimitry Andric 
297891bc56edSDimitry Andric /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
297991bc56edSDimitry Andric /// inline asm call are due to memory operands.  If so, return true, otherwise
298091bc56edSDimitry Andric /// return false.
298191bc56edSDimitry Andric static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2982ff0cc061SDimitry Andric                                     const TargetMachine &TM) {
2983ff0cc061SDimitry Andric   const Function *F = CI->getParent()->getParent();
2984ff0cc061SDimitry Andric   const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2985ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
2986ff0cc061SDimitry Andric   TargetLowering::AsmOperandInfoVector TargetConstraints =
2987ff0cc061SDimitry Andric       TLI->ParseConstraints(TRI, ImmutableCallSite(CI));
298891bc56edSDimitry Andric   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
298991bc56edSDimitry Andric     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
299091bc56edSDimitry Andric 
299191bc56edSDimitry Andric     // Compute the constraint code and ConstraintType to use.
2992ff0cc061SDimitry Andric     TLI->ComputeConstraintToUse(OpInfo, SDValue());
299391bc56edSDimitry Andric 
299491bc56edSDimitry Andric     // If this asm operand is our Value*, and if it isn't an indirect memory
299591bc56edSDimitry Andric     // operand, we can't fold it!
299691bc56edSDimitry Andric     if (OpInfo.CallOperandVal == OpVal &&
299791bc56edSDimitry Andric         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
299891bc56edSDimitry Andric          !OpInfo.isIndirect))
299991bc56edSDimitry Andric       return false;
300091bc56edSDimitry Andric   }
300191bc56edSDimitry Andric 
300291bc56edSDimitry Andric   return true;
300391bc56edSDimitry Andric }
300491bc56edSDimitry Andric 
300591bc56edSDimitry Andric /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
300691bc56edSDimitry Andric /// memory use.  If we find an obviously non-foldable instruction, return true.
300791bc56edSDimitry Andric /// Add the ultimately found memory instructions to MemoryUses.
3008ff0cc061SDimitry Andric static bool FindAllMemoryUses(
3009ff0cc061SDimitry Andric     Instruction *I,
301091bc56edSDimitry Andric     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3011ff0cc061SDimitry Andric     SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
301291bc56edSDimitry Andric   // If we already considered this instruction, we're done.
301339d628a0SDimitry Andric   if (!ConsideredInsts.insert(I).second)
301491bc56edSDimitry Andric     return false;
301591bc56edSDimitry Andric 
301691bc56edSDimitry Andric   // If this is an obviously unfoldable instruction, bail out.
301791bc56edSDimitry Andric   if (!MightBeFoldableInst(I))
301891bc56edSDimitry Andric     return true;
301991bc56edSDimitry Andric 
302091bc56edSDimitry Andric   // Loop over all the uses, recursively processing them.
302191bc56edSDimitry Andric   for (Use &U : I->uses()) {
302291bc56edSDimitry Andric     Instruction *UserI = cast<Instruction>(U.getUser());
302391bc56edSDimitry Andric 
302491bc56edSDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
302591bc56edSDimitry Andric       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
302691bc56edSDimitry Andric       continue;
302791bc56edSDimitry Andric     }
302891bc56edSDimitry Andric 
302991bc56edSDimitry Andric     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
303091bc56edSDimitry Andric       unsigned opNo = U.getOperandNo();
303191bc56edSDimitry Andric       if (opNo == 0) return true; // Storing addr, not into addr.
303291bc56edSDimitry Andric       MemoryUses.push_back(std::make_pair(SI, opNo));
303391bc56edSDimitry Andric       continue;
303491bc56edSDimitry Andric     }
303591bc56edSDimitry Andric 
303691bc56edSDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
303791bc56edSDimitry Andric       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
303891bc56edSDimitry Andric       if (!IA) return true;
303991bc56edSDimitry Andric 
304091bc56edSDimitry Andric       // If this is a memory operand, we're cool, otherwise bail out.
3041ff0cc061SDimitry Andric       if (!IsOperandAMemoryOperand(CI, IA, I, TM))
304291bc56edSDimitry Andric         return true;
304391bc56edSDimitry Andric       continue;
304491bc56edSDimitry Andric     }
304591bc56edSDimitry Andric 
3046ff0cc061SDimitry Andric     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
304791bc56edSDimitry Andric       return true;
304891bc56edSDimitry Andric   }
304991bc56edSDimitry Andric 
305091bc56edSDimitry Andric   return false;
305191bc56edSDimitry Andric }
305291bc56edSDimitry Andric 
305391bc56edSDimitry Andric /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
305491bc56edSDimitry Andric /// the use site that we're folding it into.  If so, there is no cost to
305591bc56edSDimitry Andric /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
305691bc56edSDimitry Andric /// that we know are live at the instruction already.
305791bc56edSDimitry Andric bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
305891bc56edSDimitry Andric                                                    Value *KnownLive2) {
305991bc56edSDimitry Andric   // If Val is either of the known-live values, we know it is live!
306091bc56edSDimitry Andric   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
306191bc56edSDimitry Andric     return true;
306291bc56edSDimitry Andric 
306391bc56edSDimitry Andric   // All values other than instructions and arguments (e.g. constants) are live.
306491bc56edSDimitry Andric   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
306591bc56edSDimitry Andric 
306691bc56edSDimitry Andric   // If Val is a constant sized alloca in the entry block, it is live, this is
306791bc56edSDimitry Andric   // true because it is just a reference to the stack/frame pointer, which is
306891bc56edSDimitry Andric   // live for the whole function.
306991bc56edSDimitry Andric   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
307091bc56edSDimitry Andric     if (AI->isStaticAlloca())
307191bc56edSDimitry Andric       return true;
307291bc56edSDimitry Andric 
307391bc56edSDimitry Andric   // Check to see if this value is already used in the memory instruction's
307491bc56edSDimitry Andric   // block.  If so, it's already live into the block at the very least, so we
307591bc56edSDimitry Andric   // can reasonably fold it.
307691bc56edSDimitry Andric   return Val->isUsedInBasicBlock(MemoryInst->getParent());
307791bc56edSDimitry Andric }
307891bc56edSDimitry Andric 
307991bc56edSDimitry Andric /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
308091bc56edSDimitry Andric /// mode of the machine to fold the specified instruction into a load or store
308191bc56edSDimitry Andric /// that ultimately uses it.  However, the specified instruction has multiple
308291bc56edSDimitry Andric /// uses.  Given this, it may actually increase register pressure to fold it
308391bc56edSDimitry Andric /// into the load.  For example, consider this code:
308491bc56edSDimitry Andric ///
308591bc56edSDimitry Andric ///     X = ...
308691bc56edSDimitry Andric ///     Y = X+1
308791bc56edSDimitry Andric ///     use(Y)   -> nonload/store
308891bc56edSDimitry Andric ///     Z = Y+1
308991bc56edSDimitry Andric ///     load Z
309091bc56edSDimitry Andric ///
309191bc56edSDimitry Andric /// In this case, Y has multiple uses, and can be folded into the load of Z
309291bc56edSDimitry Andric /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
309391bc56edSDimitry Andric /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
309491bc56edSDimitry Andric /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
309591bc56edSDimitry Andric /// number of computations either.
309691bc56edSDimitry Andric ///
309791bc56edSDimitry Andric /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
309891bc56edSDimitry Andric /// X was live across 'load Z' for other reasons, we actually *would* want to
309991bc56edSDimitry Andric /// fold the addressing mode in the Z case.  This would make Y die earlier.
310091bc56edSDimitry Andric bool AddressingModeMatcher::
310191bc56edSDimitry Andric IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
310291bc56edSDimitry Andric                                      ExtAddrMode &AMAfter) {
310391bc56edSDimitry Andric   if (IgnoreProfitability) return true;
310491bc56edSDimitry Andric 
310591bc56edSDimitry Andric   // AMBefore is the addressing mode before this instruction was folded into it,
310691bc56edSDimitry Andric   // and AMAfter is the addressing mode after the instruction was folded.  Get
310791bc56edSDimitry Andric   // the set of registers referenced by AMAfter and subtract out those
310891bc56edSDimitry Andric   // referenced by AMBefore: this is the set of values which folding in this
310991bc56edSDimitry Andric   // address extends the lifetime of.
311091bc56edSDimitry Andric   //
311191bc56edSDimitry Andric   // Note that there are only two potential values being referenced here,
311291bc56edSDimitry Andric   // BaseReg and ScaleReg (global addresses are always available, as are any
311391bc56edSDimitry Andric   // folded immediates).
311491bc56edSDimitry Andric   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
311591bc56edSDimitry Andric 
311691bc56edSDimitry Andric   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
311791bc56edSDimitry Andric   // lifetime wasn't extended by adding this instruction.
311891bc56edSDimitry Andric   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
311991bc56edSDimitry Andric     BaseReg = nullptr;
312091bc56edSDimitry Andric   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
312191bc56edSDimitry Andric     ScaledReg = nullptr;
312291bc56edSDimitry Andric 
312391bc56edSDimitry Andric   // If folding this instruction (and it's subexprs) didn't extend any live
312491bc56edSDimitry Andric   // ranges, we're ok with it.
312591bc56edSDimitry Andric   if (!BaseReg && !ScaledReg)
312691bc56edSDimitry Andric     return true;
312791bc56edSDimitry Andric 
312891bc56edSDimitry Andric   // If all uses of this instruction are ultimately load/store/inlineasm's,
312991bc56edSDimitry Andric   // check to see if their addressing modes will include this instruction.  If
313091bc56edSDimitry Andric   // so, we can fold it into all uses, so it doesn't matter if it has multiple
313191bc56edSDimitry Andric   // uses.
313291bc56edSDimitry Andric   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
313391bc56edSDimitry Andric   SmallPtrSet<Instruction*, 16> ConsideredInsts;
3134ff0cc061SDimitry Andric   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
313591bc56edSDimitry Andric     return false;  // Has a non-memory, non-foldable use!
313691bc56edSDimitry Andric 
313791bc56edSDimitry Andric   // Now that we know that all uses of this instruction are part of a chain of
313891bc56edSDimitry Andric   // computation involving only operations that could theoretically be folded
313991bc56edSDimitry Andric   // into a memory use, loop over each of these uses and see if they could
314091bc56edSDimitry Andric   // *actually* fold the instruction.
314191bc56edSDimitry Andric   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
314291bc56edSDimitry Andric   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
314391bc56edSDimitry Andric     Instruction *User = MemoryUses[i].first;
314491bc56edSDimitry Andric     unsigned OpNo = MemoryUses[i].second;
314591bc56edSDimitry Andric 
314691bc56edSDimitry Andric     // Get the access type of this use.  If the use isn't a pointer, we don't
314791bc56edSDimitry Andric     // know what it accesses.
314891bc56edSDimitry Andric     Value *Address = User->getOperand(OpNo);
314997bc6c73SDimitry Andric     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
315097bc6c73SDimitry Andric     if (!AddrTy)
315191bc56edSDimitry Andric       return false;
315297bc6c73SDimitry Andric     Type *AddressAccessTy = AddrTy->getElementType();
315397bc6c73SDimitry Andric     unsigned AS = AddrTy->getAddressSpace();
315491bc56edSDimitry Andric 
315591bc56edSDimitry Andric     // Do a match against the root of this address, ignoring profitability. This
315691bc56edSDimitry Andric     // will tell us if the addressing mode for the memory operation will
315791bc56edSDimitry Andric     // *actually* cover the shared instruction.
315891bc56edSDimitry Andric     ExtAddrMode Result;
315991bc56edSDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
316091bc56edSDimitry Andric         TPT.getRestorationPoint();
316197bc6c73SDimitry Andric     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
31628f0fd8f6SDimitry Andric                                   MemoryInst, Result, InsertedInsts,
316391bc56edSDimitry Andric                                   PromotedInsts, TPT);
316491bc56edSDimitry Andric     Matcher.IgnoreProfitability = true;
316591bc56edSDimitry Andric     bool Success = Matcher.MatchAddr(Address, 0);
316691bc56edSDimitry Andric     (void)Success; assert(Success && "Couldn't select *anything*?");
316791bc56edSDimitry Andric 
316891bc56edSDimitry Andric     // The match was to check the profitability, the changes made are not
316991bc56edSDimitry Andric     // part of the original matcher. Therefore, they should be dropped
317091bc56edSDimitry Andric     // otherwise the original matcher will not present the right state.
317191bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
317291bc56edSDimitry Andric 
317391bc56edSDimitry Andric     // If the match didn't cover I, then it won't be shared by it.
317491bc56edSDimitry Andric     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
317591bc56edSDimitry Andric                   I) == MatchedAddrModeInsts.end())
317691bc56edSDimitry Andric       return false;
317791bc56edSDimitry Andric 
317891bc56edSDimitry Andric     MatchedAddrModeInsts.clear();
317991bc56edSDimitry Andric   }
318091bc56edSDimitry Andric 
318191bc56edSDimitry Andric   return true;
318291bc56edSDimitry Andric }
318391bc56edSDimitry Andric 
318491bc56edSDimitry Andric } // end anonymous namespace
318591bc56edSDimitry Andric 
318691bc56edSDimitry Andric /// IsNonLocalValue - Return true if the specified values are defined in a
318791bc56edSDimitry Andric /// different basic block than BB.
318891bc56edSDimitry Andric static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
318991bc56edSDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(V))
319091bc56edSDimitry Andric     return I->getParent() != BB;
319191bc56edSDimitry Andric   return false;
319291bc56edSDimitry Andric }
319391bc56edSDimitry Andric 
319491bc56edSDimitry Andric /// OptimizeMemoryInst - Load and Store Instructions often have
319591bc56edSDimitry Andric /// addressing modes that can do significant amounts of computation.  As such,
319691bc56edSDimitry Andric /// instruction selection will try to get the load or store to do as much
319791bc56edSDimitry Andric /// computation as possible for the program.  The problem is that isel can only
319891bc56edSDimitry Andric /// see within a single block.  As such, we sink as much legal addressing mode
319991bc56edSDimitry Andric /// stuff into the block as possible.
320091bc56edSDimitry Andric ///
320191bc56edSDimitry Andric /// This method is used to optimize both load/store and inline asms with memory
320291bc56edSDimitry Andric /// operands.
320391bc56edSDimitry Andric bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
320497bc6c73SDimitry Andric                                         Type *AccessTy, unsigned AddrSpace) {
320591bc56edSDimitry Andric   Value *Repl = Addr;
320691bc56edSDimitry Andric 
320791bc56edSDimitry Andric   // Try to collapse single-value PHI nodes.  This is necessary to undo
320891bc56edSDimitry Andric   // unprofitable PRE transformations.
320991bc56edSDimitry Andric   SmallVector<Value*, 8> worklist;
321091bc56edSDimitry Andric   SmallPtrSet<Value*, 16> Visited;
321191bc56edSDimitry Andric   worklist.push_back(Addr);
321291bc56edSDimitry Andric 
321391bc56edSDimitry Andric   // Use a worklist to iteratively look through PHI nodes, and ensure that
321491bc56edSDimitry Andric   // the addressing mode obtained from the non-PHI roots of the graph
321591bc56edSDimitry Andric   // are equivalent.
321691bc56edSDimitry Andric   Value *Consensus = nullptr;
321791bc56edSDimitry Andric   unsigned NumUsesConsensus = 0;
321891bc56edSDimitry Andric   bool IsNumUsesConsensusValid = false;
321991bc56edSDimitry Andric   SmallVector<Instruction*, 16> AddrModeInsts;
322091bc56edSDimitry Andric   ExtAddrMode AddrMode;
322191bc56edSDimitry Andric   TypePromotionTransaction TPT;
322291bc56edSDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
322391bc56edSDimitry Andric       TPT.getRestorationPoint();
322491bc56edSDimitry Andric   while (!worklist.empty()) {
322591bc56edSDimitry Andric     Value *V = worklist.back();
322691bc56edSDimitry Andric     worklist.pop_back();
322791bc56edSDimitry Andric 
322891bc56edSDimitry Andric     // Break use-def graph loops.
322939d628a0SDimitry Andric     if (!Visited.insert(V).second) {
323091bc56edSDimitry Andric       Consensus = nullptr;
323191bc56edSDimitry Andric       break;
323291bc56edSDimitry Andric     }
323391bc56edSDimitry Andric 
323491bc56edSDimitry Andric     // For a PHI node, push all of its incoming values.
323591bc56edSDimitry Andric     if (PHINode *P = dyn_cast<PHINode>(V)) {
3236ff0cc061SDimitry Andric       for (Value *IncValue : P->incoming_values())
3237ff0cc061SDimitry Andric         worklist.push_back(IncValue);
323891bc56edSDimitry Andric       continue;
323991bc56edSDimitry Andric     }
324091bc56edSDimitry Andric 
324191bc56edSDimitry Andric     // For non-PHIs, determine the addressing mode being computed.
324291bc56edSDimitry Andric     SmallVector<Instruction*, 16> NewAddrModeInsts;
324391bc56edSDimitry Andric     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
324497bc6c73SDimitry Andric       V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
32458f0fd8f6SDimitry Andric       InsertedInsts, PromotedInsts, TPT);
324691bc56edSDimitry Andric 
324791bc56edSDimitry Andric     // This check is broken into two cases with very similar code to avoid using
324891bc56edSDimitry Andric     // getNumUses() as much as possible. Some values have a lot of uses, so
324991bc56edSDimitry Andric     // calling getNumUses() unconditionally caused a significant compile-time
325091bc56edSDimitry Andric     // regression.
325191bc56edSDimitry Andric     if (!Consensus) {
325291bc56edSDimitry Andric       Consensus = V;
325391bc56edSDimitry Andric       AddrMode = NewAddrMode;
325491bc56edSDimitry Andric       AddrModeInsts = NewAddrModeInsts;
325591bc56edSDimitry Andric       continue;
325691bc56edSDimitry Andric     } else if (NewAddrMode == AddrMode) {
325791bc56edSDimitry Andric       if (!IsNumUsesConsensusValid) {
325891bc56edSDimitry Andric         NumUsesConsensus = Consensus->getNumUses();
325991bc56edSDimitry Andric         IsNumUsesConsensusValid = true;
326091bc56edSDimitry Andric       }
326191bc56edSDimitry Andric 
326291bc56edSDimitry Andric       // Ensure that the obtained addressing mode is equivalent to that obtained
326391bc56edSDimitry Andric       // for all other roots of the PHI traversal.  Also, when choosing one
326491bc56edSDimitry Andric       // such root as representative, select the one with the most uses in order
326591bc56edSDimitry Andric       // to keep the cost modeling heuristics in AddressingModeMatcher
326691bc56edSDimitry Andric       // applicable.
326791bc56edSDimitry Andric       unsigned NumUses = V->getNumUses();
326891bc56edSDimitry Andric       if (NumUses > NumUsesConsensus) {
326991bc56edSDimitry Andric         Consensus = V;
327091bc56edSDimitry Andric         NumUsesConsensus = NumUses;
327191bc56edSDimitry Andric         AddrModeInsts = NewAddrModeInsts;
327291bc56edSDimitry Andric       }
327391bc56edSDimitry Andric       continue;
327491bc56edSDimitry Andric     }
327591bc56edSDimitry Andric 
327691bc56edSDimitry Andric     Consensus = nullptr;
327791bc56edSDimitry Andric     break;
327891bc56edSDimitry Andric   }
327991bc56edSDimitry Andric 
328091bc56edSDimitry Andric   // If the addressing mode couldn't be determined, or if multiple different
328191bc56edSDimitry Andric   // ones were determined, bail out now.
328291bc56edSDimitry Andric   if (!Consensus) {
328391bc56edSDimitry Andric     TPT.rollback(LastKnownGood);
328491bc56edSDimitry Andric     return false;
328591bc56edSDimitry Andric   }
328691bc56edSDimitry Andric   TPT.commit();
328791bc56edSDimitry Andric 
328891bc56edSDimitry Andric   // Check to see if any of the instructions supersumed by this addr mode are
328991bc56edSDimitry Andric   // non-local to I's BB.
329091bc56edSDimitry Andric   bool AnyNonLocal = false;
329191bc56edSDimitry Andric   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
329291bc56edSDimitry Andric     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
329391bc56edSDimitry Andric       AnyNonLocal = true;
329491bc56edSDimitry Andric       break;
329591bc56edSDimitry Andric     }
329691bc56edSDimitry Andric   }
329791bc56edSDimitry Andric 
329891bc56edSDimitry Andric   // If all the instructions matched are already in this BB, don't do anything.
329991bc56edSDimitry Andric   if (!AnyNonLocal) {
330091bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
330191bc56edSDimitry Andric     return false;
330291bc56edSDimitry Andric   }
330391bc56edSDimitry Andric 
330491bc56edSDimitry Andric   // Insert this computation right after this user.  Since our caller is
330591bc56edSDimitry Andric   // scanning from the top of the BB to the bottom, reuse of the expr are
330691bc56edSDimitry Andric   // guaranteed to happen later.
330791bc56edSDimitry Andric   IRBuilder<> Builder(MemoryInst);
330891bc56edSDimitry Andric 
330991bc56edSDimitry Andric   // Now that we determined the addressing expression we want to use and know
331091bc56edSDimitry Andric   // that we have to sink it into this block.  Check to see if we have already
331191bc56edSDimitry Andric   // done this for some other load/store instr in this block.  If so, reuse the
331291bc56edSDimitry Andric   // computation.
331391bc56edSDimitry Andric   Value *&SunkAddr = SunkAddrs[Addr];
331491bc56edSDimitry Andric   if (SunkAddr) {
331591bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
331691bc56edSDimitry Andric                  << *MemoryInst << "\n");
331791bc56edSDimitry Andric     if (SunkAddr->getType() != Addr->getType())
331891bc56edSDimitry Andric       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3319ff0cc061SDimitry Andric   } else if (AddrSinkUsingGEPs ||
3320ff0cc061SDimitry Andric              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
3321ff0cc061SDimitry Andric               TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3322ff0cc061SDimitry Andric                   ->useAA())) {
332391bc56edSDimitry Andric     // By default, we use the GEP-based method when AA is used later. This
332491bc56edSDimitry Andric     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
332591bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
332691bc56edSDimitry Andric                  << *MemoryInst << "\n");
332791bc56edSDimitry Andric     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
332891bc56edSDimitry Andric     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
332991bc56edSDimitry Andric 
333091bc56edSDimitry Andric     // First, find the pointer.
333191bc56edSDimitry Andric     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
333291bc56edSDimitry Andric       ResultPtr = AddrMode.BaseReg;
333391bc56edSDimitry Andric       AddrMode.BaseReg = nullptr;
333491bc56edSDimitry Andric     }
333591bc56edSDimitry Andric 
333691bc56edSDimitry Andric     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
333791bc56edSDimitry Andric       // We can't add more than one pointer together, nor can we scale a
333891bc56edSDimitry Andric       // pointer (both of which seem meaningless).
333991bc56edSDimitry Andric       if (ResultPtr || AddrMode.Scale != 1)
334091bc56edSDimitry Andric         return false;
334191bc56edSDimitry Andric 
334291bc56edSDimitry Andric       ResultPtr = AddrMode.ScaledReg;
334391bc56edSDimitry Andric       AddrMode.Scale = 0;
334491bc56edSDimitry Andric     }
334591bc56edSDimitry Andric 
334691bc56edSDimitry Andric     if (AddrMode.BaseGV) {
334791bc56edSDimitry Andric       if (ResultPtr)
334891bc56edSDimitry Andric         return false;
334991bc56edSDimitry Andric 
335091bc56edSDimitry Andric       ResultPtr = AddrMode.BaseGV;
335191bc56edSDimitry Andric     }
335291bc56edSDimitry Andric 
335391bc56edSDimitry Andric     // If the real base value actually came from an inttoptr, then the matcher
335491bc56edSDimitry Andric     // will look through it and provide only the integer value. In that case,
335591bc56edSDimitry Andric     // use it here.
335691bc56edSDimitry Andric     if (!ResultPtr && AddrMode.BaseReg) {
335791bc56edSDimitry Andric       ResultPtr =
335891bc56edSDimitry Andric         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
335991bc56edSDimitry Andric       AddrMode.BaseReg = nullptr;
336091bc56edSDimitry Andric     } else if (!ResultPtr && AddrMode.Scale == 1) {
336191bc56edSDimitry Andric       ResultPtr =
336291bc56edSDimitry Andric         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
336391bc56edSDimitry Andric       AddrMode.Scale = 0;
336491bc56edSDimitry Andric     }
336591bc56edSDimitry Andric 
336691bc56edSDimitry Andric     if (!ResultPtr &&
336791bc56edSDimitry Andric         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
336891bc56edSDimitry Andric       SunkAddr = Constant::getNullValue(Addr->getType());
336991bc56edSDimitry Andric     } else if (!ResultPtr) {
337091bc56edSDimitry Andric       return false;
337191bc56edSDimitry Andric     } else {
337291bc56edSDimitry Andric       Type *I8PtrTy =
337391bc56edSDimitry Andric           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3374ff0cc061SDimitry Andric       Type *I8Ty = Builder.getInt8Ty();
337591bc56edSDimitry Andric 
337691bc56edSDimitry Andric       // Start with the base register. Do this first so that subsequent address
337791bc56edSDimitry Andric       // matching finds it last, which will prevent it from trying to match it
337891bc56edSDimitry Andric       // as the scaled value in case it happens to be a mul. That would be
337991bc56edSDimitry Andric       // problematic if we've sunk a different mul for the scale, because then
338091bc56edSDimitry Andric       // we'd end up sinking both muls.
338191bc56edSDimitry Andric       if (AddrMode.BaseReg) {
338291bc56edSDimitry Andric         Value *V = AddrMode.BaseReg;
338391bc56edSDimitry Andric         if (V->getType() != IntPtrTy)
338491bc56edSDimitry Andric           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
338591bc56edSDimitry Andric 
338691bc56edSDimitry Andric         ResultIndex = V;
338791bc56edSDimitry Andric       }
338891bc56edSDimitry Andric 
338991bc56edSDimitry Andric       // Add the scale value.
339091bc56edSDimitry Andric       if (AddrMode.Scale) {
339191bc56edSDimitry Andric         Value *V = AddrMode.ScaledReg;
339291bc56edSDimitry Andric         if (V->getType() == IntPtrTy) {
339391bc56edSDimitry Andric           // done.
339491bc56edSDimitry Andric         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
339591bc56edSDimitry Andric                    cast<IntegerType>(V->getType())->getBitWidth()) {
339691bc56edSDimitry Andric           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
339791bc56edSDimitry Andric         } else {
339891bc56edSDimitry Andric           // It is only safe to sign extend the BaseReg if we know that the math
339991bc56edSDimitry Andric           // required to create it did not overflow before we extend it. Since
340091bc56edSDimitry Andric           // the original IR value was tossed in favor of a constant back when
340191bc56edSDimitry Andric           // the AddrMode was created we need to bail out gracefully if widths
340291bc56edSDimitry Andric           // do not match instead of extending it.
340391bc56edSDimitry Andric           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
340491bc56edSDimitry Andric           if (I && (ResultIndex != AddrMode.BaseReg))
340591bc56edSDimitry Andric             I->eraseFromParent();
340691bc56edSDimitry Andric           return false;
340791bc56edSDimitry Andric         }
340891bc56edSDimitry Andric 
340991bc56edSDimitry Andric         if (AddrMode.Scale != 1)
341091bc56edSDimitry Andric           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
341191bc56edSDimitry Andric                                 "sunkaddr");
341291bc56edSDimitry Andric         if (ResultIndex)
341391bc56edSDimitry Andric           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
341491bc56edSDimitry Andric         else
341591bc56edSDimitry Andric           ResultIndex = V;
341691bc56edSDimitry Andric       }
341791bc56edSDimitry Andric 
341891bc56edSDimitry Andric       // Add in the Base Offset if present.
341991bc56edSDimitry Andric       if (AddrMode.BaseOffs) {
342091bc56edSDimitry Andric         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
342191bc56edSDimitry Andric         if (ResultIndex) {
342291bc56edSDimitry Andric           // We need to add this separately from the scale above to help with
342391bc56edSDimitry Andric           // SDAG consecutive load/store merging.
342491bc56edSDimitry Andric           if (ResultPtr->getType() != I8PtrTy)
342591bc56edSDimitry Andric             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3426ff0cc061SDimitry Andric           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
342791bc56edSDimitry Andric         }
342891bc56edSDimitry Andric 
342991bc56edSDimitry Andric         ResultIndex = V;
343091bc56edSDimitry Andric       }
343191bc56edSDimitry Andric 
343291bc56edSDimitry Andric       if (!ResultIndex) {
343391bc56edSDimitry Andric         SunkAddr = ResultPtr;
343491bc56edSDimitry Andric       } else {
343591bc56edSDimitry Andric         if (ResultPtr->getType() != I8PtrTy)
343691bc56edSDimitry Andric           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3437ff0cc061SDimitry Andric         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
343891bc56edSDimitry Andric       }
343991bc56edSDimitry Andric 
344091bc56edSDimitry Andric       if (SunkAddr->getType() != Addr->getType())
344191bc56edSDimitry Andric         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
344291bc56edSDimitry Andric     }
344391bc56edSDimitry Andric   } else {
344491bc56edSDimitry Andric     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
344591bc56edSDimitry Andric                  << *MemoryInst << "\n");
344691bc56edSDimitry Andric     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
344791bc56edSDimitry Andric     Value *Result = nullptr;
344891bc56edSDimitry Andric 
344991bc56edSDimitry Andric     // Start with the base register. Do this first so that subsequent address
345091bc56edSDimitry Andric     // matching finds it last, which will prevent it from trying to match it
345191bc56edSDimitry Andric     // as the scaled value in case it happens to be a mul. That would be
345291bc56edSDimitry Andric     // problematic if we've sunk a different mul for the scale, because then
345391bc56edSDimitry Andric     // we'd end up sinking both muls.
345491bc56edSDimitry Andric     if (AddrMode.BaseReg) {
345591bc56edSDimitry Andric       Value *V = AddrMode.BaseReg;
345691bc56edSDimitry Andric       if (V->getType()->isPointerTy())
345791bc56edSDimitry Andric         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
345891bc56edSDimitry Andric       if (V->getType() != IntPtrTy)
345991bc56edSDimitry Andric         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
346091bc56edSDimitry Andric       Result = V;
346191bc56edSDimitry Andric     }
346291bc56edSDimitry Andric 
346391bc56edSDimitry Andric     // Add the scale value.
346491bc56edSDimitry Andric     if (AddrMode.Scale) {
346591bc56edSDimitry Andric       Value *V = AddrMode.ScaledReg;
346691bc56edSDimitry Andric       if (V->getType() == IntPtrTy) {
346791bc56edSDimitry Andric         // done.
346891bc56edSDimitry Andric       } else if (V->getType()->isPointerTy()) {
346991bc56edSDimitry Andric         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
347091bc56edSDimitry Andric       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
347191bc56edSDimitry Andric                  cast<IntegerType>(V->getType())->getBitWidth()) {
347291bc56edSDimitry Andric         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
347391bc56edSDimitry Andric       } else {
347491bc56edSDimitry Andric         // It is only safe to sign extend the BaseReg if we know that the math
347591bc56edSDimitry Andric         // required to create it did not overflow before we extend it. Since
347691bc56edSDimitry Andric         // the original IR value was tossed in favor of a constant back when
347791bc56edSDimitry Andric         // the AddrMode was created we need to bail out gracefully if widths
347891bc56edSDimitry Andric         // do not match instead of extending it.
347991bc56edSDimitry Andric         Instruction *I = dyn_cast_or_null<Instruction>(Result);
348091bc56edSDimitry Andric         if (I && (Result != AddrMode.BaseReg))
348191bc56edSDimitry Andric           I->eraseFromParent();
348291bc56edSDimitry Andric         return false;
348391bc56edSDimitry Andric       }
348491bc56edSDimitry Andric       if (AddrMode.Scale != 1)
348591bc56edSDimitry Andric         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
348691bc56edSDimitry Andric                               "sunkaddr");
348791bc56edSDimitry Andric       if (Result)
348891bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
348991bc56edSDimitry Andric       else
349091bc56edSDimitry Andric         Result = V;
349191bc56edSDimitry Andric     }
349291bc56edSDimitry Andric 
349391bc56edSDimitry Andric     // Add in the BaseGV if present.
349491bc56edSDimitry Andric     if (AddrMode.BaseGV) {
349591bc56edSDimitry Andric       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
349691bc56edSDimitry Andric       if (Result)
349791bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
349891bc56edSDimitry Andric       else
349991bc56edSDimitry Andric         Result = V;
350091bc56edSDimitry Andric     }
350191bc56edSDimitry Andric 
350291bc56edSDimitry Andric     // Add in the Base Offset if present.
350391bc56edSDimitry Andric     if (AddrMode.BaseOffs) {
350491bc56edSDimitry Andric       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
350591bc56edSDimitry Andric       if (Result)
350691bc56edSDimitry Andric         Result = Builder.CreateAdd(Result, V, "sunkaddr");
350791bc56edSDimitry Andric       else
350891bc56edSDimitry Andric         Result = V;
350991bc56edSDimitry Andric     }
351091bc56edSDimitry Andric 
351191bc56edSDimitry Andric     if (!Result)
351291bc56edSDimitry Andric       SunkAddr = Constant::getNullValue(Addr->getType());
351391bc56edSDimitry Andric     else
351491bc56edSDimitry Andric       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
351591bc56edSDimitry Andric   }
351691bc56edSDimitry Andric 
351791bc56edSDimitry Andric   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
351891bc56edSDimitry Andric 
351991bc56edSDimitry Andric   // If we have no uses, recursively delete the value and all dead instructions
352091bc56edSDimitry Andric   // using it.
352191bc56edSDimitry Andric   if (Repl->use_empty()) {
352291bc56edSDimitry Andric     // This can cause recursive deletion, which can invalidate our iterator.
352391bc56edSDimitry Andric     // Use a WeakVH to hold onto it in case this happens.
352491bc56edSDimitry Andric     WeakVH IterHandle(CurInstIterator);
352591bc56edSDimitry Andric     BasicBlock *BB = CurInstIterator->getParent();
352691bc56edSDimitry Andric 
352791bc56edSDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
352891bc56edSDimitry Andric 
352991bc56edSDimitry Andric     if (IterHandle != CurInstIterator) {
353091bc56edSDimitry Andric       // If the iterator instruction was recursively deleted, start over at the
353191bc56edSDimitry Andric       // start of the block.
353291bc56edSDimitry Andric       CurInstIterator = BB->begin();
353391bc56edSDimitry Andric       SunkAddrs.clear();
353491bc56edSDimitry Andric     }
353591bc56edSDimitry Andric   }
353691bc56edSDimitry Andric   ++NumMemoryInsts;
353791bc56edSDimitry Andric   return true;
353891bc56edSDimitry Andric }
353991bc56edSDimitry Andric 
354091bc56edSDimitry Andric /// OptimizeInlineAsmInst - If there are any memory operands, use
354191bc56edSDimitry Andric /// OptimizeMemoryInst to sink their address computing into the block when
354291bc56edSDimitry Andric /// possible / profitable.
354391bc56edSDimitry Andric bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
354491bc56edSDimitry Andric   bool MadeChange = false;
354591bc56edSDimitry Andric 
3546ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI =
3547ff0cc061SDimitry Andric       TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
354891bc56edSDimitry Andric   TargetLowering::AsmOperandInfoVector
3549ff0cc061SDimitry Andric     TargetConstraints = TLI->ParseConstraints(TRI, CS);
355091bc56edSDimitry Andric   unsigned ArgNo = 0;
355191bc56edSDimitry Andric   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
355291bc56edSDimitry Andric     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
355391bc56edSDimitry Andric 
355491bc56edSDimitry Andric     // Compute the constraint code and ConstraintType to use.
355591bc56edSDimitry Andric     TLI->ComputeConstraintToUse(OpInfo, SDValue());
355691bc56edSDimitry Andric 
355791bc56edSDimitry Andric     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
355891bc56edSDimitry Andric         OpInfo.isIndirect) {
355991bc56edSDimitry Andric       Value *OpVal = CS->getArgOperand(ArgNo++);
356097bc6c73SDimitry Andric       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
356191bc56edSDimitry Andric     } else if (OpInfo.Type == InlineAsm::isInput)
356291bc56edSDimitry Andric       ArgNo++;
356391bc56edSDimitry Andric   }
356491bc56edSDimitry Andric 
356591bc56edSDimitry Andric   return MadeChange;
356691bc56edSDimitry Andric }
356791bc56edSDimitry Andric 
356839d628a0SDimitry Andric /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
356939d628a0SDimitry Andric /// sign extensions.
357039d628a0SDimitry Andric static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
357139d628a0SDimitry Andric   assert(!Inst->use_empty() && "Input must have at least one use");
357239d628a0SDimitry Andric   const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
357339d628a0SDimitry Andric   bool IsSExt = isa<SExtInst>(FirstUser);
357439d628a0SDimitry Andric   Type *ExtTy = FirstUser->getType();
357539d628a0SDimitry Andric   for (const User *U : Inst->users()) {
357639d628a0SDimitry Andric     const Instruction *UI = cast<Instruction>(U);
357739d628a0SDimitry Andric     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
357839d628a0SDimitry Andric       return false;
357939d628a0SDimitry Andric     Type *CurTy = UI->getType();
358039d628a0SDimitry Andric     // Same input and output types: Same instruction after CSE.
358139d628a0SDimitry Andric     if (CurTy == ExtTy)
358239d628a0SDimitry Andric       continue;
358339d628a0SDimitry Andric 
358439d628a0SDimitry Andric     // If IsSExt is true, we are in this situation:
358539d628a0SDimitry Andric     // a = Inst
358639d628a0SDimitry Andric     // b = sext ty1 a to ty2
358739d628a0SDimitry Andric     // c = sext ty1 a to ty3
358839d628a0SDimitry Andric     // Assuming ty2 is shorter than ty3, this could be turned into:
358939d628a0SDimitry Andric     // a = Inst
359039d628a0SDimitry Andric     // b = sext ty1 a to ty2
359139d628a0SDimitry Andric     // c = sext ty2 b to ty3
359239d628a0SDimitry Andric     // However, the last sext is not free.
359339d628a0SDimitry Andric     if (IsSExt)
359439d628a0SDimitry Andric       return false;
359539d628a0SDimitry Andric 
359639d628a0SDimitry Andric     // This is a ZExt, maybe this is free to extend from one type to another.
359739d628a0SDimitry Andric     // In that case, we would not account for a different use.
359839d628a0SDimitry Andric     Type *NarrowTy;
359939d628a0SDimitry Andric     Type *LargeTy;
360039d628a0SDimitry Andric     if (ExtTy->getScalarType()->getIntegerBitWidth() >
360139d628a0SDimitry Andric         CurTy->getScalarType()->getIntegerBitWidth()) {
360239d628a0SDimitry Andric       NarrowTy = CurTy;
360339d628a0SDimitry Andric       LargeTy = ExtTy;
360439d628a0SDimitry Andric     } else {
360539d628a0SDimitry Andric       NarrowTy = ExtTy;
360639d628a0SDimitry Andric       LargeTy = CurTy;
360739d628a0SDimitry Andric     }
360839d628a0SDimitry Andric 
360939d628a0SDimitry Andric     if (!TLI.isZExtFree(NarrowTy, LargeTy))
361039d628a0SDimitry Andric       return false;
361139d628a0SDimitry Andric   }
361239d628a0SDimitry Andric   // All uses are the same or can be derived from one another for free.
361339d628a0SDimitry Andric   return true;
361439d628a0SDimitry Andric }
361539d628a0SDimitry Andric 
361639d628a0SDimitry Andric /// \brief Try to form ExtLd by promoting \p Exts until they reach a
361739d628a0SDimitry Andric /// load instruction.
361839d628a0SDimitry Andric /// If an ext(load) can be formed, it is returned via \p LI for the load
361939d628a0SDimitry Andric /// and \p Inst for the extension.
362039d628a0SDimitry Andric /// Otherwise LI == nullptr and Inst == nullptr.
362139d628a0SDimitry Andric /// When some promotion happened, \p TPT contains the proper state to
362239d628a0SDimitry Andric /// revert them.
362339d628a0SDimitry Andric ///
362439d628a0SDimitry Andric /// \return true when promoting was necessary to expose the ext(load)
362539d628a0SDimitry Andric /// opportunity, false otherwise.
362639d628a0SDimitry Andric ///
362739d628a0SDimitry Andric /// Example:
362839d628a0SDimitry Andric /// \code
362939d628a0SDimitry Andric /// %ld = load i32* %addr
363039d628a0SDimitry Andric /// %add = add nuw i32 %ld, 4
363139d628a0SDimitry Andric /// %zext = zext i32 %add to i64
363239d628a0SDimitry Andric /// \endcode
363339d628a0SDimitry Andric /// =>
363439d628a0SDimitry Andric /// \code
363539d628a0SDimitry Andric /// %ld = load i32* %addr
363639d628a0SDimitry Andric /// %zext = zext i32 %ld to i64
363739d628a0SDimitry Andric /// %add = add nuw i64 %zext, 4
363839d628a0SDimitry Andric /// \encode
363939d628a0SDimitry Andric /// Thanks to the promotion, we can match zext(load i32*) to i64.
364039d628a0SDimitry Andric bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
364139d628a0SDimitry Andric                                     LoadInst *&LI, Instruction *&Inst,
364239d628a0SDimitry Andric                                     const SmallVectorImpl<Instruction *> &Exts,
3643ff0cc061SDimitry Andric                                     unsigned CreatedInstsCost = 0) {
364439d628a0SDimitry Andric   // Iterate over all the extensions to see if one form an ext(load).
364539d628a0SDimitry Andric   for (auto I : Exts) {
364639d628a0SDimitry Andric     // Check if we directly have ext(load).
364739d628a0SDimitry Andric     if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
364839d628a0SDimitry Andric       Inst = I;
364939d628a0SDimitry Andric       // No promotion happened here.
365039d628a0SDimitry Andric       return false;
365139d628a0SDimitry Andric     }
365239d628a0SDimitry Andric     // Check whether or not we want to do any promotion.
365339d628a0SDimitry Andric     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
365439d628a0SDimitry Andric       continue;
365539d628a0SDimitry Andric     // Get the action to perform the promotion.
365639d628a0SDimitry Andric     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
36578f0fd8f6SDimitry Andric         I, InsertedInsts, *TLI, PromotedInsts);
365839d628a0SDimitry Andric     // Check if we can promote.
365939d628a0SDimitry Andric     if (!TPH)
366039d628a0SDimitry Andric       continue;
366139d628a0SDimitry Andric     // Save the current state.
366239d628a0SDimitry Andric     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
366339d628a0SDimitry Andric         TPT.getRestorationPoint();
366439d628a0SDimitry Andric     SmallVector<Instruction *, 4> NewExts;
3665ff0cc061SDimitry Andric     unsigned NewCreatedInstsCost = 0;
3666ff0cc061SDimitry Andric     unsigned ExtCost = !TLI->isExtFree(I);
366739d628a0SDimitry Andric     // Promote.
3668ff0cc061SDimitry Andric     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3669ff0cc061SDimitry Andric                              &NewExts, nullptr, *TLI);
367039d628a0SDimitry Andric     assert(PromotedVal &&
367139d628a0SDimitry Andric            "TypePromotionHelper should have filtered out those cases");
367239d628a0SDimitry Andric 
367339d628a0SDimitry Andric     // We would be able to merge only one extension in a load.
367439d628a0SDimitry Andric     // Therefore, if we have more than 1 new extension we heuristically
367539d628a0SDimitry Andric     // cut this search path, because it means we degrade the code quality.
367639d628a0SDimitry Andric     // With exactly 2, the transformation is neutral, because we will merge
367739d628a0SDimitry Andric     // one extension but leave one. However, we optimistically keep going,
367839d628a0SDimitry Andric     // because the new extension may be removed too.
3679ff0cc061SDimitry Andric     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3680ff0cc061SDimitry Andric     TotalCreatedInstsCost -= ExtCost;
368139d628a0SDimitry Andric     if (!StressExtLdPromotion &&
3682ff0cc061SDimitry Andric         (TotalCreatedInstsCost > 1 ||
368339d628a0SDimitry Andric          !isPromotedInstructionLegal(*TLI, PromotedVal))) {
368439d628a0SDimitry Andric       // The promotion is not profitable, rollback to the previous state.
368539d628a0SDimitry Andric       TPT.rollback(LastKnownGood);
368639d628a0SDimitry Andric       continue;
368739d628a0SDimitry Andric     }
368839d628a0SDimitry Andric     // The promotion is profitable.
368939d628a0SDimitry Andric     // Check if it exposes an ext(load).
3690ff0cc061SDimitry Andric     (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
3691ff0cc061SDimitry Andric     if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
369239d628a0SDimitry Andric                // If we have created a new extension, i.e., now we have two
369339d628a0SDimitry Andric                // extensions. We must make sure one of them is merged with
369439d628a0SDimitry Andric                // the load, otherwise we may degrade the code quality.
369539d628a0SDimitry Andric                (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
369639d628a0SDimitry Andric       // Promotion happened.
369739d628a0SDimitry Andric       return true;
369839d628a0SDimitry Andric     // If this does not help to expose an ext(load) then, rollback.
369939d628a0SDimitry Andric     TPT.rollback(LastKnownGood);
370039d628a0SDimitry Andric   }
370139d628a0SDimitry Andric   // None of the extension can form an ext(load).
370239d628a0SDimitry Andric   LI = nullptr;
370339d628a0SDimitry Andric   Inst = nullptr;
370439d628a0SDimitry Andric   return false;
370539d628a0SDimitry Andric }
370639d628a0SDimitry Andric 
370791bc56edSDimitry Andric /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
370891bc56edSDimitry Andric /// basic block as the load, unless conditions are unfavorable. This allows
370991bc56edSDimitry Andric /// SelectionDAG to fold the extend into the load.
371039d628a0SDimitry Andric /// \p I[in/out] the extension may be modified during the process if some
371139d628a0SDimitry Andric /// promotions apply.
371291bc56edSDimitry Andric ///
371339d628a0SDimitry Andric bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
371439d628a0SDimitry Andric   // Try to promote a chain of computation if it allows to form
371539d628a0SDimitry Andric   // an extended load.
371639d628a0SDimitry Andric   TypePromotionTransaction TPT;
371739d628a0SDimitry Andric   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
371839d628a0SDimitry Andric     TPT.getRestorationPoint();
371939d628a0SDimitry Andric   SmallVector<Instruction *, 1> Exts;
372039d628a0SDimitry Andric   Exts.push_back(I);
372191bc56edSDimitry Andric   // Look for a load being extended.
372239d628a0SDimitry Andric   LoadInst *LI = nullptr;
372339d628a0SDimitry Andric   Instruction *OldExt = I;
372439d628a0SDimitry Andric   bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
372539d628a0SDimitry Andric   if (!LI || !I) {
372639d628a0SDimitry Andric     assert(!HasPromoted && !LI && "If we did not match any load instruction "
372739d628a0SDimitry Andric                                   "the code must remain the same");
372839d628a0SDimitry Andric     I = OldExt;
372939d628a0SDimitry Andric     return false;
373039d628a0SDimitry Andric   }
373191bc56edSDimitry Andric 
373291bc56edSDimitry Andric   // If they're already in the same block, there's nothing to do.
373339d628a0SDimitry Andric   // Make the cheap checks first if we did not promote.
373439d628a0SDimitry Andric   // If we promoted, we need to check if it is indeed profitable.
373539d628a0SDimitry Andric   if (!HasPromoted && LI->getParent() == I->getParent())
373691bc56edSDimitry Andric     return false;
373791bc56edSDimitry Andric 
373839d628a0SDimitry Andric   EVT VT = TLI->getValueType(I->getType());
373939d628a0SDimitry Andric   EVT LoadVT = TLI->getValueType(LI->getType());
374039d628a0SDimitry Andric 
374191bc56edSDimitry Andric   // If the load has other users and the truncate is not free, this probably
374291bc56edSDimitry Andric   // isn't worthwhile.
374339d628a0SDimitry Andric   if (!LI->hasOneUse() && TLI &&
374439d628a0SDimitry Andric       (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
374539d628a0SDimitry Andric       !TLI->isTruncateFree(I->getType(), LI->getType())) {
374639d628a0SDimitry Andric     I = OldExt;
374739d628a0SDimitry Andric     TPT.rollback(LastKnownGood);
374891bc56edSDimitry Andric     return false;
374939d628a0SDimitry Andric   }
375091bc56edSDimitry Andric 
375191bc56edSDimitry Andric   // Check whether the target supports casts folded into loads.
375291bc56edSDimitry Andric   unsigned LType;
375391bc56edSDimitry Andric   if (isa<ZExtInst>(I))
375491bc56edSDimitry Andric     LType = ISD::ZEXTLOAD;
375591bc56edSDimitry Andric   else {
375691bc56edSDimitry Andric     assert(isa<SExtInst>(I) && "Unexpected ext type!");
375791bc56edSDimitry Andric     LType = ISD::SEXTLOAD;
375891bc56edSDimitry Andric   }
375939d628a0SDimitry Andric   if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
376039d628a0SDimitry Andric     I = OldExt;
376139d628a0SDimitry Andric     TPT.rollback(LastKnownGood);
376291bc56edSDimitry Andric     return false;
376339d628a0SDimitry Andric   }
376491bc56edSDimitry Andric 
376591bc56edSDimitry Andric   // Move the extend into the same block as the load, so that SelectionDAG
376691bc56edSDimitry Andric   // can fold it.
376739d628a0SDimitry Andric   TPT.commit();
376891bc56edSDimitry Andric   I->removeFromParent();
376991bc56edSDimitry Andric   I->insertAfter(LI);
377091bc56edSDimitry Andric   ++NumExtsMoved;
377191bc56edSDimitry Andric   return true;
377291bc56edSDimitry Andric }
377391bc56edSDimitry Andric 
377491bc56edSDimitry Andric bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
377591bc56edSDimitry Andric   BasicBlock *DefBB = I->getParent();
377691bc56edSDimitry Andric 
377791bc56edSDimitry Andric   // If the result of a {s|z}ext and its source are both live out, rewrite all
377891bc56edSDimitry Andric   // other uses of the source with result of extension.
377991bc56edSDimitry Andric   Value *Src = I->getOperand(0);
378091bc56edSDimitry Andric   if (Src->hasOneUse())
378191bc56edSDimitry Andric     return false;
378291bc56edSDimitry Andric 
378391bc56edSDimitry Andric   // Only do this xform if truncating is free.
378491bc56edSDimitry Andric   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
378591bc56edSDimitry Andric     return false;
378691bc56edSDimitry Andric 
378791bc56edSDimitry Andric   // Only safe to perform the optimization if the source is also defined in
378891bc56edSDimitry Andric   // this block.
378991bc56edSDimitry Andric   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
379091bc56edSDimitry Andric     return false;
379191bc56edSDimitry Andric 
379291bc56edSDimitry Andric   bool DefIsLiveOut = false;
379391bc56edSDimitry Andric   for (User *U : I->users()) {
379491bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
379591bc56edSDimitry Andric 
379691bc56edSDimitry Andric     // Figure out which BB this ext is used in.
379791bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
379891bc56edSDimitry Andric     if (UserBB == DefBB) continue;
379991bc56edSDimitry Andric     DefIsLiveOut = true;
380091bc56edSDimitry Andric     break;
380191bc56edSDimitry Andric   }
380291bc56edSDimitry Andric   if (!DefIsLiveOut)
380391bc56edSDimitry Andric     return false;
380491bc56edSDimitry Andric 
380591bc56edSDimitry Andric   // Make sure none of the uses are PHI nodes.
380691bc56edSDimitry Andric   for (User *U : Src->users()) {
380791bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
380891bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
380991bc56edSDimitry Andric     if (UserBB == DefBB) continue;
381091bc56edSDimitry Andric     // Be conservative. We don't want this xform to end up introducing
381191bc56edSDimitry Andric     // reloads just before load / store instructions.
381291bc56edSDimitry Andric     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
381391bc56edSDimitry Andric       return false;
381491bc56edSDimitry Andric   }
381591bc56edSDimitry Andric 
381691bc56edSDimitry Andric   // InsertedTruncs - Only insert one trunc in each block once.
381791bc56edSDimitry Andric   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
381891bc56edSDimitry Andric 
381991bc56edSDimitry Andric   bool MadeChange = false;
382091bc56edSDimitry Andric   for (Use &U : Src->uses()) {
382191bc56edSDimitry Andric     Instruction *User = cast<Instruction>(U.getUser());
382291bc56edSDimitry Andric 
382391bc56edSDimitry Andric     // Figure out which BB this ext is used in.
382491bc56edSDimitry Andric     BasicBlock *UserBB = User->getParent();
382591bc56edSDimitry Andric     if (UserBB == DefBB) continue;
382691bc56edSDimitry Andric 
382791bc56edSDimitry Andric     // Both src and def are live in this block. Rewrite the use.
382891bc56edSDimitry Andric     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
382991bc56edSDimitry Andric 
383091bc56edSDimitry Andric     if (!InsertedTrunc) {
383191bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
383291bc56edSDimitry Andric       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
38338f0fd8f6SDimitry Andric       InsertedInsts.insert(InsertedTrunc);
383491bc56edSDimitry Andric     }
383591bc56edSDimitry Andric 
383691bc56edSDimitry Andric     // Replace a use of the {s|z}ext source with a use of the result.
383791bc56edSDimitry Andric     U = InsertedTrunc;
383891bc56edSDimitry Andric     ++NumExtUses;
383991bc56edSDimitry Andric     MadeChange = true;
384091bc56edSDimitry Andric   }
384191bc56edSDimitry Andric 
384291bc56edSDimitry Andric   return MadeChange;
384391bc56edSDimitry Andric }
384491bc56edSDimitry Andric 
384591bc56edSDimitry Andric /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
384691bc56edSDimitry Andric /// turned into an explicit branch.
384791bc56edSDimitry Andric static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
384891bc56edSDimitry Andric   // FIXME: This should use the same heuristics as IfConversion to determine
384991bc56edSDimitry Andric   // whether a select is better represented as a branch.  This requires that
385091bc56edSDimitry Andric   // branch probability metadata is preserved for the select, which is not the
385191bc56edSDimitry Andric   // case currently.
385291bc56edSDimitry Andric 
385391bc56edSDimitry Andric   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
385491bc56edSDimitry Andric 
385591bc56edSDimitry Andric   // If the branch is predicted right, an out of order CPU can avoid blocking on
385691bc56edSDimitry Andric   // the compare.  Emit cmovs on compares with a memory operand as branches to
385791bc56edSDimitry Andric   // avoid stalls on the load from memory.  If the compare has more than one use
385891bc56edSDimitry Andric   // there's probably another cmov or setcc around so it's not worth emitting a
385991bc56edSDimitry Andric   // branch.
386091bc56edSDimitry Andric   if (!Cmp)
386191bc56edSDimitry Andric     return false;
386291bc56edSDimitry Andric 
386391bc56edSDimitry Andric   Value *CmpOp0 = Cmp->getOperand(0);
386491bc56edSDimitry Andric   Value *CmpOp1 = Cmp->getOperand(1);
386591bc56edSDimitry Andric 
386691bc56edSDimitry Andric   // We check that the memory operand has one use to avoid uses of the loaded
386791bc56edSDimitry Andric   // value directly after the compare, making branches unprofitable.
386891bc56edSDimitry Andric   return Cmp->hasOneUse() &&
386991bc56edSDimitry Andric          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
387091bc56edSDimitry Andric           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
387191bc56edSDimitry Andric }
387291bc56edSDimitry Andric 
387391bc56edSDimitry Andric 
387491bc56edSDimitry Andric /// If we have a SelectInst that will likely profit from branch prediction,
387591bc56edSDimitry Andric /// turn it into a branch.
387691bc56edSDimitry Andric bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
387791bc56edSDimitry Andric   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
387891bc56edSDimitry Andric 
387991bc56edSDimitry Andric   // Can we convert the 'select' to CF ?
388091bc56edSDimitry Andric   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
388191bc56edSDimitry Andric     return false;
388291bc56edSDimitry Andric 
388391bc56edSDimitry Andric   TargetLowering::SelectSupportKind SelectKind;
388491bc56edSDimitry Andric   if (VectorCond)
388591bc56edSDimitry Andric     SelectKind = TargetLowering::VectorMaskSelect;
388691bc56edSDimitry Andric   else if (SI->getType()->isVectorTy())
388791bc56edSDimitry Andric     SelectKind = TargetLowering::ScalarCondVectorVal;
388891bc56edSDimitry Andric   else
388991bc56edSDimitry Andric     SelectKind = TargetLowering::ScalarValSelect;
389091bc56edSDimitry Andric 
389191bc56edSDimitry Andric   // Do we have efficient codegen support for this kind of 'selects' ?
389291bc56edSDimitry Andric   if (TLI->isSelectSupported(SelectKind)) {
389391bc56edSDimitry Andric     // We have efficient codegen support for the select instruction.
389491bc56edSDimitry Andric     // Check if it is profitable to keep this 'select'.
389591bc56edSDimitry Andric     if (!TLI->isPredictableSelectExpensive() ||
389691bc56edSDimitry Andric         !isFormingBranchFromSelectProfitable(SI))
389791bc56edSDimitry Andric       return false;
389891bc56edSDimitry Andric   }
389991bc56edSDimitry Andric 
390091bc56edSDimitry Andric   ModifiedDT = true;
390191bc56edSDimitry Andric 
390291bc56edSDimitry Andric   // First, we split the block containing the select into 2 blocks.
390391bc56edSDimitry Andric   BasicBlock *StartBlock = SI->getParent();
390491bc56edSDimitry Andric   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
390591bc56edSDimitry Andric   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
390691bc56edSDimitry Andric 
390791bc56edSDimitry Andric   // Create a new block serving as the landing pad for the branch.
390891bc56edSDimitry Andric   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
390991bc56edSDimitry Andric                                              NextBlock->getParent(), NextBlock);
391091bc56edSDimitry Andric 
391191bc56edSDimitry Andric   // Move the unconditional branch from the block with the select in it into our
391291bc56edSDimitry Andric   // landing pad block.
391391bc56edSDimitry Andric   StartBlock->getTerminator()->eraseFromParent();
391491bc56edSDimitry Andric   BranchInst::Create(NextBlock, SmallBlock);
391591bc56edSDimitry Andric 
391691bc56edSDimitry Andric   // Insert the real conditional branch based on the original condition.
391791bc56edSDimitry Andric   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
391891bc56edSDimitry Andric 
391991bc56edSDimitry Andric   // The select itself is replaced with a PHI Node.
392091bc56edSDimitry Andric   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
392191bc56edSDimitry Andric   PN->takeName(SI);
392291bc56edSDimitry Andric   PN->addIncoming(SI->getTrueValue(), StartBlock);
392391bc56edSDimitry Andric   PN->addIncoming(SI->getFalseValue(), SmallBlock);
392491bc56edSDimitry Andric   SI->replaceAllUsesWith(PN);
392591bc56edSDimitry Andric   SI->eraseFromParent();
392691bc56edSDimitry Andric 
392791bc56edSDimitry Andric   // Instruct OptimizeBlock to skip to the next block.
392891bc56edSDimitry Andric   CurInstIterator = StartBlock->end();
392991bc56edSDimitry Andric   ++NumSelectsExpanded;
393091bc56edSDimitry Andric   return true;
393191bc56edSDimitry Andric }
393291bc56edSDimitry Andric 
393391bc56edSDimitry Andric static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
393491bc56edSDimitry Andric   SmallVector<int, 16> Mask(SVI->getShuffleMask());
393591bc56edSDimitry Andric   int SplatElem = -1;
393691bc56edSDimitry Andric   for (unsigned i = 0; i < Mask.size(); ++i) {
393791bc56edSDimitry Andric     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
393891bc56edSDimitry Andric       return false;
393991bc56edSDimitry Andric     SplatElem = Mask[i];
394091bc56edSDimitry Andric   }
394191bc56edSDimitry Andric 
394291bc56edSDimitry Andric   return true;
394391bc56edSDimitry Andric }
394491bc56edSDimitry Andric 
394591bc56edSDimitry Andric /// Some targets have expensive vector shifts if the lanes aren't all the same
394691bc56edSDimitry Andric /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
394791bc56edSDimitry Andric /// it's often worth sinking a shufflevector splat down to its use so that
394891bc56edSDimitry Andric /// codegen can spot all lanes are identical.
394991bc56edSDimitry Andric bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
395091bc56edSDimitry Andric   BasicBlock *DefBB = SVI->getParent();
395191bc56edSDimitry Andric 
395291bc56edSDimitry Andric   // Only do this xform if variable vector shifts are particularly expensive.
395391bc56edSDimitry Andric   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
395491bc56edSDimitry Andric     return false;
395591bc56edSDimitry Andric 
395691bc56edSDimitry Andric   // We only expect better codegen by sinking a shuffle if we can recognise a
395791bc56edSDimitry Andric   // constant splat.
395891bc56edSDimitry Andric   if (!isBroadcastShuffle(SVI))
395991bc56edSDimitry Andric     return false;
396091bc56edSDimitry Andric 
396191bc56edSDimitry Andric   // InsertedShuffles - Only insert a shuffle in each block once.
396291bc56edSDimitry Andric   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
396391bc56edSDimitry Andric 
396491bc56edSDimitry Andric   bool MadeChange = false;
396591bc56edSDimitry Andric   for (User *U : SVI->users()) {
396691bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
396791bc56edSDimitry Andric 
396891bc56edSDimitry Andric     // Figure out which BB this ext is used in.
396991bc56edSDimitry Andric     BasicBlock *UserBB = UI->getParent();
397091bc56edSDimitry Andric     if (UserBB == DefBB) continue;
397191bc56edSDimitry Andric 
397291bc56edSDimitry Andric     // For now only apply this when the splat is used by a shift instruction.
397391bc56edSDimitry Andric     if (!UI->isShift()) continue;
397491bc56edSDimitry Andric 
397591bc56edSDimitry Andric     // Everything checks out, sink the shuffle if the user's block doesn't
397691bc56edSDimitry Andric     // already have a copy.
397791bc56edSDimitry Andric     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
397891bc56edSDimitry Andric 
397991bc56edSDimitry Andric     if (!InsertedShuffle) {
398091bc56edSDimitry Andric       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
398191bc56edSDimitry Andric       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
398291bc56edSDimitry Andric                                               SVI->getOperand(1),
398391bc56edSDimitry Andric                                               SVI->getOperand(2), "", InsertPt);
398491bc56edSDimitry Andric     }
398591bc56edSDimitry Andric 
398691bc56edSDimitry Andric     UI->replaceUsesOfWith(SVI, InsertedShuffle);
398791bc56edSDimitry Andric     MadeChange = true;
398891bc56edSDimitry Andric   }
398991bc56edSDimitry Andric 
399091bc56edSDimitry Andric   // If we removed all uses, nuke the shuffle.
399191bc56edSDimitry Andric   if (SVI->use_empty()) {
399291bc56edSDimitry Andric     SVI->eraseFromParent();
399391bc56edSDimitry Andric     MadeChange = true;
399491bc56edSDimitry Andric   }
399591bc56edSDimitry Andric 
399691bc56edSDimitry Andric   return MadeChange;
399791bc56edSDimitry Andric }
399891bc56edSDimitry Andric 
399939d628a0SDimitry Andric namespace {
400039d628a0SDimitry Andric /// \brief Helper class to promote a scalar operation to a vector one.
400139d628a0SDimitry Andric /// This class is used to move downward extractelement transition.
400239d628a0SDimitry Andric /// E.g.,
400339d628a0SDimitry Andric /// a = vector_op <2 x i32>
400439d628a0SDimitry Andric /// b = extractelement <2 x i32> a, i32 0
400539d628a0SDimitry Andric /// c = scalar_op b
400639d628a0SDimitry Andric /// store c
400739d628a0SDimitry Andric ///
400839d628a0SDimitry Andric /// =>
400939d628a0SDimitry Andric /// a = vector_op <2 x i32>
401039d628a0SDimitry Andric /// c = vector_op a (equivalent to scalar_op on the related lane)
401139d628a0SDimitry Andric /// * d = extractelement <2 x i32> c, i32 0
401239d628a0SDimitry Andric /// * store d
401339d628a0SDimitry Andric /// Assuming both extractelement and store can be combine, we get rid of the
401439d628a0SDimitry Andric /// transition.
401539d628a0SDimitry Andric class VectorPromoteHelper {
401639d628a0SDimitry Andric   /// Used to perform some checks on the legality of vector operations.
401739d628a0SDimitry Andric   const TargetLowering &TLI;
401839d628a0SDimitry Andric 
401939d628a0SDimitry Andric   /// Used to estimated the cost of the promoted chain.
402039d628a0SDimitry Andric   const TargetTransformInfo &TTI;
402139d628a0SDimitry Andric 
402239d628a0SDimitry Andric   /// The transition being moved downwards.
402339d628a0SDimitry Andric   Instruction *Transition;
402439d628a0SDimitry Andric   /// The sequence of instructions to be promoted.
402539d628a0SDimitry Andric   SmallVector<Instruction *, 4> InstsToBePromoted;
402639d628a0SDimitry Andric   /// Cost of combining a store and an extract.
402739d628a0SDimitry Andric   unsigned StoreExtractCombineCost;
402839d628a0SDimitry Andric   /// Instruction that will be combined with the transition.
402939d628a0SDimitry Andric   Instruction *CombineInst;
403039d628a0SDimitry Andric 
403139d628a0SDimitry Andric   /// \brief The instruction that represents the current end of the transition.
403239d628a0SDimitry Andric   /// Since we are faking the promotion until we reach the end of the chain
403339d628a0SDimitry Andric   /// of computation, we need a way to get the current end of the transition.
403439d628a0SDimitry Andric   Instruction *getEndOfTransition() const {
403539d628a0SDimitry Andric     if (InstsToBePromoted.empty())
403639d628a0SDimitry Andric       return Transition;
403739d628a0SDimitry Andric     return InstsToBePromoted.back();
403839d628a0SDimitry Andric   }
403939d628a0SDimitry Andric 
404039d628a0SDimitry Andric   /// \brief Return the index of the original value in the transition.
404139d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
404239d628a0SDimitry Andric   /// c, is at index 0.
404339d628a0SDimitry Andric   unsigned getTransitionOriginalValueIdx() const {
404439d628a0SDimitry Andric     assert(isa<ExtractElementInst>(Transition) &&
404539d628a0SDimitry Andric            "Other kind of transitions are not supported yet");
404639d628a0SDimitry Andric     return 0;
404739d628a0SDimitry Andric   }
404839d628a0SDimitry Andric 
404939d628a0SDimitry Andric   /// \brief Return the index of the index in the transition.
405039d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
405139d628a0SDimitry Andric   /// is at index 1.
405239d628a0SDimitry Andric   unsigned getTransitionIdx() const {
405339d628a0SDimitry Andric     assert(isa<ExtractElementInst>(Transition) &&
405439d628a0SDimitry Andric            "Other kind of transitions are not supported yet");
405539d628a0SDimitry Andric     return 1;
405639d628a0SDimitry Andric   }
405739d628a0SDimitry Andric 
405839d628a0SDimitry Andric   /// \brief Get the type of the transition.
405939d628a0SDimitry Andric   /// This is the type of the original value.
406039d628a0SDimitry Andric   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
406139d628a0SDimitry Andric   /// transition is <2 x i32>.
406239d628a0SDimitry Andric   Type *getTransitionType() const {
406339d628a0SDimitry Andric     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
406439d628a0SDimitry Andric   }
406539d628a0SDimitry Andric 
406639d628a0SDimitry Andric   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
406739d628a0SDimitry Andric   /// I.e., we have the following sequence:
406839d628a0SDimitry Andric   /// Def = Transition <ty1> a to <ty2>
406939d628a0SDimitry Andric   /// b = ToBePromoted <ty2> Def, ...
407039d628a0SDimitry Andric   /// =>
407139d628a0SDimitry Andric   /// b = ToBePromoted <ty1> a, ...
407239d628a0SDimitry Andric   /// Def = Transition <ty1> ToBePromoted to <ty2>
407339d628a0SDimitry Andric   void promoteImpl(Instruction *ToBePromoted);
407439d628a0SDimitry Andric 
407539d628a0SDimitry Andric   /// \brief Check whether or not it is profitable to promote all the
407639d628a0SDimitry Andric   /// instructions enqueued to be promoted.
407739d628a0SDimitry Andric   bool isProfitableToPromote() {
407839d628a0SDimitry Andric     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
407939d628a0SDimitry Andric     unsigned Index = isa<ConstantInt>(ValIdx)
408039d628a0SDimitry Andric                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
408139d628a0SDimitry Andric                          : -1;
408239d628a0SDimitry Andric     Type *PromotedType = getTransitionType();
408339d628a0SDimitry Andric 
408439d628a0SDimitry Andric     StoreInst *ST = cast<StoreInst>(CombineInst);
408539d628a0SDimitry Andric     unsigned AS = ST->getPointerAddressSpace();
408639d628a0SDimitry Andric     unsigned Align = ST->getAlignment();
408739d628a0SDimitry Andric     // Check if this store is supported.
408839d628a0SDimitry Andric     if (!TLI.allowsMisalignedMemoryAccesses(
408939d628a0SDimitry Andric             TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
409039d628a0SDimitry Andric       // If this is not supported, there is no way we can combine
409139d628a0SDimitry Andric       // the extract with the store.
409239d628a0SDimitry Andric       return false;
409339d628a0SDimitry Andric     }
409439d628a0SDimitry Andric 
409539d628a0SDimitry Andric     // The scalar chain of computation has to pay for the transition
409639d628a0SDimitry Andric     // scalar to vector.
409739d628a0SDimitry Andric     // The vector chain has to account for the combining cost.
409839d628a0SDimitry Andric     uint64_t ScalarCost =
409939d628a0SDimitry Andric         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
410039d628a0SDimitry Andric     uint64_t VectorCost = StoreExtractCombineCost;
410139d628a0SDimitry Andric     for (const auto &Inst : InstsToBePromoted) {
410239d628a0SDimitry Andric       // Compute the cost.
410339d628a0SDimitry Andric       // By construction, all instructions being promoted are arithmetic ones.
410439d628a0SDimitry Andric       // Moreover, one argument is a constant that can be viewed as a splat
410539d628a0SDimitry Andric       // constant.
410639d628a0SDimitry Andric       Value *Arg0 = Inst->getOperand(0);
410739d628a0SDimitry Andric       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
410839d628a0SDimitry Andric                             isa<ConstantFP>(Arg0);
410939d628a0SDimitry Andric       TargetTransformInfo::OperandValueKind Arg0OVK =
411039d628a0SDimitry Andric           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
411139d628a0SDimitry Andric                          : TargetTransformInfo::OK_AnyValue;
411239d628a0SDimitry Andric       TargetTransformInfo::OperandValueKind Arg1OVK =
411339d628a0SDimitry Andric           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
411439d628a0SDimitry Andric                           : TargetTransformInfo::OK_AnyValue;
411539d628a0SDimitry Andric       ScalarCost += TTI.getArithmeticInstrCost(
411639d628a0SDimitry Andric           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
411739d628a0SDimitry Andric       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
411839d628a0SDimitry Andric                                                Arg0OVK, Arg1OVK);
411939d628a0SDimitry Andric     }
412039d628a0SDimitry Andric     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
412139d628a0SDimitry Andric                  << ScalarCost << "\nVector: " << VectorCost << '\n');
412239d628a0SDimitry Andric     return ScalarCost > VectorCost;
412339d628a0SDimitry Andric   }
412439d628a0SDimitry Andric 
412539d628a0SDimitry Andric   /// \brief Generate a constant vector with \p Val with the same
412639d628a0SDimitry Andric   /// number of elements as the transition.
412739d628a0SDimitry Andric   /// \p UseSplat defines whether or not \p Val should be replicated
412839d628a0SDimitry Andric   /// accross the whole vector.
412939d628a0SDimitry Andric   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
413039d628a0SDimitry Andric   /// otherwise we generate a vector with as many undef as possible:
413139d628a0SDimitry Andric   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
413239d628a0SDimitry Andric   /// used at the index of the extract.
413339d628a0SDimitry Andric   Value *getConstantVector(Constant *Val, bool UseSplat) const {
413439d628a0SDimitry Andric     unsigned ExtractIdx = UINT_MAX;
413539d628a0SDimitry Andric     if (!UseSplat) {
413639d628a0SDimitry Andric       // If we cannot determine where the constant must be, we have to
413739d628a0SDimitry Andric       // use a splat constant.
413839d628a0SDimitry Andric       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
413939d628a0SDimitry Andric       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
414039d628a0SDimitry Andric         ExtractIdx = CstVal->getSExtValue();
414139d628a0SDimitry Andric       else
414239d628a0SDimitry Andric         UseSplat = true;
414339d628a0SDimitry Andric     }
414439d628a0SDimitry Andric 
414539d628a0SDimitry Andric     unsigned End = getTransitionType()->getVectorNumElements();
414639d628a0SDimitry Andric     if (UseSplat)
414739d628a0SDimitry Andric       return ConstantVector::getSplat(End, Val);
414839d628a0SDimitry Andric 
414939d628a0SDimitry Andric     SmallVector<Constant *, 4> ConstVec;
415039d628a0SDimitry Andric     UndefValue *UndefVal = UndefValue::get(Val->getType());
415139d628a0SDimitry Andric     for (unsigned Idx = 0; Idx != End; ++Idx) {
415239d628a0SDimitry Andric       if (Idx == ExtractIdx)
415339d628a0SDimitry Andric         ConstVec.push_back(Val);
415439d628a0SDimitry Andric       else
415539d628a0SDimitry Andric         ConstVec.push_back(UndefVal);
415639d628a0SDimitry Andric     }
415739d628a0SDimitry Andric     return ConstantVector::get(ConstVec);
415839d628a0SDimitry Andric   }
415939d628a0SDimitry Andric 
416039d628a0SDimitry Andric   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
416139d628a0SDimitry Andric   /// in \p Use can trigger undefined behavior.
416239d628a0SDimitry Andric   static bool canCauseUndefinedBehavior(const Instruction *Use,
416339d628a0SDimitry Andric                                         unsigned OperandIdx) {
416439d628a0SDimitry Andric     // This is not safe to introduce undef when the operand is on
416539d628a0SDimitry Andric     // the right hand side of a division-like instruction.
416639d628a0SDimitry Andric     if (OperandIdx != 1)
416739d628a0SDimitry Andric       return false;
416839d628a0SDimitry Andric     switch (Use->getOpcode()) {
416939d628a0SDimitry Andric     default:
417039d628a0SDimitry Andric       return false;
417139d628a0SDimitry Andric     case Instruction::SDiv:
417239d628a0SDimitry Andric     case Instruction::UDiv:
417339d628a0SDimitry Andric     case Instruction::SRem:
417439d628a0SDimitry Andric     case Instruction::URem:
417539d628a0SDimitry Andric       return true;
417639d628a0SDimitry Andric     case Instruction::FDiv:
417739d628a0SDimitry Andric     case Instruction::FRem:
417839d628a0SDimitry Andric       return !Use->hasNoNaNs();
417939d628a0SDimitry Andric     }
418039d628a0SDimitry Andric     llvm_unreachable(nullptr);
418139d628a0SDimitry Andric   }
418239d628a0SDimitry Andric 
418339d628a0SDimitry Andric public:
418439d628a0SDimitry Andric   VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
418539d628a0SDimitry Andric                       Instruction *Transition, unsigned CombineCost)
418639d628a0SDimitry Andric       : TLI(TLI), TTI(TTI), Transition(Transition),
418739d628a0SDimitry Andric         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
418839d628a0SDimitry Andric     assert(Transition && "Do not know how to promote null");
418939d628a0SDimitry Andric   }
419039d628a0SDimitry Andric 
419139d628a0SDimitry Andric   /// \brief Check if we can promote \p ToBePromoted to \p Type.
419239d628a0SDimitry Andric   bool canPromote(const Instruction *ToBePromoted) const {
419339d628a0SDimitry Andric     // We could support CastInst too.
419439d628a0SDimitry Andric     return isa<BinaryOperator>(ToBePromoted);
419539d628a0SDimitry Andric   }
419639d628a0SDimitry Andric 
419739d628a0SDimitry Andric   /// \brief Check if it is profitable to promote \p ToBePromoted
419839d628a0SDimitry Andric   /// by moving downward the transition through.
419939d628a0SDimitry Andric   bool shouldPromote(const Instruction *ToBePromoted) const {
420039d628a0SDimitry Andric     // Promote only if all the operands can be statically expanded.
420139d628a0SDimitry Andric     // Indeed, we do not want to introduce any new kind of transitions.
420239d628a0SDimitry Andric     for (const Use &U : ToBePromoted->operands()) {
420339d628a0SDimitry Andric       const Value *Val = U.get();
420439d628a0SDimitry Andric       if (Val == getEndOfTransition()) {
420539d628a0SDimitry Andric         // If the use is a division and the transition is on the rhs,
420639d628a0SDimitry Andric         // we cannot promote the operation, otherwise we may create a
420739d628a0SDimitry Andric         // division by zero.
420839d628a0SDimitry Andric         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
420939d628a0SDimitry Andric           return false;
421039d628a0SDimitry Andric         continue;
421139d628a0SDimitry Andric       }
421239d628a0SDimitry Andric       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
421339d628a0SDimitry Andric           !isa<ConstantFP>(Val))
421439d628a0SDimitry Andric         return false;
421539d628a0SDimitry Andric     }
421639d628a0SDimitry Andric     // Check that the resulting operation is legal.
421739d628a0SDimitry Andric     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
421839d628a0SDimitry Andric     if (!ISDOpcode)
421939d628a0SDimitry Andric       return false;
422039d628a0SDimitry Andric     return StressStoreExtract ||
422139d628a0SDimitry Andric            TLI.isOperationLegalOrCustom(
422239d628a0SDimitry Andric                ISDOpcode, TLI.getValueType(getTransitionType(), true));
422339d628a0SDimitry Andric   }
422439d628a0SDimitry Andric 
422539d628a0SDimitry Andric   /// \brief Check whether or not \p Use can be combined
422639d628a0SDimitry Andric   /// with the transition.
422739d628a0SDimitry Andric   /// I.e., is it possible to do Use(Transition) => AnotherUse?
422839d628a0SDimitry Andric   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
422939d628a0SDimitry Andric 
423039d628a0SDimitry Andric   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
423139d628a0SDimitry Andric   void enqueueForPromotion(Instruction *ToBePromoted) {
423239d628a0SDimitry Andric     InstsToBePromoted.push_back(ToBePromoted);
423339d628a0SDimitry Andric   }
423439d628a0SDimitry Andric 
423539d628a0SDimitry Andric   /// \brief Set the instruction that will be combined with the transition.
423639d628a0SDimitry Andric   void recordCombineInstruction(Instruction *ToBeCombined) {
423739d628a0SDimitry Andric     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
423839d628a0SDimitry Andric     CombineInst = ToBeCombined;
423939d628a0SDimitry Andric   }
424039d628a0SDimitry Andric 
424139d628a0SDimitry Andric   /// \brief Promote all the instructions enqueued for promotion if it is
424239d628a0SDimitry Andric   /// is profitable.
424339d628a0SDimitry Andric   /// \return True if the promotion happened, false otherwise.
424439d628a0SDimitry Andric   bool promote() {
424539d628a0SDimitry Andric     // Check if there is something to promote.
424639d628a0SDimitry Andric     // Right now, if we do not have anything to combine with,
424739d628a0SDimitry Andric     // we assume the promotion is not profitable.
424839d628a0SDimitry Andric     if (InstsToBePromoted.empty() || !CombineInst)
424939d628a0SDimitry Andric       return false;
425039d628a0SDimitry Andric 
425139d628a0SDimitry Andric     // Check cost.
425239d628a0SDimitry Andric     if (!StressStoreExtract && !isProfitableToPromote())
425339d628a0SDimitry Andric       return false;
425439d628a0SDimitry Andric 
425539d628a0SDimitry Andric     // Promote.
425639d628a0SDimitry Andric     for (auto &ToBePromoted : InstsToBePromoted)
425739d628a0SDimitry Andric       promoteImpl(ToBePromoted);
425839d628a0SDimitry Andric     InstsToBePromoted.clear();
425939d628a0SDimitry Andric     return true;
426039d628a0SDimitry Andric   }
426139d628a0SDimitry Andric };
426239d628a0SDimitry Andric } // End of anonymous namespace.
426339d628a0SDimitry Andric 
426439d628a0SDimitry Andric void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
426539d628a0SDimitry Andric   // At this point, we know that all the operands of ToBePromoted but Def
426639d628a0SDimitry Andric   // can be statically promoted.
426739d628a0SDimitry Andric   // For Def, we need to use its parameter in ToBePromoted:
426839d628a0SDimitry Andric   // b = ToBePromoted ty1 a
426939d628a0SDimitry Andric   // Def = Transition ty1 b to ty2
427039d628a0SDimitry Andric   // Move the transition down.
427139d628a0SDimitry Andric   // 1. Replace all uses of the promoted operation by the transition.
427239d628a0SDimitry Andric   // = ... b => = ... Def.
427339d628a0SDimitry Andric   assert(ToBePromoted->getType() == Transition->getType() &&
427439d628a0SDimitry Andric          "The type of the result of the transition does not match "
427539d628a0SDimitry Andric          "the final type");
427639d628a0SDimitry Andric   ToBePromoted->replaceAllUsesWith(Transition);
427739d628a0SDimitry Andric   // 2. Update the type of the uses.
427839d628a0SDimitry Andric   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
427939d628a0SDimitry Andric   Type *TransitionTy = getTransitionType();
428039d628a0SDimitry Andric   ToBePromoted->mutateType(TransitionTy);
428139d628a0SDimitry Andric   // 3. Update all the operands of the promoted operation with promoted
428239d628a0SDimitry Andric   // operands.
428339d628a0SDimitry Andric   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
428439d628a0SDimitry Andric   for (Use &U : ToBePromoted->operands()) {
428539d628a0SDimitry Andric     Value *Val = U.get();
428639d628a0SDimitry Andric     Value *NewVal = nullptr;
428739d628a0SDimitry Andric     if (Val == Transition)
428839d628a0SDimitry Andric       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
428939d628a0SDimitry Andric     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
429039d628a0SDimitry Andric              isa<ConstantFP>(Val)) {
429139d628a0SDimitry Andric       // Use a splat constant if it is not safe to use undef.
429239d628a0SDimitry Andric       NewVal = getConstantVector(
429339d628a0SDimitry Andric           cast<Constant>(Val),
429439d628a0SDimitry Andric           isa<UndefValue>(Val) ||
429539d628a0SDimitry Andric               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
429639d628a0SDimitry Andric     } else
429739d628a0SDimitry Andric       llvm_unreachable("Did you modified shouldPromote and forgot to update "
429839d628a0SDimitry Andric                        "this?");
429939d628a0SDimitry Andric     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
430039d628a0SDimitry Andric   }
430139d628a0SDimitry Andric   Transition->removeFromParent();
430239d628a0SDimitry Andric   Transition->insertAfter(ToBePromoted);
430339d628a0SDimitry Andric   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
430439d628a0SDimitry Andric }
430539d628a0SDimitry Andric 
430639d628a0SDimitry Andric /// Some targets can do store(extractelement) with one instruction.
430739d628a0SDimitry Andric /// Try to push the extractelement towards the stores when the target
430839d628a0SDimitry Andric /// has this feature and this is profitable.
430939d628a0SDimitry Andric bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
431039d628a0SDimitry Andric   unsigned CombineCost = UINT_MAX;
431139d628a0SDimitry Andric   if (DisableStoreExtract || !TLI ||
431239d628a0SDimitry Andric       (!StressStoreExtract &&
431339d628a0SDimitry Andric        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
431439d628a0SDimitry Andric                                        Inst->getOperand(1), CombineCost)))
431539d628a0SDimitry Andric     return false;
431639d628a0SDimitry Andric 
431739d628a0SDimitry Andric   // At this point we know that Inst is a vector to scalar transition.
431839d628a0SDimitry Andric   // Try to move it down the def-use chain, until:
431939d628a0SDimitry Andric   // - We can combine the transition with its single use
432039d628a0SDimitry Andric   //   => we got rid of the transition.
432139d628a0SDimitry Andric   // - We escape the current basic block
432239d628a0SDimitry Andric   //   => we would need to check that we are moving it at a cheaper place and
432339d628a0SDimitry Andric   //      we do not do that for now.
432439d628a0SDimitry Andric   BasicBlock *Parent = Inst->getParent();
432539d628a0SDimitry Andric   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
432639d628a0SDimitry Andric   VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
432739d628a0SDimitry Andric   // If the transition has more than one use, assume this is not going to be
432839d628a0SDimitry Andric   // beneficial.
432939d628a0SDimitry Andric   while (Inst->hasOneUse()) {
433039d628a0SDimitry Andric     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
433139d628a0SDimitry Andric     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
433239d628a0SDimitry Andric 
433339d628a0SDimitry Andric     if (ToBePromoted->getParent() != Parent) {
433439d628a0SDimitry Andric       DEBUG(dbgs() << "Instruction to promote is in a different block ("
433539d628a0SDimitry Andric                    << ToBePromoted->getParent()->getName()
433639d628a0SDimitry Andric                    << ") than the transition (" << Parent->getName() << ").\n");
433739d628a0SDimitry Andric       return false;
433839d628a0SDimitry Andric     }
433939d628a0SDimitry Andric 
434039d628a0SDimitry Andric     if (VPH.canCombine(ToBePromoted)) {
434139d628a0SDimitry Andric       DEBUG(dbgs() << "Assume " << *Inst << '\n'
434239d628a0SDimitry Andric                    << "will be combined with: " << *ToBePromoted << '\n');
434339d628a0SDimitry Andric       VPH.recordCombineInstruction(ToBePromoted);
434439d628a0SDimitry Andric       bool Changed = VPH.promote();
434539d628a0SDimitry Andric       NumStoreExtractExposed += Changed;
434639d628a0SDimitry Andric       return Changed;
434739d628a0SDimitry Andric     }
434839d628a0SDimitry Andric 
434939d628a0SDimitry Andric     DEBUG(dbgs() << "Try promoting.\n");
435039d628a0SDimitry Andric     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
435139d628a0SDimitry Andric       return false;
435239d628a0SDimitry Andric 
435339d628a0SDimitry Andric     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
435439d628a0SDimitry Andric 
435539d628a0SDimitry Andric     VPH.enqueueForPromotion(ToBePromoted);
435639d628a0SDimitry Andric     Inst = ToBePromoted;
435739d628a0SDimitry Andric   }
435839d628a0SDimitry Andric   return false;
435939d628a0SDimitry Andric }
436039d628a0SDimitry Andric 
436139d628a0SDimitry Andric bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
43628f0fd8f6SDimitry Andric   // Bail out if we inserted the instruction to prevent optimizations from
43638f0fd8f6SDimitry Andric   // stepping on each other's toes.
43648f0fd8f6SDimitry Andric   if (InsertedInsts.count(I))
43658f0fd8f6SDimitry Andric     return false;
43668f0fd8f6SDimitry Andric 
436791bc56edSDimitry Andric   if (PHINode *P = dyn_cast<PHINode>(I)) {
436891bc56edSDimitry Andric     // It is possible for very late stage optimizations (such as SimplifyCFG)
436991bc56edSDimitry Andric     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
437091bc56edSDimitry Andric     // trivial PHI, go ahead and zap it here.
4371ff0cc061SDimitry Andric     const DataLayout &DL = I->getModule()->getDataLayout();
4372ff0cc061SDimitry Andric     if (Value *V = SimplifyInstruction(P, DL, TLInfo, nullptr)) {
437391bc56edSDimitry Andric       P->replaceAllUsesWith(V);
437491bc56edSDimitry Andric       P->eraseFromParent();
437591bc56edSDimitry Andric       ++NumPHIsElim;
437691bc56edSDimitry Andric       return true;
437791bc56edSDimitry Andric     }
437891bc56edSDimitry Andric     return false;
437991bc56edSDimitry Andric   }
438091bc56edSDimitry Andric 
438191bc56edSDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
438291bc56edSDimitry Andric     // If the source of the cast is a constant, then this should have
438391bc56edSDimitry Andric     // already been constant folded.  The only reason NOT to constant fold
438491bc56edSDimitry Andric     // it is if something (e.g. LSR) was careful to place the constant
438591bc56edSDimitry Andric     // evaluation in a block other than then one that uses it (e.g. to hoist
438691bc56edSDimitry Andric     // the address of globals out of a loop).  If this is the case, we don't
438791bc56edSDimitry Andric     // want to forward-subst the cast.
438891bc56edSDimitry Andric     if (isa<Constant>(CI->getOperand(0)))
438991bc56edSDimitry Andric       return false;
439091bc56edSDimitry Andric 
439191bc56edSDimitry Andric     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
439291bc56edSDimitry Andric       return true;
439391bc56edSDimitry Andric 
439491bc56edSDimitry Andric     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
439591bc56edSDimitry Andric       /// Sink a zext or sext into its user blocks if the target type doesn't
439691bc56edSDimitry Andric       /// fit in one register
439791bc56edSDimitry Andric       if (TLI && TLI->getTypeAction(CI->getContext(),
439891bc56edSDimitry Andric                                     TLI->getValueType(CI->getType())) ==
439991bc56edSDimitry Andric                      TargetLowering::TypeExpandInteger) {
440091bc56edSDimitry Andric         return SinkCast(CI);
440191bc56edSDimitry Andric       } else {
440291bc56edSDimitry Andric         bool MadeChange = MoveExtToFormExtLoad(I);
440391bc56edSDimitry Andric         return MadeChange | OptimizeExtUses(I);
440491bc56edSDimitry Andric       }
440591bc56edSDimitry Andric     }
440691bc56edSDimitry Andric     return false;
440791bc56edSDimitry Andric   }
440891bc56edSDimitry Andric 
440991bc56edSDimitry Andric   if (CmpInst *CI = dyn_cast<CmpInst>(I))
441091bc56edSDimitry Andric     if (!TLI || !TLI->hasMultipleConditionRegisters())
441191bc56edSDimitry Andric       return OptimizeCmpExpression(CI);
441291bc56edSDimitry Andric 
441391bc56edSDimitry Andric   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
441497bc6c73SDimitry Andric     if (TLI) {
441597bc6c73SDimitry Andric       unsigned AS = LI->getPointerAddressSpace();
441697bc6c73SDimitry Andric       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
441797bc6c73SDimitry Andric     }
441891bc56edSDimitry Andric     return false;
441991bc56edSDimitry Andric   }
442091bc56edSDimitry Andric 
442191bc56edSDimitry Andric   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
442297bc6c73SDimitry Andric     if (TLI) {
442397bc6c73SDimitry Andric       unsigned AS = SI->getPointerAddressSpace();
442491bc56edSDimitry Andric       return OptimizeMemoryInst(I, SI->getOperand(1),
442597bc6c73SDimitry Andric                                 SI->getOperand(0)->getType(), AS);
442697bc6c73SDimitry Andric     }
442791bc56edSDimitry Andric     return false;
442891bc56edSDimitry Andric   }
442991bc56edSDimitry Andric 
443091bc56edSDimitry Andric   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
443191bc56edSDimitry Andric 
443291bc56edSDimitry Andric   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
443391bc56edSDimitry Andric                 BinOp->getOpcode() == Instruction::LShr)) {
443491bc56edSDimitry Andric     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
443591bc56edSDimitry Andric     if (TLI && CI && TLI->hasExtractBitsInsn())
443691bc56edSDimitry Andric       return OptimizeExtractBits(BinOp, CI, *TLI);
443791bc56edSDimitry Andric 
443891bc56edSDimitry Andric     return false;
443991bc56edSDimitry Andric   }
444091bc56edSDimitry Andric 
444191bc56edSDimitry Andric   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
444291bc56edSDimitry Andric     if (GEPI->hasAllZeroIndices()) {
444391bc56edSDimitry Andric       /// The GEP operand must be a pointer, so must its result -> BitCast
444491bc56edSDimitry Andric       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
444591bc56edSDimitry Andric                                         GEPI->getName(), GEPI);
444691bc56edSDimitry Andric       GEPI->replaceAllUsesWith(NC);
444791bc56edSDimitry Andric       GEPI->eraseFromParent();
444891bc56edSDimitry Andric       ++NumGEPsElim;
444939d628a0SDimitry Andric       OptimizeInst(NC, ModifiedDT);
445091bc56edSDimitry Andric       return true;
445191bc56edSDimitry Andric     }
445291bc56edSDimitry Andric     return false;
445391bc56edSDimitry Andric   }
445491bc56edSDimitry Andric 
445591bc56edSDimitry Andric   if (CallInst *CI = dyn_cast<CallInst>(I))
445639d628a0SDimitry Andric     return OptimizeCallInst(CI, ModifiedDT);
445791bc56edSDimitry Andric 
445891bc56edSDimitry Andric   if (SelectInst *SI = dyn_cast<SelectInst>(I))
445991bc56edSDimitry Andric     return OptimizeSelectInst(SI);
446091bc56edSDimitry Andric 
446191bc56edSDimitry Andric   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
446291bc56edSDimitry Andric     return OptimizeShuffleVectorInst(SVI);
446391bc56edSDimitry Andric 
446439d628a0SDimitry Andric   if (isa<ExtractElementInst>(I))
446539d628a0SDimitry Andric     return OptimizeExtractElementInst(I);
446639d628a0SDimitry Andric 
446791bc56edSDimitry Andric   return false;
446891bc56edSDimitry Andric }
446991bc56edSDimitry Andric 
447091bc56edSDimitry Andric // In this pass we look for GEP and cast instructions that are used
447191bc56edSDimitry Andric // across basic blocks and rewrite them to improve basic-block-at-a-time
447291bc56edSDimitry Andric // selection.
447339d628a0SDimitry Andric bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
447491bc56edSDimitry Andric   SunkAddrs.clear();
447591bc56edSDimitry Andric   bool MadeChange = false;
447691bc56edSDimitry Andric 
447791bc56edSDimitry Andric   CurInstIterator = BB.begin();
447839d628a0SDimitry Andric   while (CurInstIterator != BB.end()) {
447939d628a0SDimitry Andric     MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
448039d628a0SDimitry Andric     if (ModifiedDT)
448139d628a0SDimitry Andric       return true;
448239d628a0SDimitry Andric   }
448391bc56edSDimitry Andric   MadeChange |= DupRetToEnableTailCallOpts(&BB);
448491bc56edSDimitry Andric 
448591bc56edSDimitry Andric   return MadeChange;
448691bc56edSDimitry Andric }
448791bc56edSDimitry Andric 
448891bc56edSDimitry Andric // llvm.dbg.value is far away from the value then iSel may not be able
448991bc56edSDimitry Andric // handle it properly. iSel will drop llvm.dbg.value if it can not
449091bc56edSDimitry Andric // find a node corresponding to the value.
449191bc56edSDimitry Andric bool CodeGenPrepare::PlaceDbgValues(Function &F) {
449291bc56edSDimitry Andric   bool MadeChange = false;
449339d628a0SDimitry Andric   for (BasicBlock &BB : F) {
449491bc56edSDimitry Andric     Instruction *PrevNonDbgInst = nullptr;
449539d628a0SDimitry Andric     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
449639d628a0SDimitry Andric       Instruction *Insn = BI++;
449791bc56edSDimitry Andric       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
449891bc56edSDimitry Andric       // Leave dbg.values that refer to an alloca alone. These
449991bc56edSDimitry Andric       // instrinsics describe the address of a variable (= the alloca)
450091bc56edSDimitry Andric       // being taken.  They should not be moved next to the alloca
450191bc56edSDimitry Andric       // (and to the beginning of the scope), but rather stay close to
450291bc56edSDimitry Andric       // where said address is used.
450391bc56edSDimitry Andric       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
450491bc56edSDimitry Andric         PrevNonDbgInst = Insn;
450591bc56edSDimitry Andric         continue;
450691bc56edSDimitry Andric       }
450791bc56edSDimitry Andric 
450891bc56edSDimitry Andric       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
450991bc56edSDimitry Andric       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
451091bc56edSDimitry Andric         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
451191bc56edSDimitry Andric         DVI->removeFromParent();
451291bc56edSDimitry Andric         if (isa<PHINode>(VI))
451391bc56edSDimitry Andric           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
451491bc56edSDimitry Andric         else
451591bc56edSDimitry Andric           DVI->insertAfter(VI);
451691bc56edSDimitry Andric         MadeChange = true;
451791bc56edSDimitry Andric         ++NumDbgValueMoved;
451891bc56edSDimitry Andric       }
451991bc56edSDimitry Andric     }
452091bc56edSDimitry Andric   }
452191bc56edSDimitry Andric   return MadeChange;
452291bc56edSDimitry Andric }
452391bc56edSDimitry Andric 
452491bc56edSDimitry Andric // If there is a sequence that branches based on comparing a single bit
452591bc56edSDimitry Andric // against zero that can be combined into a single instruction, and the
452691bc56edSDimitry Andric // target supports folding these into a single instruction, sink the
452791bc56edSDimitry Andric // mask and compare into the branch uses. Do this before OptimizeBlock ->
452891bc56edSDimitry Andric // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
452991bc56edSDimitry Andric // searched for.
453091bc56edSDimitry Andric bool CodeGenPrepare::sinkAndCmp(Function &F) {
453191bc56edSDimitry Andric   if (!EnableAndCmpSinking)
453291bc56edSDimitry Andric     return false;
453391bc56edSDimitry Andric   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
453491bc56edSDimitry Andric     return false;
453591bc56edSDimitry Andric   bool MadeChange = false;
453691bc56edSDimitry Andric   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
453791bc56edSDimitry Andric     BasicBlock *BB = I++;
453891bc56edSDimitry Andric 
453991bc56edSDimitry Andric     // Does this BB end with the following?
454091bc56edSDimitry Andric     //   %andVal = and %val, #single-bit-set
454191bc56edSDimitry Andric     //   %icmpVal = icmp %andResult, 0
454291bc56edSDimitry Andric     //   br i1 %cmpVal label %dest1, label %dest2"
454391bc56edSDimitry Andric     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
454491bc56edSDimitry Andric     if (!Brcc || !Brcc->isConditional())
454591bc56edSDimitry Andric       continue;
454691bc56edSDimitry Andric     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
454791bc56edSDimitry Andric     if (!Cmp || Cmp->getParent() != BB)
454891bc56edSDimitry Andric       continue;
454991bc56edSDimitry Andric     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
455091bc56edSDimitry Andric     if (!Zero || !Zero->isZero())
455191bc56edSDimitry Andric       continue;
455291bc56edSDimitry Andric     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
455391bc56edSDimitry Andric     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
455491bc56edSDimitry Andric       continue;
455591bc56edSDimitry Andric     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
455691bc56edSDimitry Andric     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
455791bc56edSDimitry Andric       continue;
455891bc56edSDimitry Andric     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
455991bc56edSDimitry Andric 
456091bc56edSDimitry Andric     // Push the "and; icmp" for any users that are conditional branches.
456191bc56edSDimitry Andric     // Since there can only be one branch use per BB, we don't need to keep
456291bc56edSDimitry Andric     // track of which BBs we insert into.
456391bc56edSDimitry Andric     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
456491bc56edSDimitry Andric          UI != E; ) {
456591bc56edSDimitry Andric       Use &TheUse = *UI;
456691bc56edSDimitry Andric       // Find brcc use.
456791bc56edSDimitry Andric       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
456891bc56edSDimitry Andric       ++UI;
456991bc56edSDimitry Andric       if (!BrccUser || !BrccUser->isConditional())
457091bc56edSDimitry Andric         continue;
457191bc56edSDimitry Andric       BasicBlock *UserBB = BrccUser->getParent();
457291bc56edSDimitry Andric       if (UserBB == BB) continue;
457391bc56edSDimitry Andric       DEBUG(dbgs() << "found Brcc use\n");
457491bc56edSDimitry Andric 
457591bc56edSDimitry Andric       // Sink the "and; icmp" to use.
457691bc56edSDimitry Andric       MadeChange = true;
457791bc56edSDimitry Andric       BinaryOperator *NewAnd =
457891bc56edSDimitry Andric         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
457991bc56edSDimitry Andric                                   BrccUser);
458091bc56edSDimitry Andric       CmpInst *NewCmp =
458191bc56edSDimitry Andric         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
458291bc56edSDimitry Andric                         "", BrccUser);
458391bc56edSDimitry Andric       TheUse = NewCmp;
458491bc56edSDimitry Andric       ++NumAndCmpsMoved;
458591bc56edSDimitry Andric       DEBUG(BrccUser->getParent()->dump());
458691bc56edSDimitry Andric     }
458791bc56edSDimitry Andric   }
458891bc56edSDimitry Andric   return MadeChange;
458991bc56edSDimitry Andric }
459039d628a0SDimitry Andric 
459139d628a0SDimitry Andric /// \brief Retrieve the probabilities of a conditional branch. Returns true on
459239d628a0SDimitry Andric /// success, or returns false if no or invalid metadata was found.
459339d628a0SDimitry Andric static bool extractBranchMetadata(BranchInst *BI,
459439d628a0SDimitry Andric                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
459539d628a0SDimitry Andric   assert(BI->isConditional() &&
459639d628a0SDimitry Andric          "Looking for probabilities on unconditional branch?");
459739d628a0SDimitry Andric   auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
459839d628a0SDimitry Andric   if (!ProfileData || ProfileData->getNumOperands() != 3)
459939d628a0SDimitry Andric     return false;
460039d628a0SDimitry Andric 
460139d628a0SDimitry Andric   const auto *CITrue =
460239d628a0SDimitry Andric       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
460339d628a0SDimitry Andric   const auto *CIFalse =
460439d628a0SDimitry Andric       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
460539d628a0SDimitry Andric   if (!CITrue || !CIFalse)
460639d628a0SDimitry Andric     return false;
460739d628a0SDimitry Andric 
460839d628a0SDimitry Andric   ProbTrue = CITrue->getValue().getZExtValue();
460939d628a0SDimitry Andric   ProbFalse = CIFalse->getValue().getZExtValue();
461039d628a0SDimitry Andric 
461139d628a0SDimitry Andric   return true;
461239d628a0SDimitry Andric }
461339d628a0SDimitry Andric 
461439d628a0SDimitry Andric /// \brief Scale down both weights to fit into uint32_t.
461539d628a0SDimitry Andric static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
461639d628a0SDimitry Andric   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
461739d628a0SDimitry Andric   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
461839d628a0SDimitry Andric   NewTrue = NewTrue / Scale;
461939d628a0SDimitry Andric   NewFalse = NewFalse / Scale;
462039d628a0SDimitry Andric }
462139d628a0SDimitry Andric 
462239d628a0SDimitry Andric /// \brief Some targets prefer to split a conditional branch like:
462339d628a0SDimitry Andric /// \code
462439d628a0SDimitry Andric ///   %0 = icmp ne i32 %a, 0
462539d628a0SDimitry Andric ///   %1 = icmp ne i32 %b, 0
462639d628a0SDimitry Andric ///   %or.cond = or i1 %0, %1
462739d628a0SDimitry Andric ///   br i1 %or.cond, label %TrueBB, label %FalseBB
462839d628a0SDimitry Andric /// \endcode
462939d628a0SDimitry Andric /// into multiple branch instructions like:
463039d628a0SDimitry Andric /// \code
463139d628a0SDimitry Andric ///   bb1:
463239d628a0SDimitry Andric ///     %0 = icmp ne i32 %a, 0
463339d628a0SDimitry Andric ///     br i1 %0, label %TrueBB, label %bb2
463439d628a0SDimitry Andric ///   bb2:
463539d628a0SDimitry Andric ///     %1 = icmp ne i32 %b, 0
463639d628a0SDimitry Andric ///     br i1 %1, label %TrueBB, label %FalseBB
463739d628a0SDimitry Andric /// \endcode
463839d628a0SDimitry Andric /// This usually allows instruction selection to do even further optimizations
463939d628a0SDimitry Andric /// and combine the compare with the branch instruction. Currently this is
464039d628a0SDimitry Andric /// applied for targets which have "cheap" jump instructions.
464139d628a0SDimitry Andric ///
464239d628a0SDimitry Andric /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
464339d628a0SDimitry Andric ///
464439d628a0SDimitry Andric bool CodeGenPrepare::splitBranchCondition(Function &F) {
4645ff0cc061SDimitry Andric   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
464639d628a0SDimitry Andric     return false;
464739d628a0SDimitry Andric 
464839d628a0SDimitry Andric   bool MadeChange = false;
464939d628a0SDimitry Andric   for (auto &BB : F) {
465039d628a0SDimitry Andric     // Does this BB end with the following?
465139d628a0SDimitry Andric     //   %cond1 = icmp|fcmp|binary instruction ...
465239d628a0SDimitry Andric     //   %cond2 = icmp|fcmp|binary instruction ...
465339d628a0SDimitry Andric     //   %cond.or = or|and i1 %cond1, cond2
465439d628a0SDimitry Andric     //   br i1 %cond.or label %dest1, label %dest2"
465539d628a0SDimitry Andric     BinaryOperator *LogicOp;
465639d628a0SDimitry Andric     BasicBlock *TBB, *FBB;
465739d628a0SDimitry Andric     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
465839d628a0SDimitry Andric       continue;
465939d628a0SDimitry Andric 
466039d628a0SDimitry Andric     unsigned Opc;
466139d628a0SDimitry Andric     Value *Cond1, *Cond2;
466239d628a0SDimitry Andric     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
466339d628a0SDimitry Andric                              m_OneUse(m_Value(Cond2)))))
466439d628a0SDimitry Andric       Opc = Instruction::And;
466539d628a0SDimitry Andric     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
466639d628a0SDimitry Andric                                  m_OneUse(m_Value(Cond2)))))
466739d628a0SDimitry Andric       Opc = Instruction::Or;
466839d628a0SDimitry Andric     else
466939d628a0SDimitry Andric       continue;
467039d628a0SDimitry Andric 
467139d628a0SDimitry Andric     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
467239d628a0SDimitry Andric         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
467339d628a0SDimitry Andric       continue;
467439d628a0SDimitry Andric 
467539d628a0SDimitry Andric     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
467639d628a0SDimitry Andric 
467739d628a0SDimitry Andric     // Create a new BB.
467839d628a0SDimitry Andric     auto *InsertBefore = std::next(Function::iterator(BB))
467939d628a0SDimitry Andric         .getNodePtrUnchecked();
468039d628a0SDimitry Andric     auto TmpBB = BasicBlock::Create(BB.getContext(),
468139d628a0SDimitry Andric                                     BB.getName() + ".cond.split",
468239d628a0SDimitry Andric                                     BB.getParent(), InsertBefore);
468339d628a0SDimitry Andric 
468439d628a0SDimitry Andric     // Update original basic block by using the first condition directly by the
468539d628a0SDimitry Andric     // branch instruction and removing the no longer needed and/or instruction.
468639d628a0SDimitry Andric     auto *Br1 = cast<BranchInst>(BB.getTerminator());
468739d628a0SDimitry Andric     Br1->setCondition(Cond1);
468839d628a0SDimitry Andric     LogicOp->eraseFromParent();
468939d628a0SDimitry Andric 
469039d628a0SDimitry Andric     // Depending on the conditon we have to either replace the true or the false
469139d628a0SDimitry Andric     // successor of the original branch instruction.
469239d628a0SDimitry Andric     if (Opc == Instruction::And)
469339d628a0SDimitry Andric       Br1->setSuccessor(0, TmpBB);
469439d628a0SDimitry Andric     else
469539d628a0SDimitry Andric       Br1->setSuccessor(1, TmpBB);
469639d628a0SDimitry Andric 
469739d628a0SDimitry Andric     // Fill in the new basic block.
469839d628a0SDimitry Andric     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
469939d628a0SDimitry Andric     if (auto *I = dyn_cast<Instruction>(Cond2)) {
470039d628a0SDimitry Andric       I->removeFromParent();
470139d628a0SDimitry Andric       I->insertBefore(Br2);
470239d628a0SDimitry Andric     }
470339d628a0SDimitry Andric 
470439d628a0SDimitry Andric     // Update PHI nodes in both successors. The original BB needs to be
470539d628a0SDimitry Andric     // replaced in one succesor's PHI nodes, because the branch comes now from
470639d628a0SDimitry Andric     // the newly generated BB (NewBB). In the other successor we need to add one
470739d628a0SDimitry Andric     // incoming edge to the PHI nodes, because both branch instructions target
470839d628a0SDimitry Andric     // now the same successor. Depending on the original branch condition
470939d628a0SDimitry Andric     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
471039d628a0SDimitry Andric     // we perfrom the correct update for the PHI nodes.
471139d628a0SDimitry Andric     // This doesn't change the successor order of the just created branch
471239d628a0SDimitry Andric     // instruction (or any other instruction).
471339d628a0SDimitry Andric     if (Opc == Instruction::Or)
471439d628a0SDimitry Andric       std::swap(TBB, FBB);
471539d628a0SDimitry Andric 
471639d628a0SDimitry Andric     // Replace the old BB with the new BB.
471739d628a0SDimitry Andric     for (auto &I : *TBB) {
471839d628a0SDimitry Andric       PHINode *PN = dyn_cast<PHINode>(&I);
471939d628a0SDimitry Andric       if (!PN)
472039d628a0SDimitry Andric         break;
472139d628a0SDimitry Andric       int i;
472239d628a0SDimitry Andric       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
472339d628a0SDimitry Andric         PN->setIncomingBlock(i, TmpBB);
472439d628a0SDimitry Andric     }
472539d628a0SDimitry Andric 
472639d628a0SDimitry Andric     // Add another incoming edge form the new BB.
472739d628a0SDimitry Andric     for (auto &I : *FBB) {
472839d628a0SDimitry Andric       PHINode *PN = dyn_cast<PHINode>(&I);
472939d628a0SDimitry Andric       if (!PN)
473039d628a0SDimitry Andric         break;
473139d628a0SDimitry Andric       auto *Val = PN->getIncomingValueForBlock(&BB);
473239d628a0SDimitry Andric       PN->addIncoming(Val, TmpBB);
473339d628a0SDimitry Andric     }
473439d628a0SDimitry Andric 
473539d628a0SDimitry Andric     // Update the branch weights (from SelectionDAGBuilder::
473639d628a0SDimitry Andric     // FindMergedConditions).
473739d628a0SDimitry Andric     if (Opc == Instruction::Or) {
473839d628a0SDimitry Andric       // Codegen X | Y as:
473939d628a0SDimitry Andric       // BB1:
474039d628a0SDimitry Andric       //   jmp_if_X TBB
474139d628a0SDimitry Andric       //   jmp TmpBB
474239d628a0SDimitry Andric       // TmpBB:
474339d628a0SDimitry Andric       //   jmp_if_Y TBB
474439d628a0SDimitry Andric       //   jmp FBB
474539d628a0SDimitry Andric       //
474639d628a0SDimitry Andric 
474739d628a0SDimitry Andric       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
474839d628a0SDimitry Andric       // The requirement is that
474939d628a0SDimitry Andric       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
475039d628a0SDimitry Andric       //     = TrueProb for orignal BB.
475139d628a0SDimitry Andric       // Assuming the orignal weights are A and B, one choice is to set BB1's
475239d628a0SDimitry Andric       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
475339d628a0SDimitry Andric       // assumes that
475439d628a0SDimitry Andric       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
475539d628a0SDimitry Andric       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
475639d628a0SDimitry Andric       // TmpBB, but the math is more complicated.
475739d628a0SDimitry Andric       uint64_t TrueWeight, FalseWeight;
475839d628a0SDimitry Andric       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
475939d628a0SDimitry Andric         uint64_t NewTrueWeight = TrueWeight;
476039d628a0SDimitry Andric         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
476139d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
476239d628a0SDimitry Andric         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
476339d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
476439d628a0SDimitry Andric 
476539d628a0SDimitry Andric         NewTrueWeight = TrueWeight;
476639d628a0SDimitry Andric         NewFalseWeight = 2 * FalseWeight;
476739d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
476839d628a0SDimitry Andric         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
476939d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
477039d628a0SDimitry Andric       }
477139d628a0SDimitry Andric     } else {
477239d628a0SDimitry Andric       // Codegen X & Y as:
477339d628a0SDimitry Andric       // BB1:
477439d628a0SDimitry Andric       //   jmp_if_X TmpBB
477539d628a0SDimitry Andric       //   jmp FBB
477639d628a0SDimitry Andric       // TmpBB:
477739d628a0SDimitry Andric       //   jmp_if_Y TBB
477839d628a0SDimitry Andric       //   jmp FBB
477939d628a0SDimitry Andric       //
478039d628a0SDimitry Andric       //  This requires creation of TmpBB after CurBB.
478139d628a0SDimitry Andric 
478239d628a0SDimitry Andric       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
478339d628a0SDimitry Andric       // The requirement is that
478439d628a0SDimitry Andric       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
478539d628a0SDimitry Andric       //     = FalseProb for orignal BB.
478639d628a0SDimitry Andric       // Assuming the orignal weights are A and B, one choice is to set BB1's
478739d628a0SDimitry Andric       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
478839d628a0SDimitry Andric       // assumes that
478939d628a0SDimitry Andric       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
479039d628a0SDimitry Andric       uint64_t TrueWeight, FalseWeight;
479139d628a0SDimitry Andric       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
479239d628a0SDimitry Andric         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
479339d628a0SDimitry Andric         uint64_t NewFalseWeight = FalseWeight;
479439d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
479539d628a0SDimitry Andric         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
479639d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
479739d628a0SDimitry Andric 
479839d628a0SDimitry Andric         NewTrueWeight = 2 * TrueWeight;
479939d628a0SDimitry Andric         NewFalseWeight = FalseWeight;
480039d628a0SDimitry Andric         scaleWeights(NewTrueWeight, NewFalseWeight);
480139d628a0SDimitry Andric         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
480239d628a0SDimitry Andric                          .createBranchWeights(TrueWeight, FalseWeight));
480339d628a0SDimitry Andric       }
480439d628a0SDimitry Andric     }
480539d628a0SDimitry Andric 
480639d628a0SDimitry Andric     // Note: No point in getting fancy here, since the DT info is never
4807ff0cc061SDimitry Andric     // available to CodeGenPrepare.
480839d628a0SDimitry Andric     ModifiedDT = true;
480939d628a0SDimitry Andric 
481039d628a0SDimitry Andric     MadeChange = true;
481139d628a0SDimitry Andric 
481239d628a0SDimitry Andric     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
481339d628a0SDimitry Andric           TmpBB->dump());
481439d628a0SDimitry Andric   }
481539d628a0SDimitry Andric   return MadeChange;
481639d628a0SDimitry Andric }
4817