LLVM API Documentation

CodeGenPrepare.cpp
Go to the documentation of this file.
00001 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass munges the code in the input function to better prepare it for
00011 // SelectionDAG-based code generation. This works around limitations in it's
00012 // basic-block-at-a-time approach. It should eventually be removed.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/CodeGen/Passes.h"
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/SmallSet.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/InstructionSimplify.h"
00021 #include "llvm/Analysis/TargetTransformInfo.h"
00022 #include "llvm/IR/CallSite.h"
00023 #include "llvm/IR/Constants.h"
00024 #include "llvm/IR/DataLayout.h"
00025 #include "llvm/IR/DerivedTypes.h"
00026 #include "llvm/IR/Dominators.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/IR/GetElementPtrTypeIterator.h"
00029 #include "llvm/IR/IRBuilder.h"
00030 #include "llvm/IR/InlineAsm.h"
00031 #include "llvm/IR/Instructions.h"
00032 #include "llvm/IR/IntrinsicInst.h"
00033 #include "llvm/IR/PatternMatch.h"
00034 #include "llvm/IR/ValueHandle.h"
00035 #include "llvm/IR/ValueMap.h"
00036 #include "llvm/Pass.h"
00037 #include "llvm/Support/CommandLine.h"
00038 #include "llvm/Support/Debug.h"
00039 #include "llvm/Support/raw_ostream.h"
00040 #include "llvm/Target/TargetLibraryInfo.h"
00041 #include "llvm/Target/TargetLowering.h"
00042 #include "llvm/Target/TargetSubtargetInfo.h"
00043 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00044 #include "llvm/Transforms/Utils/BuildLibCalls.h"
00045 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
00046 #include "llvm/Transforms/Utils/Local.h"
00047 using namespace llvm;
00048 using namespace llvm::PatternMatch;
00049 
00050 #define DEBUG_TYPE "codegenprepare"
00051 
00052 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
00053 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
00054 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
00055 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
00056                       "sunken Cmps");
00057 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
00058                        "of sunken Casts");
00059 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
00060                           "computations were sunk");
00061 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
00062 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
00063 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
00064 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
00065 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
00066 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
00067 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
00068 
00069 static cl::opt<bool> DisableBranchOpts(
00070   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
00071   cl::desc("Disable branch optimizations in CodeGenPrepare"));
00072 
00073 static cl::opt<bool> DisableSelectToBranch(
00074   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
00075   cl::desc("Disable select to branch conversion."));
00076 
00077 static cl::opt<bool> AddrSinkUsingGEPs(
00078   "addr-sink-using-gep", cl::Hidden, cl::init(false),
00079   cl::desc("Address sinking in CGP using GEPs."));
00080 
00081 static cl::opt<bool> EnableAndCmpSinking(
00082    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
00083    cl::desc("Enable sinkinig and/cmp into branches."));
00084 
00085 static cl::opt<bool> DisableStoreExtract(
00086     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
00087     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
00088 
00089 static cl::opt<bool> StressStoreExtract(
00090     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
00091     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
00092 
00093 namespace {
00094 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
00095 typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
00096 
00097   class CodeGenPrepare : public FunctionPass {
00098     /// TLI - Keep a pointer of a TargetLowering to consult for determining
00099     /// transformation profitability.
00100     const TargetMachine *TM;
00101     const TargetLowering *TLI;
00102     const TargetTransformInfo *TTI;
00103     const TargetLibraryInfo *TLInfo;
00104     DominatorTree *DT;
00105 
00106     /// CurInstIterator - As we scan instructions optimizing them, this is the
00107     /// next instruction to optimize.  Xforms that can invalidate this should
00108     /// update it.
00109     BasicBlock::iterator CurInstIterator;
00110 
00111     /// Keeps track of non-local addresses that have been sunk into a block.
00112     /// This allows us to avoid inserting duplicate code for blocks with
00113     /// multiple load/stores of the same address.
00114     ValueMap<Value*, Value*> SunkAddrs;
00115 
00116     /// Keeps track of all truncates inserted for the current function.
00117     SetOfInstrs InsertedTruncsSet;
00118     /// Keeps track of the type of the related instruction before their
00119     /// promotion for the current function.
00120     InstrToOrigTy PromotedInsts;
00121 
00122     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
00123     /// be updated.
00124     bool ModifiedDT;
00125 
00126     /// OptSize - True if optimizing for size.
00127     bool OptSize;
00128 
00129   public:
00130     static char ID; // Pass identification, replacement for typeid
00131     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
00132         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
00133         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
00134       }
00135     bool runOnFunction(Function &F) override;
00136 
00137     const char *getPassName() const override { return "CodeGen Prepare"; }
00138 
00139     void getAnalysisUsage(AnalysisUsage &AU) const override {
00140       AU.addPreserved<DominatorTreeWrapperPass>();
00141       AU.addRequired<TargetLibraryInfo>();
00142       AU.addRequired<TargetTransformInfo>();
00143     }
00144 
00145   private:
00146     bool EliminateFallThrough(Function &F);
00147     bool EliminateMostlyEmptyBlocks(Function &F);
00148     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
00149     void EliminateMostlyEmptyBlock(BasicBlock *BB);
00150     bool OptimizeBlock(BasicBlock &BB);
00151     bool OptimizeInst(Instruction *I);
00152     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
00153     bool OptimizeInlineAsmInst(CallInst *CS);
00154     bool OptimizeCallInst(CallInst *CI);
00155     bool MoveExtToFormExtLoad(Instruction *I);
00156     bool OptimizeExtUses(Instruction *I);
00157     bool OptimizeSelectInst(SelectInst *SI);
00158     bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
00159     bool OptimizeExtractElementInst(Instruction *Inst);
00160     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
00161     bool PlaceDbgValues(Function &F);
00162     bool sinkAndCmp(Function &F);
00163   };
00164 }
00165 
00166 char CodeGenPrepare::ID = 0;
00167 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
00168                    "Optimize for code generation", false, false)
00169 
00170 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
00171   return new CodeGenPrepare(TM);
00172 }
00173 
00174 bool CodeGenPrepare::runOnFunction(Function &F) {
00175   if (skipOptnoneFunction(F))
00176     return false;
00177 
00178   bool EverMadeChange = false;
00179   // Clear per function information.
00180   InsertedTruncsSet.clear();
00181   PromotedInsts.clear();
00182 
00183   ModifiedDT = false;
00184   if (TM)
00185     TLI = TM->getSubtargetImpl()->getTargetLowering();
00186   TLInfo = &getAnalysis<TargetLibraryInfo>();
00187   TTI = &getAnalysis<TargetTransformInfo>();
00188   DominatorTreeWrapperPass *DTWP =
00189       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00190   DT = DTWP ? &DTWP->getDomTree() : nullptr;
00191   OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00192                                            Attribute::OptimizeForSize);
00193 
00194   /// This optimization identifies DIV instructions that can be
00195   /// profitably bypassed and carried out with a shorter, faster divide.
00196   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
00197     const DenseMap<unsigned int, unsigned int> &BypassWidths =
00198        TLI->getBypassSlowDivWidths();
00199     for (Function::iterator I = F.begin(); I != F.end(); I++)
00200       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
00201   }
00202 
00203   // Eliminate blocks that contain only PHI nodes and an
00204   // unconditional branch.
00205   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
00206 
00207   // llvm.dbg.value is far away from the value then iSel may not be able
00208   // handle it properly. iSel will drop llvm.dbg.value if it can not
00209   // find a node corresponding to the value.
00210   EverMadeChange |= PlaceDbgValues(F);
00211 
00212   // If there is a mask, compare against zero, and branch that can be combined
00213   // into a single target instruction, push the mask and compare into branch
00214   // users. Do this before OptimizeBlock -> OptimizeInst ->
00215   // OptimizeCmpExpression, which perturbs the pattern being searched for.
00216   if (!DisableBranchOpts)
00217     EverMadeChange |= sinkAndCmp(F);
00218 
00219   bool MadeChange = true;
00220   while (MadeChange) {
00221     MadeChange = false;
00222     for (Function::iterator I = F.begin(); I != F.end(); ) {
00223       BasicBlock *BB = I++;
00224       MadeChange |= OptimizeBlock(*BB);
00225     }
00226     EverMadeChange |= MadeChange;
00227   }
00228 
00229   SunkAddrs.clear();
00230 
00231   if (!DisableBranchOpts) {
00232     MadeChange = false;
00233     SmallPtrSet<BasicBlock*, 8> WorkList;
00234     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00235       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
00236       MadeChange |= ConstantFoldTerminator(BB, true);
00237       if (!MadeChange) continue;
00238 
00239       for (SmallVectorImpl<BasicBlock*>::iterator
00240              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
00241         if (pred_begin(*II) == pred_end(*II))
00242           WorkList.insert(*II);
00243     }
00244 
00245     // Delete the dead blocks and any of their dead successors.
00246     MadeChange |= !WorkList.empty();
00247     while (!WorkList.empty()) {
00248       BasicBlock *BB = *WorkList.begin();
00249       WorkList.erase(BB);
00250       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
00251 
00252       DeleteDeadBlock(BB);
00253 
00254       for (SmallVectorImpl<BasicBlock*>::iterator
00255              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
00256         if (pred_begin(*II) == pred_end(*II))
00257           WorkList.insert(*II);
00258     }
00259 
00260     // Merge pairs of basic blocks with unconditional branches, connected by
00261     // a single edge.
00262     if (EverMadeChange || MadeChange)
00263       MadeChange |= EliminateFallThrough(F);
00264 
00265     if (MadeChange)
00266       ModifiedDT = true;
00267     EverMadeChange |= MadeChange;
00268   }
00269 
00270   if (ModifiedDT && DT)
00271     DT->recalculate(F);
00272 
00273   return EverMadeChange;
00274 }
00275 
00276 /// EliminateFallThrough - Merge basic blocks which are connected
00277 /// by a single edge, where one of the basic blocks has a single successor
00278 /// pointing to the other basic block, which has a single predecessor.
00279 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
00280   bool Changed = false;
00281   // Scan all of the blocks in the function, except for the entry block.
00282   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
00283     BasicBlock *BB = I++;
00284     // If the destination block has a single pred, then this is a trivial
00285     // edge, just collapse it.
00286     BasicBlock *SinglePred = BB->getSinglePredecessor();
00287 
00288     // Don't merge if BB's address is taken.
00289     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
00290 
00291     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
00292     if (Term && !Term->isConditional()) {
00293       Changed = true;
00294       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
00295       // Remember if SinglePred was the entry block of the function.
00296       // If so, we will need to move BB back to the entry position.
00297       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
00298       MergeBasicBlockIntoOnlyPred(BB, this);
00299 
00300       if (isEntry && BB != &BB->getParent()->getEntryBlock())
00301         BB->moveBefore(&BB->getParent()->getEntryBlock());
00302 
00303       // We have erased a block. Update the iterator.
00304       I = BB;
00305     }
00306   }
00307   return Changed;
00308 }
00309 
00310 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
00311 /// debug info directives, and an unconditional branch.  Passes before isel
00312 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
00313 /// isel.  Start by eliminating these blocks so we can split them the way we
00314 /// want them.
00315 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
00316   bool MadeChange = false;
00317   // Note that this intentionally skips the entry block.
00318   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
00319     BasicBlock *BB = I++;
00320 
00321     // If this block doesn't end with an uncond branch, ignore it.
00322     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
00323     if (!BI || !BI->isUnconditional())
00324       continue;
00325 
00326     // If the instruction before the branch (skipping debug info) isn't a phi
00327     // node, then other stuff is happening here.
00328     BasicBlock::iterator BBI = BI;
00329     if (BBI != BB->begin()) {
00330       --BBI;
00331       while (isa<DbgInfoIntrinsic>(BBI)) {
00332         if (BBI == BB->begin())
00333           break;
00334         --BBI;
00335       }
00336       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
00337         continue;
00338     }
00339 
00340     // Do not break infinite loops.
00341     BasicBlock *DestBB = BI->getSuccessor(0);
00342     if (DestBB == BB)
00343       continue;
00344 
00345     if (!CanMergeBlocks(BB, DestBB))
00346       continue;
00347 
00348     EliminateMostlyEmptyBlock(BB);
00349     MadeChange = true;
00350   }
00351   return MadeChange;
00352 }
00353 
00354 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
00355 /// single uncond branch between them, and BB contains no other non-phi
00356 /// instructions.
00357 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
00358                                     const BasicBlock *DestBB) const {
00359   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
00360   // the successor.  If there are more complex condition (e.g. preheaders),
00361   // don't mess around with them.
00362   BasicBlock::const_iterator BBI = BB->begin();
00363   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
00364     for (const User *U : PN->users()) {
00365       const Instruction *UI = cast<Instruction>(U);
00366       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
00367         return false;
00368       // If User is inside DestBB block and it is a PHINode then check
00369       // incoming value. If incoming value is not from BB then this is
00370       // a complex condition (e.g. preheaders) we want to avoid here.
00371       if (UI->getParent() == DestBB) {
00372         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
00373           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
00374             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
00375             if (Insn && Insn->getParent() == BB &&
00376                 Insn->getParent() != UPN->getIncomingBlock(I))
00377               return false;
00378           }
00379       }
00380     }
00381   }
00382 
00383   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
00384   // and DestBB may have conflicting incoming values for the block.  If so, we
00385   // can't merge the block.
00386   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
00387   if (!DestBBPN) return true;  // no conflict.
00388 
00389   // Collect the preds of BB.
00390   SmallPtrSet<const BasicBlock*, 16> BBPreds;
00391   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
00392     // It is faster to get preds from a PHI than with pred_iterator.
00393     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
00394       BBPreds.insert(BBPN->getIncomingBlock(i));
00395   } else {
00396     BBPreds.insert(pred_begin(BB), pred_end(BB));
00397   }
00398 
00399   // Walk the preds of DestBB.
00400   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
00401     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
00402     if (BBPreds.count(Pred)) {   // Common predecessor?
00403       BBI = DestBB->begin();
00404       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
00405         const Value *V1 = PN->getIncomingValueForBlock(Pred);
00406         const Value *V2 = PN->getIncomingValueForBlock(BB);
00407 
00408         // If V2 is a phi node in BB, look up what the mapped value will be.
00409         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
00410           if (V2PN->getParent() == BB)
00411             V2 = V2PN->getIncomingValueForBlock(Pred);
00412 
00413         // If there is a conflict, bail out.
00414         if (V1 != V2) return false;
00415       }
00416     }
00417   }
00418 
00419   return true;
00420 }
00421 
00422 
00423 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
00424 /// an unconditional branch in it.
00425 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
00426   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
00427   BasicBlock *DestBB = BI->getSuccessor(0);
00428 
00429   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
00430 
00431   // If the destination block has a single pred, then this is a trivial edge,
00432   // just collapse it.
00433   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
00434     if (SinglePred != DestBB) {
00435       // Remember if SinglePred was the entry block of the function.  If so, we
00436       // will need to move BB back to the entry position.
00437       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
00438       MergeBasicBlockIntoOnlyPred(DestBB, this);
00439 
00440       if (isEntry && BB != &BB->getParent()->getEntryBlock())
00441         BB->moveBefore(&BB->getParent()->getEntryBlock());
00442 
00443       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
00444       return;
00445     }
00446   }
00447 
00448   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
00449   // to handle the new incoming edges it is about to have.
00450   PHINode *PN;
00451   for (BasicBlock::iterator BBI = DestBB->begin();
00452        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
00453     // Remove the incoming value for BB, and remember it.
00454     Value *InVal = PN->removeIncomingValue(BB, false);
00455 
00456     // Two options: either the InVal is a phi node defined in BB or it is some
00457     // value that dominates BB.
00458     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
00459     if (InValPhi && InValPhi->getParent() == BB) {
00460       // Add all of the input values of the input PHI as inputs of this phi.
00461       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
00462         PN->addIncoming(InValPhi->getIncomingValue(i),
00463                         InValPhi->getIncomingBlock(i));
00464     } else {
00465       // Otherwise, add one instance of the dominating value for each edge that
00466       // we will be adding.
00467       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
00468         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
00469           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
00470       } else {
00471         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00472           PN->addIncoming(InVal, *PI);
00473       }
00474     }
00475   }
00476 
00477   // The PHIs are now updated, change everything that refers to BB to use
00478   // DestBB and remove BB.
00479   BB->replaceAllUsesWith(DestBB);
00480   if (DT && !ModifiedDT) {
00481     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
00482     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
00483     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
00484     DT->changeImmediateDominator(DestBB, NewIDom);
00485     DT->eraseNode(BB);
00486   }
00487   BB->eraseFromParent();
00488   ++NumBlocksElim;
00489 
00490   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
00491 }
00492 
00493 /// SinkCast - Sink the specified cast instruction into its user blocks
00494 static bool SinkCast(CastInst *CI) {
00495   BasicBlock *DefBB = CI->getParent();
00496 
00497   /// InsertedCasts - Only insert a cast in each block once.
00498   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
00499 
00500   bool MadeChange = false;
00501   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
00502        UI != E; ) {
00503     Use &TheUse = UI.getUse();
00504     Instruction *User = cast<Instruction>(*UI);
00505 
00506     // Figure out which BB this cast is used in.  For PHI's this is the
00507     // appropriate predecessor block.
00508     BasicBlock *UserBB = User->getParent();
00509     if (PHINode *PN = dyn_cast<PHINode>(User)) {
00510       UserBB = PN->getIncomingBlock(TheUse);
00511     }
00512 
00513     // Preincrement use iterator so we don't invalidate it.
00514     ++UI;
00515 
00516     // If this user is in the same block as the cast, don't change the cast.
00517     if (UserBB == DefBB) continue;
00518 
00519     // If we have already inserted a cast into this block, use it.
00520     CastInst *&InsertedCast = InsertedCasts[UserBB];
00521 
00522     if (!InsertedCast) {
00523       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
00524       InsertedCast =
00525         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
00526                          InsertPt);
00527       MadeChange = true;
00528     }
00529 
00530     // Replace a use of the cast with a use of the new cast.
00531     TheUse = InsertedCast;
00532     ++NumCastUses;
00533   }
00534 
00535   // If we removed all uses, nuke the cast.
00536   if (CI->use_empty()) {
00537     CI->eraseFromParent();
00538     MadeChange = true;
00539   }
00540 
00541   return MadeChange;
00542 }
00543 
00544 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
00545 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
00546 /// sink it into user blocks to reduce the number of virtual
00547 /// registers that must be created and coalesced.
00548 ///
00549 /// Return true if any changes are made.
00550 ///
00551 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
00552   // If this is a noop copy,
00553   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
00554   EVT DstVT = TLI.getValueType(CI->getType());
00555 
00556   // This is an fp<->int conversion?
00557   if (SrcVT.isInteger() != DstVT.isInteger())
00558     return false;
00559 
00560   // If this is an extension, it will be a zero or sign extension, which
00561   // isn't a noop.
00562   if (SrcVT.bitsLT(DstVT)) return false;
00563 
00564   // If these values will be promoted, find out what they will be promoted
00565   // to.  This helps us consider truncates on PPC as noop copies when they
00566   // are.
00567   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
00568       TargetLowering::TypePromoteInteger)
00569     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
00570   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
00571       TargetLowering::TypePromoteInteger)
00572     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
00573 
00574   // If, after promotion, these are the same types, this is a noop copy.
00575   if (SrcVT != DstVT)
00576     return false;
00577 
00578   return SinkCast(CI);
00579 }
00580 
00581 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
00582 /// the number of virtual registers that must be created and coalesced.  This is
00583 /// a clear win except on targets with multiple condition code registers
00584 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
00585 ///
00586 /// Return true if any changes are made.
00587 static bool OptimizeCmpExpression(CmpInst *CI) {
00588   BasicBlock *DefBB = CI->getParent();
00589 
00590   /// InsertedCmp - Only insert a cmp in each block once.
00591   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
00592 
00593   bool MadeChange = false;
00594   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
00595        UI != E; ) {
00596     Use &TheUse = UI.getUse();
00597     Instruction *User = cast<Instruction>(*UI);
00598 
00599     // Preincrement use iterator so we don't invalidate it.
00600     ++UI;
00601 
00602     // Don't bother for PHI nodes.
00603     if (isa<PHINode>(User))
00604       continue;
00605 
00606     // Figure out which BB this cmp is used in.
00607     BasicBlock *UserBB = User->getParent();
00608 
00609     // If this user is in the same block as the cmp, don't change the cmp.
00610     if (UserBB == DefBB) continue;
00611 
00612     // If we have already inserted a cmp into this block, use it.
00613     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
00614 
00615     if (!InsertedCmp) {
00616       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
00617       InsertedCmp =
00618         CmpInst::Create(CI->getOpcode(),
00619                         CI->getPredicate(),  CI->getOperand(0),
00620                         CI->getOperand(1), "", InsertPt);
00621       MadeChange = true;
00622     }
00623 
00624     // Replace a use of the cmp with a use of the new cmp.
00625     TheUse = InsertedCmp;
00626     ++NumCmpUses;
00627   }
00628 
00629   // If we removed all uses, nuke the cmp.
00630   if (CI->use_empty())
00631     CI->eraseFromParent();
00632 
00633   return MadeChange;
00634 }
00635 
00636 /// isExtractBitsCandidateUse - Check if the candidates could
00637 /// be combined with shift instruction, which includes:
00638 /// 1. Truncate instruction
00639 /// 2. And instruction and the imm is a mask of the low bits:
00640 /// imm & (imm+1) == 0
00641 static bool isExtractBitsCandidateUse(Instruction *User) {
00642   if (!isa<TruncInst>(User)) {
00643     if (User->getOpcode() != Instruction::And ||
00644         !isa<ConstantInt>(User->getOperand(1)))
00645       return false;
00646 
00647     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
00648 
00649     if ((Cimm & (Cimm + 1)).getBoolValue())
00650       return false;
00651   }
00652   return true;
00653 }
00654 
00655 /// SinkShiftAndTruncate - sink both shift and truncate instruction
00656 /// to the use of truncate's BB.
00657 static bool
00658 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
00659                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
00660                      const TargetLowering &TLI) {
00661   BasicBlock *UserBB = User->getParent();
00662   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
00663   TruncInst *TruncI = dyn_cast<TruncInst>(User);
00664   bool MadeChange = false;
00665 
00666   for (Value::user_iterator TruncUI = TruncI->user_begin(),
00667                             TruncE = TruncI->user_end();
00668        TruncUI != TruncE;) {
00669 
00670     Use &TruncTheUse = TruncUI.getUse();
00671     Instruction *TruncUser = cast<Instruction>(*TruncUI);
00672     // Preincrement use iterator so we don't invalidate it.
00673 
00674     ++TruncUI;
00675 
00676     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
00677     if (!ISDOpcode)
00678       continue;
00679 
00680     // If the use is actually a legal node, there will not be an
00681     // implicit truncate.
00682     // FIXME: always querying the result type is just an
00683     // approximation; some nodes' legality is determined by the
00684     // operand or other means. There's no good way to find out though.
00685     if (TLI.isOperationLegalOrCustom(ISDOpcode,
00686                                      EVT::getEVT(TruncUser->getType(), true)))
00687       continue;
00688 
00689     // Don't bother for PHI nodes.
00690     if (isa<PHINode>(TruncUser))
00691       continue;
00692 
00693     BasicBlock *TruncUserBB = TruncUser->getParent();
00694 
00695     if (UserBB == TruncUserBB)
00696       continue;
00697 
00698     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
00699     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
00700 
00701     if (!InsertedShift && !InsertedTrunc) {
00702       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
00703       // Sink the shift
00704       if (ShiftI->getOpcode() == Instruction::AShr)
00705         InsertedShift =
00706             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
00707       else
00708         InsertedShift =
00709             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
00710 
00711       // Sink the trunc
00712       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
00713       TruncInsertPt++;
00714 
00715       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
00716                                        TruncI->getType(), "", TruncInsertPt);
00717 
00718       MadeChange = true;
00719 
00720       TruncTheUse = InsertedTrunc;
00721     }
00722   }
00723   return MadeChange;
00724 }
00725 
00726 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
00727 /// the uses could potentially be combined with this shift instruction and
00728 /// generate BitExtract instruction. It will only be applied if the architecture
00729 /// supports BitExtract instruction. Here is an example:
00730 /// BB1:
00731 ///   %x.extract.shift = lshr i64 %arg1, 32
00732 /// BB2:
00733 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
00734 /// ==>
00735 ///
00736 /// BB2:
00737 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
00738 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
00739 ///
00740 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
00741 /// instruction.
00742 /// Return true if any changes are made.
00743 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
00744                                 const TargetLowering &TLI) {
00745   BasicBlock *DefBB = ShiftI->getParent();
00746 
00747   /// Only insert instructions in each block once.
00748   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
00749 
00750   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
00751 
00752   bool MadeChange = false;
00753   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
00754        UI != E;) {
00755     Use &TheUse = UI.getUse();
00756     Instruction *User = cast<Instruction>(*UI);
00757     // Preincrement use iterator so we don't invalidate it.
00758     ++UI;
00759 
00760     // Don't bother for PHI nodes.
00761     if (isa<PHINode>(User))
00762       continue;
00763 
00764     if (!isExtractBitsCandidateUse(User))
00765       continue;
00766 
00767     BasicBlock *UserBB = User->getParent();
00768 
00769     if (UserBB == DefBB) {
00770       // If the shift and truncate instruction are in the same BB. The use of
00771       // the truncate(TruncUse) may still introduce another truncate if not
00772       // legal. In this case, we would like to sink both shift and truncate
00773       // instruction to the BB of TruncUse.
00774       // for example:
00775       // BB1:
00776       // i64 shift.result = lshr i64 opnd, imm
00777       // trunc.result = trunc shift.result to i16
00778       //
00779       // BB2:
00780       //   ----> We will have an implicit truncate here if the architecture does
00781       //   not have i16 compare.
00782       // cmp i16 trunc.result, opnd2
00783       //
00784       if (isa<TruncInst>(User) && shiftIsLegal
00785           // If the type of the truncate is legal, no trucate will be
00786           // introduced in other basic blocks.
00787           && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
00788         MadeChange =
00789             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
00790 
00791       continue;
00792     }
00793     // If we have already inserted a shift into this block, use it.
00794     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
00795 
00796     if (!InsertedShift) {
00797       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
00798 
00799       if (ShiftI->getOpcode() == Instruction::AShr)
00800         InsertedShift =
00801             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
00802       else
00803         InsertedShift =
00804             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
00805 
00806       MadeChange = true;
00807     }
00808 
00809     // Replace a use of the shift with a use of the new shift.
00810     TheUse = InsertedShift;
00811   }
00812 
00813   // If we removed all uses, nuke the shift.
00814   if (ShiftI->use_empty())
00815     ShiftI->eraseFromParent();
00816 
00817   return MadeChange;
00818 }
00819 
00820 namespace {
00821 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
00822 protected:
00823   void replaceCall(Value *With) override {
00824     CI->replaceAllUsesWith(With);
00825     CI->eraseFromParent();
00826   }
00827   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
00828       if (ConstantInt *SizeCI =
00829                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
00830         return SizeCI->isAllOnesValue();
00831     return false;
00832   }
00833 };
00834 } // end anonymous namespace
00835 
00836 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
00837   BasicBlock *BB = CI->getParent();
00838 
00839   // Lower inline assembly if we can.
00840   // If we found an inline asm expession, and if the target knows how to
00841   // lower it to normal LLVM code, do so now.
00842   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
00843     if (TLI->ExpandInlineAsm(CI)) {
00844       // Avoid invalidating the iterator.
00845       CurInstIterator = BB->begin();
00846       // Avoid processing instructions out of order, which could cause
00847       // reuse before a value is defined.
00848       SunkAddrs.clear();
00849       return true;
00850     }
00851     // Sink address computing for memory operands into the block.
00852     if (OptimizeInlineAsmInst(CI))
00853       return true;
00854   }
00855 
00856   // Lower all uses of llvm.objectsize.*
00857   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
00858   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
00859     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
00860     Type *ReturnTy = CI->getType();
00861     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
00862 
00863     // Substituting this can cause recursive simplifications, which can
00864     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
00865     // happens.
00866     WeakVH IterHandle(CurInstIterator);
00867 
00868     replaceAndRecursivelySimplify(CI, RetVal,
00869                                   TLI ? TLI->getDataLayout() : nullptr,
00870                                   TLInfo, ModifiedDT ? nullptr : DT);
00871 
00872     // If the iterator instruction was recursively deleted, start over at the
00873     // start of the block.
00874     if (IterHandle != CurInstIterator) {
00875       CurInstIterator = BB->begin();
00876       SunkAddrs.clear();
00877     }
00878     return true;
00879   }
00880 
00881   if (II && TLI) {
00882     SmallVector<Value*, 2> PtrOps;
00883     Type *AccessTy;
00884     if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
00885       while (!PtrOps.empty())
00886         if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
00887           return true;
00888   }
00889 
00890   // From here on out we're working with named functions.
00891   if (!CI->getCalledFunction()) return false;
00892 
00893   // We'll need DataLayout from here on out.
00894   const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
00895   if (!TD) return false;
00896 
00897   // Lower all default uses of _chk calls.  This is very similar
00898   // to what InstCombineCalls does, but here we are only lowering calls
00899   // that have the default "don't know" as the objectsize.  Anything else
00900   // should be left alone.
00901   CodeGenPrepareFortifiedLibCalls Simplifier;
00902   return Simplifier.fold(CI, TD, TLInfo);
00903 }
00904 
00905 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
00906 /// instructions to the predecessor to enable tail call optimizations. The
00907 /// case it is currently looking for is:
00908 /// @code
00909 /// bb0:
00910 ///   %tmp0 = tail call i32 @f0()
00911 ///   br label %return
00912 /// bb1:
00913 ///   %tmp1 = tail call i32 @f1()
00914 ///   br label %return
00915 /// bb2:
00916 ///   %tmp2 = tail call i32 @f2()
00917 ///   br label %return
00918 /// return:
00919 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
00920 ///   ret i32 %retval
00921 /// @endcode
00922 ///
00923 /// =>
00924 ///
00925 /// @code
00926 /// bb0:
00927 ///   %tmp0 = tail call i32 @f0()
00928 ///   ret i32 %tmp0
00929 /// bb1:
00930 ///   %tmp1 = tail call i32 @f1()
00931 ///   ret i32 %tmp1
00932 /// bb2:
00933 ///   %tmp2 = tail call i32 @f2()
00934 ///   ret i32 %tmp2
00935 /// @endcode
00936 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
00937   if (!TLI)
00938     return false;
00939 
00940   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
00941   if (!RI)
00942     return false;
00943 
00944   PHINode *PN = nullptr;
00945   BitCastInst *BCI = nullptr;
00946   Value *V = RI->getReturnValue();
00947   if (V) {
00948     BCI = dyn_cast<BitCastInst>(V);
00949     if (BCI)
00950       V = BCI->getOperand(0);
00951 
00952     PN = dyn_cast<PHINode>(V);
00953     if (!PN)
00954       return false;
00955   }
00956 
00957   if (PN && PN->getParent() != BB)
00958     return false;
00959 
00960   // It's not safe to eliminate the sign / zero extension of the return value.
00961   // See llvm::isInTailCallPosition().
00962   const Function *F = BB->getParent();
00963   AttributeSet CallerAttrs = F->getAttributes();
00964   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
00965       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
00966     return false;
00967 
00968   // Make sure there are no instructions between the PHI and return, or that the
00969   // return is the first instruction in the block.
00970   if (PN) {
00971     BasicBlock::iterator BI = BB->begin();
00972     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
00973     if (&*BI == BCI)
00974       // Also skip over the bitcast.
00975       ++BI;
00976     if (&*BI != RI)
00977       return false;
00978   } else {
00979     BasicBlock::iterator BI = BB->begin();
00980     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
00981     if (&*BI != RI)
00982       return false;
00983   }
00984 
00985   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
00986   /// call.
00987   SmallVector<CallInst*, 4> TailCalls;
00988   if (PN) {
00989     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
00990       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
00991       // Make sure the phi value is indeed produced by the tail call.
00992       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
00993           TLI->mayBeEmittedAsTailCall(CI))
00994         TailCalls.push_back(CI);
00995     }
00996   } else {
00997     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
00998     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
00999       if (!VisitedBBs.insert(*PI))
01000         continue;
01001 
01002       BasicBlock::InstListType &InstList = (*PI)->getInstList();
01003       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
01004       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
01005       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
01006       if (RI == RE)
01007         continue;
01008 
01009       CallInst *CI = dyn_cast<CallInst>(&*RI);
01010       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
01011         TailCalls.push_back(CI);
01012     }
01013   }
01014 
01015   bool Changed = false;
01016   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
01017     CallInst *CI = TailCalls[i];
01018     CallSite CS(CI);
01019 
01020     // Conservatively require the attributes of the call to match those of the
01021     // return. Ignore noalias because it doesn't affect the call sequence.
01022     AttributeSet CalleeAttrs = CS.getAttributes();
01023     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
01024           removeAttribute(Attribute::NoAlias) !=
01025         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
01026           removeAttribute(Attribute::NoAlias))
01027       continue;
01028 
01029     // Make sure the call instruction is followed by an unconditional branch to
01030     // the return block.
01031     BasicBlock *CallBB = CI->getParent();
01032     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
01033     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
01034       continue;
01035 
01036     // Duplicate the return into CallBB.
01037     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
01038     ModifiedDT = Changed = true;
01039     ++NumRetsDup;
01040   }
01041 
01042   // If we eliminated all predecessors of the block, delete the block now.
01043   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
01044     BB->eraseFromParent();
01045 
01046   return Changed;
01047 }
01048 
01049 //===----------------------------------------------------------------------===//
01050 // Memory Optimization
01051 //===----------------------------------------------------------------------===//
01052 
01053 namespace {
01054 
01055 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
01056 /// which holds actual Value*'s for register values.
01057 struct ExtAddrMode : public TargetLowering::AddrMode {
01058   Value *BaseReg;
01059   Value *ScaledReg;
01060   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
01061   void print(raw_ostream &OS) const;
01062   void dump() const;
01063 
01064   bool operator==(const ExtAddrMode& O) const {
01065     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
01066            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
01067            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
01068   }
01069 };
01070 
01071 #ifndef NDEBUG
01072 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
01073   AM.print(OS);
01074   return OS;
01075 }
01076 #endif
01077 
01078 void ExtAddrMode::print(raw_ostream &OS) const {
01079   bool NeedPlus = false;
01080   OS << "[";
01081   if (BaseGV) {
01082     OS << (NeedPlus ? " + " : "")
01083        << "GV:";
01084     BaseGV->printAsOperand(OS, /*PrintType=*/false);
01085     NeedPlus = true;
01086   }
01087 
01088   if (BaseOffs) {
01089     OS << (NeedPlus ? " + " : "")
01090        << BaseOffs;
01091     NeedPlus = true;
01092   }
01093 
01094   if (BaseReg) {
01095     OS << (NeedPlus ? " + " : "")
01096        << "Base:";
01097     BaseReg->printAsOperand(OS, /*PrintType=*/false);
01098     NeedPlus = true;
01099   }
01100   if (Scale) {
01101     OS << (NeedPlus ? " + " : "")
01102        << Scale << "*";
01103     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
01104   }
01105 
01106   OS << ']';
01107 }
01108 
01109 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01110 void ExtAddrMode::dump() const {
01111   print(dbgs());
01112   dbgs() << '\n';
01113 }
01114 #endif
01115 
01116 /// \brief This class provides transaction based operation on the IR.
01117 /// Every change made through this class is recorded in the internal state and
01118 /// can be undone (rollback) until commit is called.
01119 class TypePromotionTransaction {
01120 
01121   /// \brief This represents the common interface of the individual transaction.
01122   /// Each class implements the logic for doing one specific modification on
01123   /// the IR via the TypePromotionTransaction.
01124   class TypePromotionAction {
01125   protected:
01126     /// The Instruction modified.
01127     Instruction *Inst;
01128 
01129   public:
01130     /// \brief Constructor of the action.
01131     /// The constructor performs the related action on the IR.
01132     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
01133 
01134     virtual ~TypePromotionAction() {}
01135 
01136     /// \brief Undo the modification done by this action.
01137     /// When this method is called, the IR must be in the same state as it was
01138     /// before this action was applied.
01139     /// \pre Undoing the action works if and only if the IR is in the exact same
01140     /// state as it was directly after this action was applied.
01141     virtual void undo() = 0;
01142 
01143     /// \brief Advocate every change made by this action.
01144     /// When the results on the IR of the action are to be kept, it is important
01145     /// to call this function, otherwise hidden information may be kept forever.
01146     virtual void commit() {
01147       // Nothing to be done, this action is not doing anything.
01148     }
01149   };
01150 
01151   /// \brief Utility to remember the position of an instruction.
01152   class InsertionHandler {
01153     /// Position of an instruction.
01154     /// Either an instruction:
01155     /// - Is the first in a basic block: BB is used.
01156     /// - Has a previous instructon: PrevInst is used.
01157     union {
01158       Instruction *PrevInst;
01159       BasicBlock *BB;
01160     } Point;
01161     /// Remember whether or not the instruction had a previous instruction.
01162     bool HasPrevInstruction;
01163 
01164   public:
01165     /// \brief Record the position of \p Inst.
01166     InsertionHandler(Instruction *Inst) {
01167       BasicBlock::iterator It = Inst;
01168       HasPrevInstruction = (It != (Inst->getParent()->begin()));
01169       if (HasPrevInstruction)
01170         Point.PrevInst = --It;
01171       else
01172         Point.BB = Inst->getParent();
01173     }
01174 
01175     /// \brief Insert \p Inst at the recorded position.
01176     void insert(Instruction *Inst) {
01177       if (HasPrevInstruction) {
01178         if (Inst->getParent())
01179           Inst->removeFromParent();
01180         Inst->insertAfter(Point.PrevInst);
01181       } else {
01182         Instruction *Position = Point.BB->getFirstInsertionPt();
01183         if (Inst->getParent())
01184           Inst->moveBefore(Position);
01185         else
01186           Inst->insertBefore(Position);
01187       }
01188     }
01189   };
01190 
01191   /// \brief Move an instruction before another.
01192   class InstructionMoveBefore : public TypePromotionAction {
01193     /// Original position of the instruction.
01194     InsertionHandler Position;
01195 
01196   public:
01197     /// \brief Move \p Inst before \p Before.
01198     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
01199         : TypePromotionAction(Inst), Position(Inst) {
01200       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
01201       Inst->moveBefore(Before);
01202     }
01203 
01204     /// \brief Move the instruction back to its original position.
01205     void undo() override {
01206       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
01207       Position.insert(Inst);
01208     }
01209   };
01210 
01211   /// \brief Set the operand of an instruction with a new value.
01212   class OperandSetter : public TypePromotionAction {
01213     /// Original operand of the instruction.
01214     Value *Origin;
01215     /// Index of the modified instruction.
01216     unsigned Idx;
01217 
01218   public:
01219     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
01220     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
01221         : TypePromotionAction(Inst), Idx(Idx) {
01222       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
01223                    << "for:" << *Inst << "\n"
01224                    << "with:" << *NewVal << "\n");
01225       Origin = Inst->getOperand(Idx);
01226       Inst->setOperand(Idx, NewVal);
01227     }
01228 
01229     /// \brief Restore the original value of the instruction.
01230     void undo() override {
01231       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
01232                    << "for: " << *Inst << "\n"
01233                    << "with: " << *Origin << "\n");
01234       Inst->setOperand(Idx, Origin);
01235     }
01236   };
01237 
01238   /// \brief Hide the operands of an instruction.
01239   /// Do as if this instruction was not using any of its operands.
01240   class OperandsHider : public TypePromotionAction {
01241     /// The list of original operands.
01242     SmallVector<Value *, 4> OriginalValues;
01243 
01244   public:
01245     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
01246     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
01247       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
01248       unsigned NumOpnds = Inst->getNumOperands();
01249       OriginalValues.reserve(NumOpnds);
01250       for (unsigned It = 0; It < NumOpnds; ++It) {
01251         // Save the current operand.
01252         Value *Val = Inst->getOperand(It);
01253         OriginalValues.push_back(Val);
01254         // Set a dummy one.
01255         // We could use OperandSetter here, but that would implied an overhead
01256         // that we are not willing to pay.
01257         Inst->setOperand(It, UndefValue::get(Val->getType()));
01258       }
01259     }
01260 
01261     /// \brief Restore the original list of uses.
01262     void undo() override {
01263       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
01264       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
01265         Inst->setOperand(It, OriginalValues[It]);
01266     }
01267   };
01268 
01269   /// \brief Build a truncate instruction.
01270   class TruncBuilder : public TypePromotionAction {
01271     Value *Val;
01272   public:
01273     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
01274     /// result.
01275     /// trunc Opnd to Ty.
01276     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
01277       IRBuilder<> Builder(Opnd);
01278       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
01279       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
01280     }
01281 
01282     /// \brief Get the built value.
01283     Value *getBuiltValue() { return Val; }
01284 
01285     /// \brief Remove the built instruction.
01286     void undo() override {
01287       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
01288       if (Instruction *IVal = dyn_cast<Instruction>(Val))
01289         IVal->eraseFromParent();
01290     }
01291   };
01292 
01293   /// \brief Build a sign extension instruction.
01294   class SExtBuilder : public TypePromotionAction {
01295     Value *Val;
01296   public:
01297     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
01298     /// result.
01299     /// sext Opnd to Ty.
01300     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
01301         : TypePromotionAction(InsertPt) {
01302       IRBuilder<> Builder(InsertPt);
01303       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
01304       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
01305     }
01306 
01307     /// \brief Get the built value.
01308     Value *getBuiltValue() { return Val; }
01309 
01310     /// \brief Remove the built instruction.
01311     void undo() override {
01312       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
01313       if (Instruction *IVal = dyn_cast<Instruction>(Val))
01314         IVal->eraseFromParent();
01315     }
01316   };
01317 
01318   /// \brief Build a zero extension instruction.
01319   class ZExtBuilder : public TypePromotionAction {
01320     Value *Val;
01321   public:
01322     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
01323     /// result.
01324     /// zext Opnd to Ty.
01325     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
01326         : TypePromotionAction(InsertPt) {
01327       IRBuilder<> Builder(InsertPt);
01328       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
01329       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
01330     }
01331 
01332     /// \brief Get the built value.
01333     Value *getBuiltValue() { return Val; }
01334 
01335     /// \brief Remove the built instruction.
01336     void undo() override {
01337       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
01338       if (Instruction *IVal = dyn_cast<Instruction>(Val))
01339         IVal->eraseFromParent();
01340     }
01341   };
01342 
01343   /// \brief Mutate an instruction to another type.
01344   class TypeMutator : public TypePromotionAction {
01345     /// Record the original type.
01346     Type *OrigTy;
01347 
01348   public:
01349     /// \brief Mutate the type of \p Inst into \p NewTy.
01350     TypeMutator(Instruction *Inst, Type *NewTy)
01351         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
01352       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
01353                    << "\n");
01354       Inst->mutateType(NewTy);
01355     }
01356 
01357     /// \brief Mutate the instruction back to its original type.
01358     void undo() override {
01359       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
01360                    << "\n");
01361       Inst->mutateType(OrigTy);
01362     }
01363   };
01364 
01365   /// \brief Replace the uses of an instruction by another instruction.
01366   class UsesReplacer : public TypePromotionAction {
01367     /// Helper structure to keep track of the replaced uses.
01368     struct InstructionAndIdx {
01369       /// The instruction using the instruction.
01370       Instruction *Inst;
01371       /// The index where this instruction is used for Inst.
01372       unsigned Idx;
01373       InstructionAndIdx(Instruction *Inst, unsigned Idx)
01374           : Inst(Inst), Idx(Idx) {}
01375     };
01376 
01377     /// Keep track of the original uses (pair Instruction, Index).
01378     SmallVector<InstructionAndIdx, 4> OriginalUses;
01379     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
01380 
01381   public:
01382     /// \brief Replace all the use of \p Inst by \p New.
01383     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
01384       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
01385                    << "\n");
01386       // Record the original uses.
01387       for (Use &U : Inst->uses()) {
01388         Instruction *UserI = cast<Instruction>(U.getUser());
01389         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
01390       }
01391       // Now, we can replace the uses.
01392       Inst->replaceAllUsesWith(New);
01393     }
01394 
01395     /// \brief Reassign the original uses of Inst to Inst.
01396     void undo() override {
01397       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
01398       for (use_iterator UseIt = OriginalUses.begin(),
01399                         EndIt = OriginalUses.end();
01400            UseIt != EndIt; ++UseIt) {
01401         UseIt->Inst->setOperand(UseIt->Idx, Inst);
01402       }
01403     }
01404   };
01405 
01406   /// \brief Remove an instruction from the IR.
01407   class InstructionRemover : public TypePromotionAction {
01408     /// Original position of the instruction.
01409     InsertionHandler Inserter;
01410     /// Helper structure to hide all the link to the instruction. In other
01411     /// words, this helps to do as if the instruction was removed.
01412     OperandsHider Hider;
01413     /// Keep track of the uses replaced, if any.
01414     UsesReplacer *Replacer;
01415 
01416   public:
01417     /// \brief Remove all reference of \p Inst and optinally replace all its
01418     /// uses with New.
01419     /// \pre If !Inst->use_empty(), then New != nullptr
01420     InstructionRemover(Instruction *Inst, Value *New = nullptr)
01421         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
01422           Replacer(nullptr) {
01423       if (New)
01424         Replacer = new UsesReplacer(Inst, New);
01425       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
01426       Inst->removeFromParent();
01427     }
01428 
01429     ~InstructionRemover() { delete Replacer; }
01430 
01431     /// \brief Really remove the instruction.
01432     void commit() override { delete Inst; }
01433 
01434     /// \brief Resurrect the instruction and reassign it to the proper uses if
01435     /// new value was provided when build this action.
01436     void undo() override {
01437       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
01438       Inserter.insert(Inst);
01439       if (Replacer)
01440         Replacer->undo();
01441       Hider.undo();
01442     }
01443   };
01444 
01445 public:
01446   /// Restoration point.
01447   /// The restoration point is a pointer to an action instead of an iterator
01448   /// because the iterator may be invalidated but not the pointer.
01449   typedef const TypePromotionAction *ConstRestorationPt;
01450   /// Advocate every changes made in that transaction.
01451   void commit();
01452   /// Undo all the changes made after the given point.
01453   void rollback(ConstRestorationPt Point);
01454   /// Get the current restoration point.
01455   ConstRestorationPt getRestorationPoint() const;
01456 
01457   /// \name API for IR modification with state keeping to support rollback.
01458   /// @{
01459   /// Same as Instruction::setOperand.
01460   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
01461   /// Same as Instruction::eraseFromParent.
01462   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
01463   /// Same as Value::replaceAllUsesWith.
01464   void replaceAllUsesWith(Instruction *Inst, Value *New);
01465   /// Same as Value::mutateType.
01466   void mutateType(Instruction *Inst, Type *NewTy);
01467   /// Same as IRBuilder::createTrunc.
01468   Value *createTrunc(Instruction *Opnd, Type *Ty);
01469   /// Same as IRBuilder::createSExt.
01470   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
01471   /// Same as IRBuilder::createZExt.
01472   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
01473   /// Same as Instruction::moveBefore.
01474   void moveBefore(Instruction *Inst, Instruction *Before);
01475   /// @}
01476 
01477 private:
01478   /// The ordered list of actions made so far.
01479   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
01480   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
01481 };
01482 
01483 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
01484                                           Value *NewVal) {
01485   Actions.push_back(
01486       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
01487 }
01488 
01489 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
01490                                                 Value *NewVal) {
01491   Actions.push_back(
01492       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
01493 }
01494 
01495 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
01496                                                   Value *New) {
01497   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
01498 }
01499 
01500 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
01501   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
01502 }
01503 
01504 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
01505                                              Type *Ty) {
01506   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
01507   Value *Val = Ptr->getBuiltValue();
01508   Actions.push_back(std::move(Ptr));
01509   return Val;
01510 }
01511 
01512 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
01513                                             Value *Opnd, Type *Ty) {
01514   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
01515   Value *Val = Ptr->getBuiltValue();
01516   Actions.push_back(std::move(Ptr));
01517   return Val;
01518 }
01519 
01520 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
01521                                             Value *Opnd, Type *Ty) {
01522   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
01523   Value *Val = Ptr->getBuiltValue();
01524   Actions.push_back(std::move(Ptr));
01525   return Val;
01526 }
01527 
01528 void TypePromotionTransaction::moveBefore(Instruction *Inst,
01529                                           Instruction *Before) {
01530   Actions.push_back(
01531       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
01532 }
01533 
01534 TypePromotionTransaction::ConstRestorationPt
01535 TypePromotionTransaction::getRestorationPoint() const {
01536   return !Actions.empty() ? Actions.back().get() : nullptr;
01537 }
01538 
01539 void TypePromotionTransaction::commit() {
01540   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
01541        ++It)
01542     (*It)->commit();
01543   Actions.clear();
01544 }
01545 
01546 void TypePromotionTransaction::rollback(
01547     TypePromotionTransaction::ConstRestorationPt Point) {
01548   while (!Actions.empty() && Point != Actions.back().get()) {
01549     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
01550     Curr->undo();
01551   }
01552 }
01553 
01554 /// \brief A helper class for matching addressing modes.
01555 ///
01556 /// This encapsulates the logic for matching the target-legal addressing modes.
01557 class AddressingModeMatcher {
01558   SmallVectorImpl<Instruction*> &AddrModeInsts;
01559   const TargetLowering &TLI;
01560 
01561   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
01562   /// the memory instruction that we're computing this address for.
01563   Type *AccessTy;
01564   Instruction *MemoryInst;
01565 
01566   /// AddrMode - This is the addressing mode that we're building up.  This is
01567   /// part of the return value of this addressing mode matching stuff.
01568   ExtAddrMode &AddrMode;
01569 
01570   /// The truncate instruction inserted by other CodeGenPrepare optimizations.
01571   const SetOfInstrs &InsertedTruncs;
01572   /// A map from the instructions to their type before promotion.
01573   InstrToOrigTy &PromotedInsts;
01574   /// The ongoing transaction where every action should be registered.
01575   TypePromotionTransaction &TPT;
01576 
01577   /// IgnoreProfitability - This is set to true when we should not do
01578   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
01579   /// always returns true.
01580   bool IgnoreProfitability;
01581 
01582   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
01583                         const TargetLowering &T, Type *AT,
01584                         Instruction *MI, ExtAddrMode &AM,
01585                         const SetOfInstrs &InsertedTruncs,
01586                         InstrToOrigTy &PromotedInsts,
01587                         TypePromotionTransaction &TPT)
01588       : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
01589         InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
01590     IgnoreProfitability = false;
01591   }
01592 public:
01593 
01594   /// Match - Find the maximal addressing mode that a load/store of V can fold,
01595   /// give an access type of AccessTy.  This returns a list of involved
01596   /// instructions in AddrModeInsts.
01597   /// \p InsertedTruncs The truncate instruction inserted by other
01598   /// CodeGenPrepare
01599   /// optimizations.
01600   /// \p PromotedInsts maps the instructions to their type before promotion.
01601   /// \p The ongoing transaction where every action should be registered.
01602   static ExtAddrMode Match(Value *V, Type *AccessTy,
01603                            Instruction *MemoryInst,
01604                            SmallVectorImpl<Instruction*> &AddrModeInsts,
01605                            const TargetLowering &TLI,
01606                            const SetOfInstrs &InsertedTruncs,
01607                            InstrToOrigTy &PromotedInsts,
01608                            TypePromotionTransaction &TPT) {
01609     ExtAddrMode Result;
01610 
01611     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
01612                                          MemoryInst, Result, InsertedTruncs,
01613                                          PromotedInsts, TPT).MatchAddr(V, 0);
01614     (void)Success; assert(Success && "Couldn't select *anything*?");
01615     return Result;
01616   }
01617 private:
01618   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
01619   bool MatchAddr(Value *V, unsigned Depth);
01620   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
01621                           bool *MovedAway = nullptr);
01622   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
01623                                             ExtAddrMode &AMBefore,
01624                                             ExtAddrMode &AMAfter);
01625   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
01626   bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
01627                              Value *PromotedOperand) const;
01628 };
01629 
01630 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
01631 /// Return true and update AddrMode if this addr mode is legal for the target,
01632 /// false if not.
01633 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
01634                                              unsigned Depth) {
01635   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
01636   // mode.  Just process that directly.
01637   if (Scale == 1)
01638     return MatchAddr(ScaleReg, Depth);
01639 
01640   // If the scale is 0, it takes nothing to add this.
01641   if (Scale == 0)
01642     return true;
01643 
01644   // If we already have a scale of this value, we can add to it, otherwise, we
01645   // need an available scale field.
01646   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
01647     return false;
01648 
01649   ExtAddrMode TestAddrMode = AddrMode;
01650 
01651   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
01652   // [A+B + A*7] -> [B+A*8].
01653   TestAddrMode.Scale += Scale;
01654   TestAddrMode.ScaledReg = ScaleReg;
01655 
01656   // If the new address isn't legal, bail out.
01657   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
01658     return false;
01659 
01660   // It was legal, so commit it.
01661   AddrMode = TestAddrMode;
01662 
01663   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
01664   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
01665   // X*Scale + C*Scale to addr mode.
01666   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
01667   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
01668       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
01669     TestAddrMode.ScaledReg = AddLHS;
01670     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
01671 
01672     // If this addressing mode is legal, commit it and remember that we folded
01673     // this instruction.
01674     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
01675       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
01676       AddrMode = TestAddrMode;
01677       return true;
01678     }
01679   }
01680 
01681   // Otherwise, not (x+c)*scale, just return what we have.
01682   return true;
01683 }
01684 
01685 /// MightBeFoldableInst - This is a little filter, which returns true if an
01686 /// addressing computation involving I might be folded into a load/store
01687 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
01688 /// the set of instructions that MatchOperationAddr can.
01689 static bool MightBeFoldableInst(Instruction *I) {
01690   switch (I->getOpcode()) {
01691   case Instruction::BitCast:
01692   case Instruction::AddrSpaceCast:
01693     // Don't touch identity bitcasts.
01694     if (I->getType() == I->getOperand(0)->getType())
01695       return false;
01696     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
01697   case Instruction::PtrToInt:
01698     // PtrToInt is always a noop, as we know that the int type is pointer sized.
01699     return true;
01700   case Instruction::IntToPtr:
01701     // We know the input is intptr_t, so this is foldable.
01702     return true;
01703   case Instruction::Add:
01704     return true;
01705   case Instruction::Mul:
01706   case Instruction::Shl:
01707     // Can only handle X*C and X << C.
01708     return isa<ConstantInt>(I->getOperand(1));
01709   case Instruction::GetElementPtr:
01710     return true;
01711   default:
01712     return false;
01713   }
01714 }
01715 
01716 /// \brief Hepler class to perform type promotion.
01717 class TypePromotionHelper {
01718   /// \brief Utility function to check whether or not a sign extension of
01719   /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
01720   /// using the operands of \p Inst or promoting \p Inst.
01721   /// In other words, check if:
01722   /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
01723   /// #1 Promotion applies:
01724   /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
01725   /// #2 Operand reuses:
01726   /// sext opnd1 to ConsideredSExtType.
01727   /// \p PromotedInsts maps the instructions to their type before promotion.
01728   static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
01729                             const InstrToOrigTy &PromotedInsts);
01730 
01731   /// \brief Utility function to determine if \p OpIdx should be promoted when
01732   /// promoting \p Inst.
01733   static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
01734     if (isa<SelectInst>(Inst) && OpIdx == 0)
01735       return false;
01736     return true;
01737   }
01738 
01739   /// \brief Utility function to promote the operand of \p SExt when this
01740   /// operand is a promotable trunc or sext or zext.
01741   /// \p PromotedInsts maps the instructions to their type before promotion.
01742   /// \p CreatedInsts[out] contains how many non-free instructions have been
01743   /// created to promote the operand of SExt.
01744   /// Should never be called directly.
01745   /// \return The promoted value which is used instead of SExt.
01746   static Value *promoteOperandForTruncAndAnyExt(Instruction *SExt,
01747                                                 TypePromotionTransaction &TPT,
01748                                                 InstrToOrigTy &PromotedInsts,
01749                                                 unsigned &CreatedInsts);
01750 
01751   /// \brief Utility function to promote the operand of \p SExt when this
01752   /// operand is promotable and is not a supported trunc or sext.
01753   /// \p PromotedInsts maps the instructions to their type before promotion.
01754   /// \p CreatedInsts[out] contains how many non-free instructions have been
01755   /// created to promote the operand of SExt.
01756   /// Should never be called directly.
01757   /// \return The promoted value which is used instead of SExt.
01758   static Value *promoteOperandForOther(Instruction *SExt,
01759                                        TypePromotionTransaction &TPT,
01760                                        InstrToOrigTy &PromotedInsts,
01761                                        unsigned &CreatedInsts);
01762 
01763 public:
01764   /// Type for the utility function that promotes the operand of SExt.
01765   typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
01766                            InstrToOrigTy &PromotedInsts,
01767                            unsigned &CreatedInsts);
01768   /// \brief Given a sign extend instruction \p SExt, return the approriate
01769   /// action to promote the operand of \p SExt instead of using SExt.
01770   /// \return NULL if no promotable action is possible with the current
01771   /// sign extension.
01772   /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
01773   /// the others CodeGenPrepare optimizations. This information is important
01774   /// because we do not want to promote these instructions as CodeGenPrepare
01775   /// will reinsert them later. Thus creating an infinite loop: create/remove.
01776   /// \p PromotedInsts maps the instructions to their type before promotion.
01777   static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
01778                           const TargetLowering &TLI,
01779                           const InstrToOrigTy &PromotedInsts);
01780 };
01781 
01782 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
01783                                         Type *ConsideredSExtType,
01784                                         const InstrToOrigTy &PromotedInsts) {
01785   // We can always get through sext or zext.
01786   if (isa<SExtInst>(Inst) || isa<ZExtInst>(Inst))
01787     return true;
01788 
01789   // We can get through binary operator, if it is legal. In other words, the
01790   // binary operator must have a nuw or nsw flag.
01791   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
01792   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
01793       (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
01794     return true;
01795 
01796   // Check if we can do the following simplification.
01797   // sext(trunc(sext)) --> sext
01798   if (!isa<TruncInst>(Inst))
01799     return false;
01800 
01801   Value *OpndVal = Inst->getOperand(0);
01802   // Check if we can use this operand in the sext.
01803   // If the type is larger than the result type of the sign extension,
01804   // we cannot.
01805   if (OpndVal->getType()->getIntegerBitWidth() >
01806       ConsideredSExtType->getIntegerBitWidth())
01807     return false;
01808 
01809   // If the operand of the truncate is not an instruction, we will not have
01810   // any information on the dropped bits.
01811   // (Actually we could for constant but it is not worth the extra logic).
01812   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
01813   if (!Opnd)
01814     return false;
01815 
01816   // Check if the source of the type is narrow enough.
01817   // I.e., check that trunc just drops sign extended bits.
01818   // #1 get the type of the operand.
01819   const Type *OpndType;
01820   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
01821   if (It != PromotedInsts.end())
01822     OpndType = It->second;
01823   else if (isa<SExtInst>(Opnd))
01824     OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
01825   else
01826     return false;
01827 
01828   // #2 check that the truncate just drop sign extended bits.
01829   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
01830     return true;
01831 
01832   return false;
01833 }
01834 
01835 TypePromotionHelper::Action TypePromotionHelper::getAction(
01836     Instruction *SExt, const SetOfInstrs &InsertedTruncs,
01837     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
01838   Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
01839   Type *SExtTy = SExt->getType();
01840   // If the operand of the sign extension is not an instruction, we cannot
01841   // get through.
01842   // If it, check we can get through.
01843   if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
01844     return nullptr;
01845 
01846   // Do not promote if the operand has been added by codegenprepare.
01847   // Otherwise, it means we are undoing an optimization that is likely to be
01848   // redone, thus causing potential infinite loop.
01849   if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
01850     return nullptr;
01851 
01852   // SExt or Trunc instructions.
01853   // Return the related handler.
01854   if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd) ||
01855       isa<ZExtInst>(SExtOpnd))
01856     return promoteOperandForTruncAndAnyExt;
01857 
01858   // Regular instruction.
01859   // Abort early if we will have to insert non-free instructions.
01860   if (!SExtOpnd->hasOneUse() &&
01861       !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
01862     return nullptr;
01863   return promoteOperandForOther;
01864 }
01865 
01866 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
01867     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
01868     InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
01869   // By construction, the operand of SExt is an instruction. Otherwise we cannot
01870   // get through it and this method should not be called.
01871   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
01872   Value *ExtVal = SExt;
01873   if (isa<ZExtInst>(SExtOpnd)) {
01874     // Replace sext(zext(opnd))
01875     // => zext(opnd).
01876     Value *ZExt =
01877         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
01878     TPT.replaceAllUsesWith(SExt, ZExt);
01879     TPT.eraseInstruction(SExt);
01880     ExtVal = ZExt;
01881   } else {
01882     // Replace sext(trunc(opnd)) or sext(sext(opnd))
01883     // => sext(opnd).
01884     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
01885   }
01886   CreatedInsts = 0;
01887 
01888   // Remove dead code.
01889   if (SExtOpnd->use_empty())
01890     TPT.eraseInstruction(SExtOpnd);
01891 
01892   // Check if the extension is still needed.
01893   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
01894   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
01895     return ExtVal;
01896 
01897   // At this point we have: ext ty opnd to ty.
01898   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
01899   Value *NextVal = ExtInst->getOperand(0);
01900   TPT.eraseInstruction(ExtInst, NextVal);
01901   return NextVal;
01902 }
01903 
01904 Value *
01905 TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
01906                                             TypePromotionTransaction &TPT,
01907                                             InstrToOrigTy &PromotedInsts,
01908                                             unsigned &CreatedInsts) {
01909   // By construction, the operand of SExt is an instruction. Otherwise we cannot
01910   // get through it and this method should not be called.
01911   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
01912   CreatedInsts = 0;
01913   if (!SExtOpnd->hasOneUse()) {
01914     // SExtOpnd will be promoted.
01915     // All its uses, but SExt, will need to use a truncated value of the
01916     // promoted version.
01917     // Create the truncate now.
01918     Value *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
01919     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
01920       ITrunc->removeFromParent();
01921       // Insert it just after the definition.
01922       ITrunc->insertAfter(SExtOpnd);
01923     }
01924 
01925     TPT.replaceAllUsesWith(SExtOpnd, Trunc);
01926     // Restore the operand of SExt (which has been replace by the previous call
01927     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
01928     TPT.setOperand(SExt, 0, SExtOpnd);
01929   }
01930 
01931   // Get through the Instruction:
01932   // 1. Update its type.
01933   // 2. Replace the uses of SExt by Inst.
01934   // 3. Sign extend each operand that needs to be sign extended.
01935 
01936   // Remember the original type of the instruction before promotion.
01937   // This is useful to know that the high bits are sign extended bits.
01938   PromotedInsts.insert(
01939       std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
01940   // Step #1.
01941   TPT.mutateType(SExtOpnd, SExt->getType());
01942   // Step #2.
01943   TPT.replaceAllUsesWith(SExt, SExtOpnd);
01944   // Step #3.
01945   Instruction *SExtForOpnd = SExt;
01946 
01947   DEBUG(dbgs() << "Propagate SExt to operands\n");
01948   for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
01949        ++OpIdx) {
01950     DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
01951     if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
01952         !shouldSExtOperand(SExtOpnd, OpIdx)) {
01953       DEBUG(dbgs() << "No need to propagate\n");
01954       continue;
01955     }
01956     // Check if we can statically sign extend the operand.
01957     Value *Opnd = SExtOpnd->getOperand(OpIdx);
01958     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
01959       DEBUG(dbgs() << "Statically sign extend\n");
01960       TPT.setOperand(
01961           SExtOpnd, OpIdx,
01962           ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
01963       continue;
01964     }
01965     // UndefValue are typed, so we have to statically sign extend them.
01966     if (isa<UndefValue>(Opnd)) {
01967       DEBUG(dbgs() << "Statically sign extend\n");
01968       TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
01969       continue;
01970     }
01971 
01972     // Otherwise we have to explicity sign extend the operand.
01973     // Check if SExt was reused to sign extend an operand.
01974     if (!SExtForOpnd) {
01975       // If yes, create a new one.
01976       DEBUG(dbgs() << "More operands to sext\n");
01977       SExtForOpnd =
01978         cast<Instruction>(TPT.createSExt(SExt, Opnd, SExt->getType()));
01979       ++CreatedInsts;
01980     }
01981 
01982     TPT.setOperand(SExtForOpnd, 0, Opnd);
01983 
01984     // Move the sign extension before the insertion point.
01985     TPT.moveBefore(SExtForOpnd, SExtOpnd);
01986     TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
01987     // If more sext are required, new instructions will have to be created.
01988     SExtForOpnd = nullptr;
01989   }
01990   if (SExtForOpnd == SExt) {
01991     DEBUG(dbgs() << "Sign extension is useless now\n");
01992     TPT.eraseInstruction(SExt);
01993   }
01994   return SExtOpnd;
01995 }
01996 
01997 /// IsPromotionProfitable - Check whether or not promoting an instruction
01998 /// to a wider type was profitable.
01999 /// \p MatchedSize gives the number of instructions that have been matched
02000 /// in the addressing mode after the promotion was applied.
02001 /// \p SizeWithPromotion gives the number of created instructions for
02002 /// the promotion plus the number of instructions that have been
02003 /// matched in the addressing mode before the promotion.
02004 /// \p PromotedOperand is the value that has been promoted.
02005 /// \return True if the promotion is profitable, false otherwise.
02006 bool
02007 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
02008                                              unsigned SizeWithPromotion,
02009                                              Value *PromotedOperand) const {
02010   // We folded less instructions than what we created to promote the operand.
02011   // This is not profitable.
02012   if (MatchedSize < SizeWithPromotion)
02013     return false;
02014   if (MatchedSize > SizeWithPromotion)
02015     return true;
02016   // The promotion is neutral but it may help folding the sign extension in
02017   // loads for instance.
02018   // Check that we did not create an illegal instruction.
02019   Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
02020   if (!PromotedInst)
02021     return false;
02022   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
02023   // If the ISDOpcode is undefined, it was undefined before the promotion.
02024   if (!ISDOpcode)
02025     return true;
02026   // Otherwise, check if the promoted instruction is legal or not.
02027   return TLI.isOperationLegalOrCustom(ISDOpcode,
02028                                       EVT::getEVT(PromotedInst->getType()));
02029 }
02030 
02031 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
02032 /// fold the operation into the addressing mode.  If so, update the addressing
02033 /// mode and return true, otherwise return false without modifying AddrMode.
02034 /// If \p MovedAway is not NULL, it contains the information of whether or
02035 /// not AddrInst has to be folded into the addressing mode on success.
02036 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
02037 /// because it has been moved away.
02038 /// Thus AddrInst must not be added in the matched instructions.
02039 /// This state can happen when AddrInst is a sext, since it may be moved away.
02040 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
02041 /// not be referenced anymore.
02042 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
02043                                                unsigned Depth,
02044                                                bool *MovedAway) {
02045   // Avoid exponential behavior on extremely deep expression trees.
02046   if (Depth >= 5) return false;
02047 
02048   // By default, all matched instructions stay in place.
02049   if (MovedAway)
02050     *MovedAway = false;
02051 
02052   switch (Opcode) {
02053   case Instruction::PtrToInt:
02054     // PtrToInt is always a noop, as we know that the int type is pointer sized.
02055     return MatchAddr(AddrInst->getOperand(0), Depth);
02056   case Instruction::IntToPtr:
02057     // This inttoptr is a no-op if the integer type is pointer sized.
02058     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
02059         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
02060       return MatchAddr(AddrInst->getOperand(0), Depth);
02061     return false;
02062   case Instruction::BitCast:
02063   case Instruction::AddrSpaceCast:
02064     // BitCast is always a noop, and we can handle it as long as it is
02065     // int->int or pointer->pointer (we don't want int<->fp or something).
02066     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
02067          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
02068         // Don't touch identity bitcasts.  These were probably put here by LSR,
02069         // and we don't want to mess around with them.  Assume it knows what it
02070         // is doing.
02071         AddrInst->getOperand(0)->getType() != AddrInst->getType())
02072       return MatchAddr(AddrInst->getOperand(0), Depth);
02073     return false;
02074   case Instruction::Add: {
02075     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
02076     ExtAddrMode BackupAddrMode = AddrMode;
02077     unsigned OldSize = AddrModeInsts.size();
02078     // Start a transaction at this point.
02079     // The LHS may match but not the RHS.
02080     // Therefore, we need a higher level restoration point to undo partially
02081     // matched operation.
02082     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02083         TPT.getRestorationPoint();
02084 
02085     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
02086         MatchAddr(AddrInst->getOperand(0), Depth+1))
02087       return true;
02088 
02089     // Restore the old addr mode info.
02090     AddrMode = BackupAddrMode;
02091     AddrModeInsts.resize(OldSize);
02092     TPT.rollback(LastKnownGood);
02093 
02094     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
02095     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
02096         MatchAddr(AddrInst->getOperand(1), Depth+1))
02097       return true;
02098 
02099     // Otherwise we definitely can't merge the ADD in.
02100     AddrMode = BackupAddrMode;
02101     AddrModeInsts.resize(OldSize);
02102     TPT.rollback(LastKnownGood);
02103     break;
02104   }
02105   //case Instruction::Or:
02106   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
02107   //break;
02108   case Instruction::Mul:
02109   case Instruction::Shl: {
02110     // Can only handle X*C and X << C.
02111     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
02112     if (!RHS)
02113       return false;
02114     int64_t Scale = RHS->getSExtValue();
02115     if (Opcode == Instruction::Shl)
02116       Scale = 1LL << Scale;
02117 
02118     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
02119   }
02120   case Instruction::GetElementPtr: {
02121     // Scan the GEP.  We check it if it contains constant offsets and at most
02122     // one variable offset.
02123     int VariableOperand = -1;
02124     unsigned VariableScale = 0;
02125 
02126     int64_t ConstantOffset = 0;
02127     const DataLayout *TD = TLI.getDataLayout();
02128     gep_type_iterator GTI = gep_type_begin(AddrInst);
02129     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
02130       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
02131         const StructLayout *SL = TD->getStructLayout(STy);
02132         unsigned Idx =
02133           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
02134         ConstantOffset += SL->getElementOffset(Idx);
02135       } else {
02136         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
02137         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
02138           ConstantOffset += CI->getSExtValue()*TypeSize;
02139         } else if (TypeSize) {  // Scales of zero don't do anything.
02140           // We only allow one variable index at the moment.
02141           if (VariableOperand != -1)
02142             return false;
02143 
02144           // Remember the variable index.
02145           VariableOperand = i;
02146           VariableScale = TypeSize;
02147         }
02148       }
02149     }
02150 
02151     // A common case is for the GEP to only do a constant offset.  In this case,
02152     // just add it to the disp field and check validity.
02153     if (VariableOperand == -1) {
02154       AddrMode.BaseOffs += ConstantOffset;
02155       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
02156         // Check to see if we can fold the base pointer in too.
02157         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
02158           return true;
02159       }
02160       AddrMode.BaseOffs -= ConstantOffset;
02161       return false;
02162     }
02163 
02164     // Save the valid addressing mode in case we can't match.
02165     ExtAddrMode BackupAddrMode = AddrMode;
02166     unsigned OldSize = AddrModeInsts.size();
02167 
02168     // See if the scale and offset amount is valid for this target.
02169     AddrMode.BaseOffs += ConstantOffset;
02170 
02171     // Match the base operand of the GEP.
02172     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
02173       // If it couldn't be matched, just stuff the value in a register.
02174       if (AddrMode.HasBaseReg) {
02175         AddrMode = BackupAddrMode;
02176         AddrModeInsts.resize(OldSize);
02177         return false;
02178       }
02179       AddrMode.HasBaseReg = true;
02180       AddrMode.BaseReg = AddrInst->getOperand(0);
02181     }
02182 
02183     // Match the remaining variable portion of the GEP.
02184     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
02185                           Depth)) {
02186       // If it couldn't be matched, try stuffing the base into a register
02187       // instead of matching it, and retrying the match of the scale.
02188       AddrMode = BackupAddrMode;
02189       AddrModeInsts.resize(OldSize);
02190       if (AddrMode.HasBaseReg)
02191         return false;
02192       AddrMode.HasBaseReg = true;
02193       AddrMode.BaseReg = AddrInst->getOperand(0);
02194       AddrMode.BaseOffs += ConstantOffset;
02195       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
02196                             VariableScale, Depth)) {
02197         // If even that didn't work, bail.
02198         AddrMode = BackupAddrMode;
02199         AddrModeInsts.resize(OldSize);
02200         return false;
02201       }
02202     }
02203 
02204     return true;
02205   }
02206   case Instruction::SExt: {
02207     Instruction *SExt = dyn_cast<Instruction>(AddrInst);
02208     if (!SExt)
02209       return false;
02210 
02211     // Try to move this sext out of the way of the addressing mode.
02212     // Ask for a method for doing so.
02213     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
02214         SExt, InsertedTruncs, TLI, PromotedInsts);
02215     if (!TPH)
02216       return false;
02217 
02218     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02219         TPT.getRestorationPoint();
02220     unsigned CreatedInsts = 0;
02221     Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
02222     // SExt has been moved away.
02223     // Thus either it will be rematched later in the recursive calls or it is
02224     // gone. Anyway, we must not fold it into the addressing mode at this point.
02225     // E.g.,
02226     // op = add opnd, 1
02227     // idx = sext op
02228     // addr = gep base, idx
02229     // is now:
02230     // promotedOpnd = sext opnd           <- no match here
02231     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
02232     // addr = gep base, op                <- match
02233     if (MovedAway)
02234       *MovedAway = true;
02235 
02236     assert(PromotedOperand &&
02237            "TypePromotionHelper should have filtered out those cases");
02238 
02239     ExtAddrMode BackupAddrMode = AddrMode;
02240     unsigned OldSize = AddrModeInsts.size();
02241 
02242     if (!MatchAddr(PromotedOperand, Depth) ||
02243         !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
02244                                PromotedOperand)) {
02245       AddrMode = BackupAddrMode;
02246       AddrModeInsts.resize(OldSize);
02247       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
02248       TPT.rollback(LastKnownGood);
02249       return false;
02250     }
02251     return true;
02252   }
02253   }
02254   return false;
02255 }
02256 
02257 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
02258 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
02259 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
02260 /// or intptr_t for the target.
02261 ///
02262 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
02263   // Start a transaction at this point that we will rollback if the matching
02264   // fails.
02265   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02266       TPT.getRestorationPoint();
02267   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
02268     // Fold in immediates if legal for the target.
02269     AddrMode.BaseOffs += CI->getSExtValue();
02270     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
02271       return true;
02272     AddrMode.BaseOffs -= CI->getSExtValue();
02273   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
02274     // If this is a global variable, try to fold it into the addressing mode.
02275     if (!AddrMode.BaseGV) {
02276       AddrMode.BaseGV = GV;
02277       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
02278         return true;
02279       AddrMode.BaseGV = nullptr;
02280     }
02281   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
02282     ExtAddrMode BackupAddrMode = AddrMode;
02283     unsigned OldSize = AddrModeInsts.size();
02284 
02285     // Check to see if it is possible to fold this operation.
02286     bool MovedAway = false;
02287     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
02288       // This instruction may have been move away. If so, there is nothing
02289       // to check here.
02290       if (MovedAway)
02291         return true;
02292       // Okay, it's possible to fold this.  Check to see if it is actually
02293       // *profitable* to do so.  We use a simple cost model to avoid increasing
02294       // register pressure too much.
02295       if (I->hasOneUse() ||
02296           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
02297         AddrModeInsts.push_back(I);
02298         return true;
02299       }
02300 
02301       // It isn't profitable to do this, roll back.
02302       //cerr << "NOT FOLDING: " << *I;
02303       AddrMode = BackupAddrMode;
02304       AddrModeInsts.resize(OldSize);
02305       TPT.rollback(LastKnownGood);
02306     }
02307   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
02308     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
02309       return true;
02310     TPT.rollback(LastKnownGood);
02311   } else if (isa<ConstantPointerNull>(Addr)) {
02312     // Null pointer gets folded without affecting the addressing mode.
02313     return true;
02314   }
02315 
02316   // Worse case, the target should support [reg] addressing modes. :)
02317   if (!AddrMode.HasBaseReg) {
02318     AddrMode.HasBaseReg = true;
02319     AddrMode.BaseReg = Addr;
02320     // Still check for legality in case the target supports [imm] but not [i+r].
02321     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
02322       return true;
02323     AddrMode.HasBaseReg = false;
02324     AddrMode.BaseReg = nullptr;
02325   }
02326 
02327   // If the base register is already taken, see if we can do [r+r].
02328   if (AddrMode.Scale == 0) {
02329     AddrMode.Scale = 1;
02330     AddrMode.ScaledReg = Addr;
02331     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
02332       return true;
02333     AddrMode.Scale = 0;
02334     AddrMode.ScaledReg = nullptr;
02335   }
02336   // Couldn't match.
02337   TPT.rollback(LastKnownGood);
02338   return false;
02339 }
02340 
02341 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
02342 /// inline asm call are due to memory operands.  If so, return true, otherwise
02343 /// return false.
02344 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
02345                                     const TargetLowering &TLI) {
02346   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
02347   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
02348     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
02349 
02350     // Compute the constraint code and ConstraintType to use.
02351     TLI.ComputeConstraintToUse(OpInfo, SDValue());
02352 
02353     // If this asm operand is our Value*, and if it isn't an indirect memory
02354     // operand, we can't fold it!
02355     if (OpInfo.CallOperandVal == OpVal &&
02356         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
02357          !OpInfo.isIndirect))
02358       return false;
02359   }
02360 
02361   return true;
02362 }
02363 
02364 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
02365 /// memory use.  If we find an obviously non-foldable instruction, return true.
02366 /// Add the ultimately found memory instructions to MemoryUses.
02367 static bool FindAllMemoryUses(Instruction *I,
02368                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
02369                               SmallPtrSetImpl<Instruction*> &ConsideredInsts,
02370                               const TargetLowering &TLI) {
02371   // If we already considered this instruction, we're done.
02372   if (!ConsideredInsts.insert(I))
02373     return false;
02374 
02375   // If this is an obviously unfoldable instruction, bail out.
02376   if (!MightBeFoldableInst(I))
02377     return true;
02378 
02379   // Loop over all the uses, recursively processing them.
02380   for (Use &U : I->uses()) {
02381     Instruction *UserI = cast<Instruction>(U.getUser());
02382 
02383     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
02384       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
02385       continue;
02386     }
02387 
02388     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
02389       unsigned opNo = U.getOperandNo();
02390       if (opNo == 0) return true; // Storing addr, not into addr.
02391       MemoryUses.push_back(std::make_pair(SI, opNo));
02392       continue;
02393     }
02394 
02395     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
02396       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
02397       if (!IA) return true;
02398 
02399       // If this is a memory operand, we're cool, otherwise bail out.
02400       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
02401         return true;
02402       continue;
02403     }
02404 
02405     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
02406       return true;
02407   }
02408 
02409   return false;
02410 }
02411 
02412 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
02413 /// the use site that we're folding it into.  If so, there is no cost to
02414 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
02415 /// that we know are live at the instruction already.
02416 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
02417                                                    Value *KnownLive2) {
02418   // If Val is either of the known-live values, we know it is live!
02419   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
02420     return true;
02421 
02422   // All values other than instructions and arguments (e.g. constants) are live.
02423   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
02424 
02425   // If Val is a constant sized alloca in the entry block, it is live, this is
02426   // true because it is just a reference to the stack/frame pointer, which is
02427   // live for the whole function.
02428   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
02429     if (AI->isStaticAlloca())
02430       return true;
02431 
02432   // Check to see if this value is already used in the memory instruction's
02433   // block.  If so, it's already live into the block at the very least, so we
02434   // can reasonably fold it.
02435   return Val->isUsedInBasicBlock(MemoryInst->getParent());
02436 }
02437 
02438 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
02439 /// mode of the machine to fold the specified instruction into a load or store
02440 /// that ultimately uses it.  However, the specified instruction has multiple
02441 /// uses.  Given this, it may actually increase register pressure to fold it
02442 /// into the load.  For example, consider this code:
02443 ///
02444 ///     X = ...
02445 ///     Y = X+1
02446 ///     use(Y)   -> nonload/store
02447 ///     Z = Y+1
02448 ///     load Z
02449 ///
02450 /// In this case, Y has multiple uses, and can be folded into the load of Z
02451 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
02452 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
02453 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
02454 /// number of computations either.
02455 ///
02456 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
02457 /// X was live across 'load Z' for other reasons, we actually *would* want to
02458 /// fold the addressing mode in the Z case.  This would make Y die earlier.
02459 bool AddressingModeMatcher::
02460 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
02461                                      ExtAddrMode &AMAfter) {
02462   if (IgnoreProfitability) return true;
02463 
02464   // AMBefore is the addressing mode before this instruction was folded into it,
02465   // and AMAfter is the addressing mode after the instruction was folded.  Get
02466   // the set of registers referenced by AMAfter and subtract out those
02467   // referenced by AMBefore: this is the set of values which folding in this
02468   // address extends the lifetime of.
02469   //
02470   // Note that there are only two potential values being referenced here,
02471   // BaseReg and ScaleReg (global addresses are always available, as are any
02472   // folded immediates).
02473   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
02474 
02475   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
02476   // lifetime wasn't extended by adding this instruction.
02477   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
02478     BaseReg = nullptr;
02479   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
02480     ScaledReg = nullptr;
02481 
02482   // If folding this instruction (and it's subexprs) didn't extend any live
02483   // ranges, we're ok with it.
02484   if (!BaseReg && !ScaledReg)
02485     return true;
02486 
02487   // If all uses of this instruction are ultimately load/store/inlineasm's,
02488   // check to see if their addressing modes will include this instruction.  If
02489   // so, we can fold it into all uses, so it doesn't matter if it has multiple
02490   // uses.
02491   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
02492   SmallPtrSet<Instruction*, 16> ConsideredInsts;
02493   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
02494     return false;  // Has a non-memory, non-foldable use!
02495 
02496   // Now that we know that all uses of this instruction are part of a chain of
02497   // computation involving only operations that could theoretically be folded
02498   // into a memory use, loop over each of these uses and see if they could
02499   // *actually* fold the instruction.
02500   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
02501   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
02502     Instruction *User = MemoryUses[i].first;
02503     unsigned OpNo = MemoryUses[i].second;
02504 
02505     // Get the access type of this use.  If the use isn't a pointer, we don't
02506     // know what it accesses.
02507     Value *Address = User->getOperand(OpNo);
02508     if (!Address->getType()->isPointerTy())
02509       return false;
02510     Type *AddressAccessTy = Address->getType()->getPointerElementType();
02511 
02512     // Do a match against the root of this address, ignoring profitability. This
02513     // will tell us if the addressing mode for the memory operation will
02514     // *actually* cover the shared instruction.
02515     ExtAddrMode Result;
02516     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02517         TPT.getRestorationPoint();
02518     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
02519                                   MemoryInst, Result, InsertedTruncs,
02520                                   PromotedInsts, TPT);
02521     Matcher.IgnoreProfitability = true;
02522     bool Success = Matcher.MatchAddr(Address, 0);
02523     (void)Success; assert(Success && "Couldn't select *anything*?");
02524 
02525     // The match was to check the profitability, the changes made are not
02526     // part of the original matcher. Therefore, they should be dropped
02527     // otherwise the original matcher will not present the right state.
02528     TPT.rollback(LastKnownGood);
02529 
02530     // If the match didn't cover I, then it won't be shared by it.
02531     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
02532                   I) == MatchedAddrModeInsts.end())
02533       return false;
02534 
02535     MatchedAddrModeInsts.clear();
02536   }
02537 
02538   return true;
02539 }
02540 
02541 } // end anonymous namespace
02542 
02543 /// IsNonLocalValue - Return true if the specified values are defined in a
02544 /// different basic block than BB.
02545 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
02546   if (Instruction *I = dyn_cast<Instruction>(V))
02547     return I->getParent() != BB;
02548   return false;
02549 }
02550 
02551 /// OptimizeMemoryInst - Load and Store Instructions often have
02552 /// addressing modes that can do significant amounts of computation.  As such,
02553 /// instruction selection will try to get the load or store to do as much
02554 /// computation as possible for the program.  The problem is that isel can only
02555 /// see within a single block.  As such, we sink as much legal addressing mode
02556 /// stuff into the block as possible.
02557 ///
02558 /// This method is used to optimize both load/store and inline asms with memory
02559 /// operands.
02560 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
02561                                         Type *AccessTy) {
02562   Value *Repl = Addr;
02563 
02564   // Try to collapse single-value PHI nodes.  This is necessary to undo
02565   // unprofitable PRE transformations.
02566   SmallVector<Value*, 8> worklist;
02567   SmallPtrSet<Value*, 16> Visited;
02568   worklist.push_back(Addr);
02569 
02570   // Use a worklist to iteratively look through PHI nodes, and ensure that
02571   // the addressing mode obtained from the non-PHI roots of the graph
02572   // are equivalent.
02573   Value *Consensus = nullptr;
02574   unsigned NumUsesConsensus = 0;
02575   bool IsNumUsesConsensusValid = false;
02576   SmallVector<Instruction*, 16> AddrModeInsts;
02577   ExtAddrMode AddrMode;
02578   TypePromotionTransaction TPT;
02579   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02580       TPT.getRestorationPoint();
02581   while (!worklist.empty()) {
02582     Value *V = worklist.back();
02583     worklist.pop_back();
02584 
02585     // Break use-def graph loops.
02586     if (!Visited.insert(V)) {
02587       Consensus = nullptr;
02588       break;
02589     }
02590 
02591     // For a PHI node, push all of its incoming values.
02592     if (PHINode *P = dyn_cast<PHINode>(V)) {
02593       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
02594         worklist.push_back(P->getIncomingValue(i));
02595       continue;
02596     }
02597 
02598     // For non-PHIs, determine the addressing mode being computed.
02599     SmallVector<Instruction*, 16> NewAddrModeInsts;
02600     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
02601         V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
02602         PromotedInsts, TPT);
02603 
02604     // This check is broken into two cases with very similar code to avoid using
02605     // getNumUses() as much as possible. Some values have a lot of uses, so
02606     // calling getNumUses() unconditionally caused a significant compile-time
02607     // regression.
02608     if (!Consensus) {
02609       Consensus = V;
02610       AddrMode = NewAddrMode;
02611       AddrModeInsts = NewAddrModeInsts;
02612       continue;
02613     } else if (NewAddrMode == AddrMode) {
02614       if (!IsNumUsesConsensusValid) {
02615         NumUsesConsensus = Consensus->getNumUses();
02616         IsNumUsesConsensusValid = true;
02617       }
02618 
02619       // Ensure that the obtained addressing mode is equivalent to that obtained
02620       // for all other roots of the PHI traversal.  Also, when choosing one
02621       // such root as representative, select the one with the most uses in order
02622       // to keep the cost modeling heuristics in AddressingModeMatcher
02623       // applicable.
02624       unsigned NumUses = V->getNumUses();
02625       if (NumUses > NumUsesConsensus) {
02626         Consensus = V;
02627         NumUsesConsensus = NumUses;
02628         AddrModeInsts = NewAddrModeInsts;
02629       }
02630       continue;
02631     }
02632 
02633     Consensus = nullptr;
02634     break;
02635   }
02636 
02637   // If the addressing mode couldn't be determined, or if multiple different
02638   // ones were determined, bail out now.
02639   if (!Consensus) {
02640     TPT.rollback(LastKnownGood);
02641     return false;
02642   }
02643   TPT.commit();
02644 
02645   // Check to see if any of the instructions supersumed by this addr mode are
02646   // non-local to I's BB.
02647   bool AnyNonLocal = false;
02648   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
02649     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
02650       AnyNonLocal = true;
02651       break;
02652     }
02653   }
02654 
02655   // If all the instructions matched are already in this BB, don't do anything.
02656   if (!AnyNonLocal) {
02657     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
02658     return false;
02659   }
02660 
02661   // Insert this computation right after this user.  Since our caller is
02662   // scanning from the top of the BB to the bottom, reuse of the expr are
02663   // guaranteed to happen later.
02664   IRBuilder<> Builder(MemoryInst);
02665 
02666   // Now that we determined the addressing expression we want to use and know
02667   // that we have to sink it into this block.  Check to see if we have already
02668   // done this for some other load/store instr in this block.  If so, reuse the
02669   // computation.
02670   Value *&SunkAddr = SunkAddrs[Addr];
02671   if (SunkAddr) {
02672     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
02673                  << *MemoryInst << "\n");
02674     if (SunkAddr->getType() != Addr->getType())
02675       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
02676   } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
02677                TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
02678     // By default, we use the GEP-based method when AA is used later. This
02679     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
02680     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
02681                  << *MemoryInst << "\n");
02682     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
02683     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
02684 
02685     // First, find the pointer.
02686     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
02687       ResultPtr = AddrMode.BaseReg;
02688       AddrMode.BaseReg = nullptr;
02689     }
02690 
02691     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
02692       // We can't add more than one pointer together, nor can we scale a
02693       // pointer (both of which seem meaningless).
02694       if (ResultPtr || AddrMode.Scale != 1)
02695         return false;
02696 
02697       ResultPtr = AddrMode.ScaledReg;
02698       AddrMode.Scale = 0;
02699     }
02700 
02701     if (AddrMode.BaseGV) {
02702       if (ResultPtr)
02703         return false;
02704 
02705       ResultPtr = AddrMode.BaseGV;
02706     }
02707 
02708     // If the real base value actually came from an inttoptr, then the matcher
02709     // will look through it and provide only the integer value. In that case,
02710     // use it here.
02711     if (!ResultPtr && AddrMode.BaseReg) {
02712       ResultPtr =
02713         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
02714       AddrMode.BaseReg = nullptr;
02715     } else if (!ResultPtr && AddrMode.Scale == 1) {
02716       ResultPtr =
02717         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
02718       AddrMode.Scale = 0;
02719     }
02720 
02721     if (!ResultPtr &&
02722         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
02723       SunkAddr = Constant::getNullValue(Addr->getType());
02724     } else if (!ResultPtr) {
02725       return false;
02726     } else {
02727       Type *I8PtrTy =
02728         Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
02729 
02730       // Start with the base register. Do this first so that subsequent address
02731       // matching finds it last, which will prevent it from trying to match it
02732       // as the scaled value in case it happens to be a mul. That would be
02733       // problematic if we've sunk a different mul for the scale, because then
02734       // we'd end up sinking both muls.
02735       if (AddrMode.BaseReg) {
02736         Value *V = AddrMode.BaseReg;
02737         if (V->getType() != IntPtrTy)
02738           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
02739 
02740         ResultIndex = V;
02741       }
02742 
02743       // Add the scale value.
02744       if (AddrMode.Scale) {
02745         Value *V = AddrMode.ScaledReg;
02746         if (V->getType() == IntPtrTy) {
02747           // done.
02748         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
02749                    cast<IntegerType>(V->getType())->getBitWidth()) {
02750           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
02751         } else {
02752           // It is only safe to sign extend the BaseReg if we know that the math
02753           // required to create it did not overflow before we extend it. Since
02754           // the original IR value was tossed in favor of a constant back when
02755           // the AddrMode was created we need to bail out gracefully if widths
02756           // do not match instead of extending it.
02757           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
02758           if (I && (ResultIndex != AddrMode.BaseReg))
02759             I->eraseFromParent();
02760           return false;
02761         }
02762 
02763         if (AddrMode.Scale != 1)
02764           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
02765                                 "sunkaddr");
02766         if (ResultIndex)
02767           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
02768         else
02769           ResultIndex = V;
02770       }
02771 
02772       // Add in the Base Offset if present.
02773       if (AddrMode.BaseOffs) {
02774         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
02775         if (ResultIndex) {
02776           // We need to add this separately from the scale above to help with
02777           // SDAG consecutive load/store merging.
02778           if (ResultPtr->getType() != I8PtrTy)
02779             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
02780           ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
02781         }
02782 
02783         ResultIndex = V;
02784       }
02785 
02786       if (!ResultIndex) {
02787         SunkAddr = ResultPtr;
02788       } else {
02789         if (ResultPtr->getType() != I8PtrTy)
02790           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
02791         SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
02792       }
02793 
02794       if (SunkAddr->getType() != Addr->getType())
02795         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
02796     }
02797   } else {
02798     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
02799                  << *MemoryInst << "\n");
02800     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
02801     Value *Result = nullptr;
02802 
02803     // Start with the base register. Do this first so that subsequent address
02804     // matching finds it last, which will prevent it from trying to match it
02805     // as the scaled value in case it happens to be a mul. That would be
02806     // problematic if we've sunk a different mul for the scale, because then
02807     // we'd end up sinking both muls.
02808     if (AddrMode.BaseReg) {
02809       Value *V = AddrMode.BaseReg;
02810       if (V->getType()->isPointerTy())
02811         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
02812       if (V->getType() != IntPtrTy)
02813         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
02814       Result = V;
02815     }
02816 
02817     // Add the scale value.
02818     if (AddrMode.Scale) {
02819       Value *V = AddrMode.ScaledReg;
02820       if (V->getType() == IntPtrTy) {
02821         // done.
02822       } else if (V->getType()->isPointerTy()) {
02823         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
02824       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
02825                  cast<IntegerType>(V->getType())->getBitWidth()) {
02826         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
02827       } else {
02828         // It is only safe to sign extend the BaseReg if we know that the math
02829         // required to create it did not overflow before we extend it. Since
02830         // the original IR value was tossed in favor of a constant back when
02831         // the AddrMode was created we need to bail out gracefully if widths
02832         // do not match instead of extending it.
02833         Instruction *I = dyn_cast_or_null<Instruction>(Result);
02834         if (I && (Result != AddrMode.BaseReg))
02835           I->eraseFromParent();
02836         return false;
02837       }
02838       if (AddrMode.Scale != 1)
02839         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
02840                               "sunkaddr");
02841       if (Result)
02842         Result = Builder.CreateAdd(Result, V, "sunkaddr");
02843       else
02844         Result = V;
02845     }
02846 
02847     // Add in the BaseGV if present.
02848     if (AddrMode.BaseGV) {
02849       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
02850       if (Result)
02851         Result = Builder.CreateAdd(Result, V, "sunkaddr");
02852       else
02853         Result = V;
02854     }
02855 
02856     // Add in the Base Offset if present.
02857     if (AddrMode.BaseOffs) {
02858       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
02859       if (Result)
02860         Result = Builder.CreateAdd(Result, V, "sunkaddr");
02861       else
02862         Result = V;
02863     }
02864 
02865     if (!Result)
02866       SunkAddr = Constant::getNullValue(Addr->getType());
02867     else
02868       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
02869   }
02870 
02871   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
02872 
02873   // If we have no uses, recursively delete the value and all dead instructions
02874   // using it.
02875   if (Repl->use_empty()) {
02876     // This can cause recursive deletion, which can invalidate our iterator.
02877     // Use a WeakVH to hold onto it in case this happens.
02878     WeakVH IterHandle(CurInstIterator);
02879     BasicBlock *BB = CurInstIterator->getParent();
02880 
02881     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
02882 
02883     if (IterHandle != CurInstIterator) {
02884       // If the iterator instruction was recursively deleted, start over at the
02885       // start of the block.
02886       CurInstIterator = BB->begin();
02887       SunkAddrs.clear();
02888     }
02889   }
02890   ++NumMemoryInsts;
02891   return true;
02892 }
02893 
02894 /// OptimizeInlineAsmInst - If there are any memory operands, use
02895 /// OptimizeMemoryInst to sink their address computing into the block when
02896 /// possible / profitable.
02897 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
02898   bool MadeChange = false;
02899 
02900   TargetLowering::AsmOperandInfoVector
02901     TargetConstraints = TLI->ParseConstraints(CS);
02902   unsigned ArgNo = 0;
02903   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
02904     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
02905 
02906     // Compute the constraint code and ConstraintType to use.
02907     TLI->ComputeConstraintToUse(OpInfo, SDValue());
02908 
02909     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
02910         OpInfo.isIndirect) {
02911       Value *OpVal = CS->getArgOperand(ArgNo++);
02912       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
02913     } else if (OpInfo.Type == InlineAsm::isInput)
02914       ArgNo++;
02915   }
02916 
02917   return MadeChange;
02918 }
02919 
02920 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
02921 /// basic block as the load, unless conditions are unfavorable. This allows
02922 /// SelectionDAG to fold the extend into the load.
02923 ///
02924 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
02925   // Look for a load being extended.
02926   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
02927   if (!LI) return false;
02928 
02929   // If they're already in the same block, there's nothing to do.
02930   if (LI->getParent() == I->getParent())
02931     return false;
02932 
02933   // If the load has other users and the truncate is not free, this probably
02934   // isn't worthwhile.
02935   if (!LI->hasOneUse() &&
02936       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
02937               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
02938       !TLI->isTruncateFree(I->getType(), LI->getType()))
02939     return false;
02940 
02941   // Check whether the target supports casts folded into loads.
02942   unsigned LType;
02943   if (isa<ZExtInst>(I))
02944     LType = ISD::ZEXTLOAD;
02945   else {
02946     assert(isa<SExtInst>(I) && "Unexpected ext type!");
02947     LType = ISD::SEXTLOAD;
02948   }
02949   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
02950     return false;
02951 
02952   // Move the extend into the same block as the load, so that SelectionDAG
02953   // can fold it.
02954   I->removeFromParent();
02955   I->insertAfter(LI);
02956   ++NumExtsMoved;
02957   return true;
02958 }
02959 
02960 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
02961   BasicBlock *DefBB = I->getParent();
02962 
02963   // If the result of a {s|z}ext and its source are both live out, rewrite all
02964   // other uses of the source with result of extension.
02965   Value *Src = I->getOperand(0);
02966   if (Src->hasOneUse())
02967     return false;
02968 
02969   // Only do this xform if truncating is free.
02970   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
02971     return false;
02972 
02973   // Only safe to perform the optimization if the source is also defined in
02974   // this block.
02975   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
02976     return false;
02977 
02978   bool DefIsLiveOut = false;
02979   for (User *U : I->users()) {
02980     Instruction *UI = cast<Instruction>(U);
02981 
02982     // Figure out which BB this ext is used in.
02983     BasicBlock *UserBB = UI->getParent();
02984     if (UserBB == DefBB) continue;
02985     DefIsLiveOut = true;
02986     break;
02987   }
02988   if (!DefIsLiveOut)
02989     return false;
02990 
02991   // Make sure none of the uses are PHI nodes.
02992   for (User *U : Src->users()) {
02993     Instruction *UI = cast<Instruction>(U);
02994     BasicBlock *UserBB = UI->getParent();
02995     if (UserBB == DefBB) continue;
02996     // Be conservative. We don't want this xform to end up introducing
02997     // reloads just before load / store instructions.
02998     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
02999       return false;
03000   }
03001 
03002   // InsertedTruncs - Only insert one trunc in each block once.
03003   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
03004 
03005   bool MadeChange = false;
03006   for (Use &U : Src->uses()) {
03007     Instruction *User = cast<Instruction>(U.getUser());
03008 
03009     // Figure out which BB this ext is used in.
03010     BasicBlock *UserBB = User->getParent();
03011     if (UserBB == DefBB) continue;
03012 
03013     // Both src and def are live in this block. Rewrite the use.
03014     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
03015 
03016     if (!InsertedTrunc) {
03017       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
03018       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
03019       InsertedTruncsSet.insert(InsertedTrunc);
03020     }
03021 
03022     // Replace a use of the {s|z}ext source with a use of the result.
03023     U = InsertedTrunc;
03024     ++NumExtUses;
03025     MadeChange = true;
03026   }
03027 
03028   return MadeChange;
03029 }
03030 
03031 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
03032 /// turned into an explicit branch.
03033 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
03034   // FIXME: This should use the same heuristics as IfConversion to determine
03035   // whether a select is better represented as a branch.  This requires that
03036   // branch probability metadata is preserved for the select, which is not the
03037   // case currently.
03038 
03039   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
03040 
03041   // If the branch is predicted right, an out of order CPU can avoid blocking on
03042   // the compare.  Emit cmovs on compares with a memory operand as branches to
03043   // avoid stalls on the load from memory.  If the compare has more than one use
03044   // there's probably another cmov or setcc around so it's not worth emitting a
03045   // branch.
03046   if (!Cmp)
03047     return false;
03048 
03049   Value *CmpOp0 = Cmp->getOperand(0);
03050   Value *CmpOp1 = Cmp->getOperand(1);
03051 
03052   // We check that the memory operand has one use to avoid uses of the loaded
03053   // value directly after the compare, making branches unprofitable.
03054   return Cmp->hasOneUse() &&
03055          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
03056           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
03057 }
03058 
03059 
03060 /// If we have a SelectInst that will likely profit from branch prediction,
03061 /// turn it into a branch.
03062 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
03063   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
03064 
03065   // Can we convert the 'select' to CF ?
03066   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
03067     return false;
03068 
03069   TargetLowering::SelectSupportKind SelectKind;
03070   if (VectorCond)
03071     SelectKind = TargetLowering::VectorMaskSelect;
03072   else if (SI->getType()->isVectorTy())
03073     SelectKind = TargetLowering::ScalarCondVectorVal;
03074   else
03075     SelectKind = TargetLowering::ScalarValSelect;
03076 
03077   // Do we have efficient codegen support for this kind of 'selects' ?
03078   if (TLI->isSelectSupported(SelectKind)) {
03079     // We have efficient codegen support for the select instruction.
03080     // Check if it is profitable to keep this 'select'.
03081     if (!TLI->isPredictableSelectExpensive() ||
03082         !isFormingBranchFromSelectProfitable(SI))
03083       return false;
03084   }
03085 
03086   ModifiedDT = true;
03087 
03088   // First, we split the block containing the select into 2 blocks.
03089   BasicBlock *StartBlock = SI->getParent();
03090   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
03091   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
03092 
03093   // Create a new block serving as the landing pad for the branch.
03094   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
03095                                              NextBlock->getParent(), NextBlock);
03096 
03097   // Move the unconditional branch from the block with the select in it into our
03098   // landing pad block.
03099   StartBlock->getTerminator()->eraseFromParent();
03100   BranchInst::Create(NextBlock, SmallBlock);
03101 
03102   // Insert the real conditional branch based on the original condition.
03103   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
03104 
03105   // The select itself is replaced with a PHI Node.
03106   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
03107   PN->takeName(SI);
03108   PN->addIncoming(SI->getTrueValue(), StartBlock);
03109   PN->addIncoming(SI->getFalseValue(), SmallBlock);
03110   SI->replaceAllUsesWith(PN);
03111   SI->eraseFromParent();
03112 
03113   // Instruct OptimizeBlock to skip to the next block.
03114   CurInstIterator = StartBlock->end();
03115   ++NumSelectsExpanded;
03116   return true;
03117 }
03118 
03119 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
03120   SmallVector<int, 16> Mask(SVI->getShuffleMask());
03121   int SplatElem = -1;
03122   for (unsigned i = 0; i < Mask.size(); ++i) {
03123     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
03124       return false;
03125     SplatElem = Mask[i];
03126   }
03127 
03128   return true;
03129 }
03130 
03131 /// Some targets have expensive vector shifts if the lanes aren't all the same
03132 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
03133 /// it's often worth sinking a shufflevector splat down to its use so that
03134 /// codegen can spot all lanes are identical.
03135 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
03136   BasicBlock *DefBB = SVI->getParent();
03137 
03138   // Only do this xform if variable vector shifts are particularly expensive.
03139   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
03140     return false;
03141 
03142   // We only expect better codegen by sinking a shuffle if we can recognise a
03143   // constant splat.
03144   if (!isBroadcastShuffle(SVI))
03145     return false;
03146 
03147   // InsertedShuffles - Only insert a shuffle in each block once.
03148   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
03149 
03150   bool MadeChange = false;
03151   for (User *U : SVI->users()) {
03152     Instruction *UI = cast<Instruction>(U);
03153 
03154     // Figure out which BB this ext is used in.
03155     BasicBlock *UserBB = UI->getParent();
03156     if (UserBB == DefBB) continue;
03157 
03158     // For now only apply this when the splat is used by a shift instruction.
03159     if (!UI->isShift()) continue;
03160 
03161     // Everything checks out, sink the shuffle if the user's block doesn't
03162     // already have a copy.
03163     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
03164 
03165     if (!InsertedShuffle) {
03166       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
03167       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
03168                                               SVI->getOperand(1),
03169                                               SVI->getOperand(2), "", InsertPt);
03170     }
03171 
03172     UI->replaceUsesOfWith(SVI, InsertedShuffle);
03173     MadeChange = true;
03174   }
03175 
03176   // If we removed all uses, nuke the shuffle.
03177   if (SVI->use_empty()) {
03178     SVI->eraseFromParent();
03179     MadeChange = true;
03180   }
03181 
03182   return MadeChange;
03183 }
03184 
03185 namespace {
03186 /// \brief Helper class to promote a scalar operation to a vector one.
03187 /// This class is used to move downward extractelement transition.
03188 /// E.g.,
03189 /// a = vector_op <2 x i32>
03190 /// b = extractelement <2 x i32> a, i32 0
03191 /// c = scalar_op b
03192 /// store c
03193 ///
03194 /// =>
03195 /// a = vector_op <2 x i32>
03196 /// c = vector_op a (equivalent to scalar_op on the related lane)
03197 /// * d = extractelement <2 x i32> c, i32 0
03198 /// * store d
03199 /// Assuming both extractelement and store can be combine, we get rid of the
03200 /// transition.
03201 class VectorPromoteHelper {
03202   /// Used to perform some checks on the legality of vector operations.
03203   const TargetLowering &TLI;
03204 
03205   /// Used to estimated the cost of the promoted chain.
03206   const TargetTransformInfo &TTI;
03207 
03208   /// The transition being moved downwards.
03209   Instruction *Transition;
03210   /// The sequence of instructions to be promoted.
03211   SmallVector<Instruction *, 4> InstsToBePromoted;
03212   /// Cost of combining a store and an extract.
03213   unsigned StoreExtractCombineCost;
03214   /// Instruction that will be combined with the transition.
03215   Instruction *CombineInst;
03216 
03217   /// \brief The instruction that represents the current end of the transition.
03218   /// Since we are faking the promotion until we reach the end of the chain
03219   /// of computation, we need a way to get the current end of the transition.
03220   Instruction *getEndOfTransition() const {
03221     if (InstsToBePromoted.empty())
03222       return Transition;
03223     return InstsToBePromoted.back();
03224   }
03225 
03226   /// \brief Return the index of the original value in the transition.
03227   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
03228   /// c, is at index 0.
03229   unsigned getTransitionOriginalValueIdx() const {
03230     assert(isa<ExtractElementInst>(Transition) &&
03231            "Other kind of transitions are not supported yet");
03232     return 0;
03233   }
03234 
03235   /// \brief Return the index of the index in the transition.
03236   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
03237   /// is at index 1.
03238   unsigned getTransitionIdx() const {
03239     assert(isa<ExtractElementInst>(Transition) &&
03240            "Other kind of transitions are not supported yet");
03241     return 1;
03242   }
03243 
03244   /// \brief Get the type of the transition.
03245   /// This is the type of the original value.
03246   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
03247   /// transition is <2 x i32>.
03248   Type *getTransitionType() const {
03249     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
03250   }
03251 
03252   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
03253   /// I.e., we have the following sequence:
03254   /// Def = Transition <ty1> a to <ty2>
03255   /// b = ToBePromoted <ty2> Def, ...
03256   /// =>
03257   /// b = ToBePromoted <ty1> a, ...
03258   /// Def = Transition <ty1> ToBePromoted to <ty2>
03259   void promoteImpl(Instruction *ToBePromoted);
03260 
03261   /// \brief Check whether or not it is profitable to promote all the
03262   /// instructions enqueued to be promoted.
03263   bool isProfitableToPromote() {
03264     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
03265     unsigned Index = isa<ConstantInt>(ValIdx)
03266                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
03267                          : -1;
03268     Type *PromotedType = getTransitionType();
03269 
03270     StoreInst *ST = cast<StoreInst>(CombineInst);
03271     unsigned AS = ST->getPointerAddressSpace();
03272     unsigned Align = ST->getAlignment();
03273     // Check if this store is supported.
03274     if (!TLI.allowsMisalignedMemoryAccesses(
03275             EVT::getEVT(ST->getValueOperand()->getType()), AS, Align)) {
03276       // If this is not supported, there is no way we can combine
03277       // the extract with the store.
03278       return false;
03279     }
03280 
03281     // The scalar chain of computation has to pay for the transition
03282     // scalar to vector.
03283     // The vector chain has to account for the combining cost.
03284     uint64_t ScalarCost =
03285         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
03286     uint64_t VectorCost = StoreExtractCombineCost;
03287     for (const auto &Inst : InstsToBePromoted) {
03288       // Compute the cost.
03289       // By construction, all instructions being promoted are arithmetic ones.
03290       // Moreover, one argument is a constant that can be viewed as a splat
03291       // constant.
03292       Value *Arg0 = Inst->getOperand(0);
03293       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
03294                             isa<ConstantFP>(Arg0);
03295       TargetTransformInfo::OperandValueKind Arg0OVK =
03296           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
03297                          : TargetTransformInfo::OK_AnyValue;
03298       TargetTransformInfo::OperandValueKind Arg1OVK =
03299           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
03300                           : TargetTransformInfo::OK_AnyValue;
03301       ScalarCost += TTI.getArithmeticInstrCost(
03302           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
03303       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
03304                                                Arg0OVK, Arg1OVK);
03305     }
03306     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
03307                  << ScalarCost << "\nVector: " << VectorCost << '\n');
03308     return ScalarCost > VectorCost;
03309   }
03310 
03311   /// \brief Generate a constant vector with \p Val with the same
03312   /// number of elements as the transition.
03313   /// \p UseSplat defines whether or not \p Val should be replicated
03314   /// accross the whole vector.
03315   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
03316   /// otherwise we generate a vector with as many undef as possible:
03317   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
03318   /// used at the index of the extract.
03319   Value *getConstantVector(Constant *Val, bool UseSplat) const {
03320     unsigned ExtractIdx = UINT_MAX;
03321     if (!UseSplat) {
03322       // If we cannot determine where the constant must be, we have to
03323       // use a splat constant.
03324       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
03325       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
03326         ExtractIdx = CstVal->getSExtValue();
03327       else
03328         UseSplat = true;
03329     }
03330 
03331     unsigned End = getTransitionType()->getVectorNumElements();
03332     if (UseSplat)
03333       return ConstantVector::getSplat(End, Val);
03334 
03335     SmallVector<Constant *, 4> ConstVec;
03336     UndefValue *UndefVal = UndefValue::get(Val->getType());
03337     for (unsigned Idx = 0; Idx != End; ++Idx) {
03338       if (Idx == ExtractIdx)
03339         ConstVec.push_back(Val);
03340       else
03341         ConstVec.push_back(UndefVal);
03342     }
03343     return ConstantVector::get(ConstVec);
03344   }
03345 
03346   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
03347   /// in \p Use can trigger undefined behavior.
03348   static bool canCauseUndefinedBehavior(const Instruction *Use,
03349                                         unsigned OperandIdx) {
03350     // This is not safe to introduce undef when the operand is on
03351     // the right hand side of a division-like instruction.
03352     if (OperandIdx != 1)
03353       return false;
03354     switch (Use->getOpcode()) {
03355     default:
03356       return false;
03357     case Instruction::SDiv:
03358     case Instruction::UDiv:
03359     case Instruction::SRem:
03360     case Instruction::URem:
03361       return true;
03362     case Instruction::FDiv:
03363     case Instruction::FRem:
03364       return !Use->hasNoNaNs();
03365     }
03366     llvm_unreachable(nullptr);
03367   }
03368 
03369 public:
03370   VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
03371                       Instruction *Transition, unsigned CombineCost)
03372       : TLI(TLI), TTI(TTI), Transition(Transition),
03373         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
03374     assert(Transition && "Do not know how to promote null");
03375   }
03376 
03377   /// \brief Check if we can promote \p ToBePromoted to \p Type.
03378   bool canPromote(const Instruction *ToBePromoted) const {
03379     // We could support CastInst too.
03380     return isa<BinaryOperator>(ToBePromoted);
03381   }
03382 
03383   /// \brief Check if it is profitable to promote \p ToBePromoted
03384   /// by moving downward the transition through.
03385   bool shouldPromote(const Instruction *ToBePromoted) const {
03386     // Promote only if all the operands can be statically expanded.
03387     // Indeed, we do not want to introduce any new kind of transitions.
03388     for (const Use &U : ToBePromoted->operands()) {
03389       const Value *Val = U.get();
03390       if (Val == getEndOfTransition()) {
03391         // If the use is a division and the transition is on the rhs,
03392         // we cannot promote the operation, otherwise we may create a
03393         // division by zero.
03394         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
03395           return false;
03396         continue;
03397       }
03398       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
03399           !isa<ConstantFP>(Val))
03400         return false;
03401     }
03402     // Check that the resulting operation is legal.
03403     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
03404     if (!ISDOpcode)
03405       return false;
03406     return StressStoreExtract ||
03407            TLI.isOperationLegalOrCustom(ISDOpcode,
03408                                         EVT::getEVT(getTransitionType(), true));
03409   }
03410 
03411   /// \brief Check whether or not \p Use can be combined
03412   /// with the transition.
03413   /// I.e., is it possible to do Use(Transition) => AnotherUse?
03414   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
03415 
03416   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
03417   void enqueueForPromotion(Instruction *ToBePromoted) {
03418     InstsToBePromoted.push_back(ToBePromoted);
03419   }
03420 
03421   /// \brief Set the instruction that will be combined with the transition.
03422   void recordCombineInstruction(Instruction *ToBeCombined) {
03423     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
03424     CombineInst = ToBeCombined;
03425   }
03426 
03427   /// \brief Promote all the instructions enqueued for promotion if it is
03428   /// is profitable.
03429   /// \return True if the promotion happened, false otherwise.
03430   bool promote() {
03431     // Check if there is something to promote.
03432     // Right now, if we do not have anything to combine with,
03433     // we assume the promotion is not profitable.
03434     if (InstsToBePromoted.empty() || !CombineInst)
03435       return false;
03436 
03437     // Check cost.
03438     if (!StressStoreExtract && !isProfitableToPromote())
03439       return false;
03440 
03441     // Promote.
03442     for (auto &ToBePromoted : InstsToBePromoted)
03443       promoteImpl(ToBePromoted);
03444     InstsToBePromoted.clear();
03445     return true;
03446   }
03447 };
03448 } // End of anonymous namespace.
03449 
03450 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
03451   // At this point, we know that all the operands of ToBePromoted but Def
03452   // can be statically promoted.
03453   // For Def, we need to use its parameter in ToBePromoted:
03454   // b = ToBePromoted ty1 a
03455   // Def = Transition ty1 b to ty2
03456   // Move the transition down.
03457   // 1. Replace all uses of the promoted operation by the transition.
03458   // = ... b => = ... Def.
03459   assert(ToBePromoted->getType() == Transition->getType() &&
03460          "The type of the result of the transition does not match "
03461          "the final type");
03462   ToBePromoted->replaceAllUsesWith(Transition);
03463   // 2. Update the type of the uses.
03464   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
03465   Type *TransitionTy = getTransitionType();
03466   ToBePromoted->mutateType(TransitionTy);
03467   // 3. Update all the operands of the promoted operation with promoted
03468   // operands.
03469   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
03470   for (Use &U : ToBePromoted->operands()) {
03471     Value *Val = U.get();
03472     Value *NewVal = nullptr;
03473     if (Val == Transition)
03474       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
03475     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
03476              isa<ConstantFP>(Val)) {
03477       // Use a splat constant if it is not safe to use undef.
03478       NewVal = getConstantVector(
03479           cast<Constant>(Val),
03480           isa<UndefValue>(Val) ||
03481               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
03482     } else
03483       assert(0 && "Did you modified shouldPromote and forgot to update this?");
03484     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
03485   }
03486   Transition->removeFromParent();
03487   Transition->insertAfter(ToBePromoted);
03488   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
03489 }
03490 
03491 /// Some targets can do store(extractelement) with one instruction.
03492 /// Try to push the extractelement towards the stores when the target
03493 /// has this feature and this is profitable.
03494 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
03495   unsigned CombineCost = UINT_MAX;
03496   if (DisableStoreExtract || !TLI ||
03497       (!StressStoreExtract &&
03498        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
03499                                        Inst->getOperand(1), CombineCost)))
03500     return false;
03501 
03502   // At this point we know that Inst is a vector to scalar transition.
03503   // Try to move it down the def-use chain, until:
03504   // - We can combine the transition with its single use
03505   //   => we got rid of the transition.
03506   // - We escape the current basic block
03507   //   => we would need to check that we are moving it at a cheaper place and
03508   //      we do not do that for now.
03509   BasicBlock *Parent = Inst->getParent();
03510   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
03511   VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
03512   // If the transition has more than one use, assume this is not going to be
03513   // beneficial.
03514   while (Inst->hasOneUse()) {
03515     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
03516     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
03517 
03518     if (ToBePromoted->getParent() != Parent) {
03519       DEBUG(dbgs() << "Instruction to promote is in a different block ("
03520                    << ToBePromoted->getParent()->getName()
03521                    << ") than the transition (" << Parent->getName() << ").\n");
03522       return false;
03523     }
03524 
03525     if (VPH.canCombine(ToBePromoted)) {
03526       DEBUG(dbgs() << "Assume " << *Inst << '\n'
03527                    << "will be combined with: " << *ToBePromoted << '\n');
03528       VPH.recordCombineInstruction(ToBePromoted);
03529       bool Changed = VPH.promote();
03530       NumStoreExtractExposed += Changed;
03531       return Changed;
03532     }
03533 
03534     DEBUG(dbgs() << "Try promoting.\n");
03535     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
03536       return false;
03537 
03538     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
03539 
03540     VPH.enqueueForPromotion(ToBePromoted);
03541     Inst = ToBePromoted;
03542   }
03543   return false;
03544 }
03545 
03546 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
03547   if (PHINode *P = dyn_cast<PHINode>(I)) {
03548     // It is possible for very late stage optimizations (such as SimplifyCFG)
03549     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
03550     // trivial PHI, go ahead and zap it here.
03551     if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
03552                                        TLInfo, DT)) {
03553       P->replaceAllUsesWith(V);
03554       P->eraseFromParent();
03555       ++NumPHIsElim;
03556       return true;
03557     }
03558     return false;
03559   }
03560 
03561   if (CastInst *CI = dyn_cast<CastInst>(I)) {
03562     // If the source of the cast is a constant, then this should have
03563     // already been constant folded.  The only reason NOT to constant fold
03564     // it is if something (e.g. LSR) was careful to place the constant
03565     // evaluation in a block other than then one that uses it (e.g. to hoist
03566     // the address of globals out of a loop).  If this is the case, we don't
03567     // want to forward-subst the cast.
03568     if (isa<Constant>(CI->getOperand(0)))
03569       return false;
03570 
03571     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
03572       return true;
03573 
03574     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
03575       /// Sink a zext or sext into its user blocks if the target type doesn't
03576       /// fit in one register
03577       if (TLI && TLI->getTypeAction(CI->getContext(),
03578                                     TLI->getValueType(CI->getType())) ==
03579                      TargetLowering::TypeExpandInteger) {
03580         return SinkCast(CI);
03581       } else {
03582         bool MadeChange = MoveExtToFormExtLoad(I);
03583         return MadeChange | OptimizeExtUses(I);
03584       }
03585     }
03586     return false;
03587   }
03588 
03589   if (CmpInst *CI = dyn_cast<CmpInst>(I))
03590     if (!TLI || !TLI->hasMultipleConditionRegisters())
03591       return OptimizeCmpExpression(CI);
03592 
03593   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
03594     if (TLI)
03595       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
03596     return false;
03597   }
03598 
03599   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
03600     if (TLI)
03601       return OptimizeMemoryInst(I, SI->getOperand(1),
03602                                 SI->getOperand(0)->getType());
03603     return false;
03604   }
03605 
03606   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
03607 
03608   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
03609                 BinOp->getOpcode() == Instruction::LShr)) {
03610     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
03611     if (TLI && CI && TLI->hasExtractBitsInsn())
03612       return OptimizeExtractBits(BinOp, CI, *TLI);
03613 
03614     return false;
03615   }
03616 
03617   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
03618     if (GEPI->hasAllZeroIndices()) {
03619       /// The GEP operand must be a pointer, so must its result -> BitCast
03620       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
03621                                         GEPI->getName(), GEPI);
03622       GEPI->replaceAllUsesWith(NC);
03623       GEPI->eraseFromParent();
03624       ++NumGEPsElim;
03625       OptimizeInst(NC);
03626       return true;
03627     }
03628     return false;
03629   }
03630 
03631   if (CallInst *CI = dyn_cast<CallInst>(I))
03632     return OptimizeCallInst(CI);
03633 
03634   if (SelectInst *SI = dyn_cast<SelectInst>(I))
03635     return OptimizeSelectInst(SI);
03636 
03637   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
03638     return OptimizeShuffleVectorInst(SVI);
03639 
03640   if (isa<ExtractElementInst>(I))
03641     return OptimizeExtractElementInst(I);
03642 
03643   return false;
03644 }
03645 
03646 // In this pass we look for GEP and cast instructions that are used
03647 // across basic blocks and rewrite them to improve basic-block-at-a-time
03648 // selection.
03649 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
03650   SunkAddrs.clear();
03651   bool MadeChange = false;
03652 
03653   CurInstIterator = BB.begin();
03654   while (CurInstIterator != BB.end())
03655     MadeChange |= OptimizeInst(CurInstIterator++);
03656 
03657   MadeChange |= DupRetToEnableTailCallOpts(&BB);
03658 
03659   return MadeChange;
03660 }
03661 
03662 // llvm.dbg.value is far away from the value then iSel may not be able
03663 // handle it properly. iSel will drop llvm.dbg.value if it can not
03664 // find a node corresponding to the value.
03665 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
03666   bool MadeChange = false;
03667   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
03668     Instruction *PrevNonDbgInst = nullptr;
03669     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
03670       Instruction *Insn = BI; ++BI;
03671       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
03672       // Leave dbg.values that refer to an alloca alone. These
03673       // instrinsics describe the address of a variable (= the alloca)
03674       // being taken.  They should not be moved next to the alloca
03675       // (and to the beginning of the scope), but rather stay close to
03676       // where said address is used.
03677       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
03678         PrevNonDbgInst = Insn;
03679         continue;
03680       }
03681 
03682       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
03683       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
03684         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
03685         DVI->removeFromParent();
03686         if (isa<PHINode>(VI))
03687           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
03688         else
03689           DVI->insertAfter(VI);
03690         MadeChange = true;
03691         ++NumDbgValueMoved;
03692       }
03693     }
03694   }
03695   return MadeChange;
03696 }
03697 
03698 // If there is a sequence that branches based on comparing a single bit
03699 // against zero that can be combined into a single instruction, and the
03700 // target supports folding these into a single instruction, sink the
03701 // mask and compare into the branch uses. Do this before OptimizeBlock ->
03702 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
03703 // searched for.
03704 bool CodeGenPrepare::sinkAndCmp(Function &F) {
03705   if (!EnableAndCmpSinking)
03706     return false;
03707   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
03708     return false;
03709   bool MadeChange = false;
03710   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
03711     BasicBlock *BB = I++;
03712 
03713     // Does this BB end with the following?
03714     //   %andVal = and %val, #single-bit-set
03715     //   %icmpVal = icmp %andResult, 0
03716     //   br i1 %cmpVal label %dest1, label %dest2"
03717     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
03718     if (!Brcc || !Brcc->isConditional())
03719       continue;
03720     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
03721     if (!Cmp || Cmp->getParent() != BB)
03722       continue;
03723     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
03724     if (!Zero || !Zero->isZero())
03725       continue;
03726     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
03727     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
03728       continue;
03729     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
03730     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
03731       continue;
03732     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
03733 
03734     // Push the "and; icmp" for any users that are conditional branches.
03735     // Since there can only be one branch use per BB, we don't need to keep
03736     // track of which BBs we insert into.
03737     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
03738          UI != E; ) {
03739       Use &TheUse = *UI;
03740       // Find brcc use.
03741       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
03742       ++UI;
03743       if (!BrccUser || !BrccUser->isConditional())
03744         continue;
03745       BasicBlock *UserBB = BrccUser->getParent();
03746       if (UserBB == BB) continue;
03747       DEBUG(dbgs() << "found Brcc use\n");
03748 
03749       // Sink the "and; icmp" to use.
03750       MadeChange = true;
03751       BinaryOperator *NewAnd =
03752         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
03753                                   BrccUser);
03754       CmpInst *NewCmp =
03755         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
03756                         "", BrccUser);
03757       TheUse = NewCmp;
03758       ++NumAndCmpsMoved;
03759       DEBUG(BrccUser->getParent()->dump());
03760     }
03761   }
03762   return MadeChange;
03763 }