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