]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/CodeGenPrepare.cpp
Make helper functions static.
[opencl/llvm.git] / lib / CodeGen / CodeGenPrepare.cpp
1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation. This works around limitations in it's
12 // basic-block-at-a-time approach. It should eventually be removed.
13 //
14 //===----------------------------------------------------------------------===//
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GetElementPtrTypeIterator.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/IR/ValueMap.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetLibraryInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/BuildLibCalls.h"
44 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 using namespace llvm;
47 using namespace llvm::PatternMatch;
49 #define DEBUG_TYPE "codegenprepare"
51 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
52 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
53 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
54 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
55                       "sunken Cmps");
56 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
57                        "of sunken Casts");
58 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
59                           "computations were sunk");
60 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
61 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
62 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
63 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
64 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
65 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
67 static cl::opt<bool> DisableBranchOpts(
68   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69   cl::desc("Disable branch optimizations in CodeGenPrepare"));
71 static cl::opt<bool> DisableSelectToBranch(
72   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73   cl::desc("Disable select to branch conversion."));
75 static cl::opt<bool> AddrSinkUsingGEPs(
76   "addr-sink-using-gep", cl::Hidden, cl::init(false),
77   cl::desc("Address sinking in CGP using GEPs."));
79 static cl::opt<bool> EnableAndCmpSinking(
80    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
81    cl::desc("Enable sinkinig and/cmp into branches."));
83 namespace {
84 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
85 typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
87   class CodeGenPrepare : public FunctionPass {
88     /// TLI - Keep a pointer of a TargetLowering to consult for determining
89     /// transformation profitability.
90     const TargetMachine *TM;
91     const TargetLowering *TLI;
92     const TargetLibraryInfo *TLInfo;
93     DominatorTree *DT;
95     /// CurInstIterator - As we scan instructions optimizing them, this is the
96     /// next instruction to optimize.  Xforms that can invalidate this should
97     /// update it.
98     BasicBlock::iterator CurInstIterator;
100     /// Keeps track of non-local addresses that have been sunk into a block.
101     /// This allows us to avoid inserting duplicate code for blocks with
102     /// multiple load/stores of the same address.
103     ValueMap<Value*, Value*> SunkAddrs;
105     /// Keeps track of all truncates inserted for the current function.
106     SetOfInstrs InsertedTruncsSet;
107     /// Keeps track of the type of the related instruction before their
108     /// promotion for the current function.
109     InstrToOrigTy PromotedInsts;
111     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
112     /// be updated.
113     bool ModifiedDT;
115     /// OptSize - True if optimizing for size.
116     bool OptSize;
118   public:
119     static char ID; // Pass identification, replacement for typeid
120     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
121       : FunctionPass(ID), TM(TM), TLI(nullptr) {
122         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
123       }
124     bool runOnFunction(Function &F) override;
126     const char *getPassName() const override { return "CodeGen Prepare"; }
128     void getAnalysisUsage(AnalysisUsage &AU) const override {
129       AU.addPreserved<DominatorTreeWrapperPass>();
130       AU.addRequired<TargetLibraryInfo>();
131     }
133   private:
134     bool EliminateFallThrough(Function &F);
135     bool EliminateMostlyEmptyBlocks(Function &F);
136     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
137     void EliminateMostlyEmptyBlock(BasicBlock *BB);
138     bool OptimizeBlock(BasicBlock &BB);
139     bool OptimizeInst(Instruction *I);
140     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
141     bool OptimizeInlineAsmInst(CallInst *CS);
142     bool OptimizeCallInst(CallInst *CI);
143     bool MoveExtToFormExtLoad(Instruction *I);
144     bool OptimizeExtUses(Instruction *I);
145     bool OptimizeSelectInst(SelectInst *SI);
146     bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
147     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
148     bool PlaceDbgValues(Function &F);
149     bool sinkAndCmp(Function &F);
150   };
153 char CodeGenPrepare::ID = 0;
154 static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
155   initializeTargetLibraryInfoPass(Registry);
156   PassInfo *PI = new PassInfo(
157       "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
158       PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
159       PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
160   Registry.registerPass(*PI, true);
161   return PI;
164 void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
165   CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
168 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
169   return new CodeGenPrepare(TM);
172 bool CodeGenPrepare::runOnFunction(Function &F) {
173   if (skipOptnoneFunction(F))
174     return false;
176   bool EverMadeChange = false;
177   // Clear per function information.
178   InsertedTruncsSet.clear();
179   PromotedInsts.clear();
181   ModifiedDT = false;
182   if (TM) TLI = TM->getTargetLowering();
183   TLInfo = &getAnalysis<TargetLibraryInfo>();
184   DominatorTreeWrapperPass *DTWP =
185       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
186   DT = DTWP ? &DTWP->getDomTree() : nullptr;
187   OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
188                                            Attribute::OptimizeForSize);
190   /// This optimization identifies DIV instructions that can be
191   /// profitably bypassed and carried out with a shorter, faster divide.
192   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
193     const DenseMap<unsigned int, unsigned int> &BypassWidths =
194        TLI->getBypassSlowDivWidths();
195     for (Function::iterator I = F.begin(); I != F.end(); I++)
196       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
197   }
199   // Eliminate blocks that contain only PHI nodes and an
200   // unconditional branch.
201   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
203   // llvm.dbg.value is far away from the value then iSel may not be able
204   // handle it properly. iSel will drop llvm.dbg.value if it can not
205   // find a node corresponding to the value.
206   EverMadeChange |= PlaceDbgValues(F);
208   // If there is a mask, compare against zero, and branch that can be combined
209   // into a single target instruction, push the mask and compare into branch
210   // users. Do this before OptimizeBlock -> OptimizeInst ->
211   // OptimizeCmpExpression, which perturbs the pattern being searched for.
212   if (!DisableBranchOpts)
213     EverMadeChange |= sinkAndCmp(F);
215   bool MadeChange = true;
216   while (MadeChange) {
217     MadeChange = false;
218     for (Function::iterator I = F.begin(); I != F.end(); ) {
219       BasicBlock *BB = I++;
220       MadeChange |= OptimizeBlock(*BB);
221     }
222     EverMadeChange |= MadeChange;
223   }
225   SunkAddrs.clear();
227   if (!DisableBranchOpts) {
228     MadeChange = false;
229     SmallPtrSet<BasicBlock*, 8> WorkList;
230     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
231       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
232       MadeChange |= ConstantFoldTerminator(BB, true);
233       if (!MadeChange) continue;
235       for (SmallVectorImpl<BasicBlock*>::iterator
236              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
237         if (pred_begin(*II) == pred_end(*II))
238           WorkList.insert(*II);
239     }
241     // Delete the dead blocks and any of their dead successors.
242     MadeChange |= !WorkList.empty();
243     while (!WorkList.empty()) {
244       BasicBlock *BB = *WorkList.begin();
245       WorkList.erase(BB);
246       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
248       DeleteDeadBlock(BB);
250       for (SmallVectorImpl<BasicBlock*>::iterator
251              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
252         if (pred_begin(*II) == pred_end(*II))
253           WorkList.insert(*II);
254     }
256     // Merge pairs of basic blocks with unconditional branches, connected by
257     // a single edge.
258     if (EverMadeChange || MadeChange)
259       MadeChange |= EliminateFallThrough(F);
261     if (MadeChange)
262       ModifiedDT = true;
263     EverMadeChange |= MadeChange;
264   }
266   if (ModifiedDT && DT)
267     DT->recalculate(F);
269   return EverMadeChange;
272 /// EliminateFallThrough - Merge basic blocks which are connected
273 /// by a single edge, where one of the basic blocks has a single successor
274 /// pointing to the other basic block, which has a single predecessor.
275 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
276   bool Changed = false;
277   // Scan all of the blocks in the function, except for the entry block.
278   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
279     BasicBlock *BB = I++;
280     // If the destination block has a single pred, then this is a trivial
281     // edge, just collapse it.
282     BasicBlock *SinglePred = BB->getSinglePredecessor();
284     // Don't merge if BB's address is taken.
285     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
287     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
288     if (Term && !Term->isConditional()) {
289       Changed = true;
290       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
291       // Remember if SinglePred was the entry block of the function.
292       // If so, we will need to move BB back to the entry position.
293       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
294       MergeBasicBlockIntoOnlyPred(BB, this);
296       if (isEntry && BB != &BB->getParent()->getEntryBlock())
297         BB->moveBefore(&BB->getParent()->getEntryBlock());
299       // We have erased a block. Update the iterator.
300       I = BB;
301     }
302   }
303   return Changed;
306 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
307 /// debug info directives, and an unconditional branch.  Passes before isel
308 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
309 /// isel.  Start by eliminating these blocks so we can split them the way we
310 /// want them.
311 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
312   bool MadeChange = false;
313   // Note that this intentionally skips the entry block.
314   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
315     BasicBlock *BB = I++;
317     // If this block doesn't end with an uncond branch, ignore it.
318     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
319     if (!BI || !BI->isUnconditional())
320       continue;
322     // If the instruction before the branch (skipping debug info) isn't a phi
323     // node, then other stuff is happening here.
324     BasicBlock::iterator BBI = BI;
325     if (BBI != BB->begin()) {
326       --BBI;
327       while (isa<DbgInfoIntrinsic>(BBI)) {
328         if (BBI == BB->begin())
329           break;
330         --BBI;
331       }
332       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
333         continue;
334     }
336     // Do not break infinite loops.
337     BasicBlock *DestBB = BI->getSuccessor(0);
338     if (DestBB == BB)
339       continue;
341     if (!CanMergeBlocks(BB, DestBB))
342       continue;
344     EliminateMostlyEmptyBlock(BB);
345     MadeChange = true;
346   }
347   return MadeChange;
350 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
351 /// single uncond branch between them, and BB contains no other non-phi
352 /// instructions.
353 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
354                                     const BasicBlock *DestBB) const {
355   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
356   // the successor.  If there are more complex condition (e.g. preheaders),
357   // don't mess around with them.
358   BasicBlock::const_iterator BBI = BB->begin();
359   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
360     for (const User *U : PN->users()) {
361       const Instruction *UI = cast<Instruction>(U);
362       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
363         return false;
364       // If User is inside DestBB block and it is a PHINode then check
365       // incoming value. If incoming value is not from BB then this is
366       // a complex condition (e.g. preheaders) we want to avoid here.
367       if (UI->getParent() == DestBB) {
368         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
369           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
370             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
371             if (Insn && Insn->getParent() == BB &&
372                 Insn->getParent() != UPN->getIncomingBlock(I))
373               return false;
374           }
375       }
376     }
377   }
379   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
380   // and DestBB may have conflicting incoming values for the block.  If so, we
381   // can't merge the block.
382   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
383   if (!DestBBPN) return true;  // no conflict.
385   // Collect the preds of BB.
386   SmallPtrSet<const BasicBlock*, 16> BBPreds;
387   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
388     // It is faster to get preds from a PHI than with pred_iterator.
389     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
390       BBPreds.insert(BBPN->getIncomingBlock(i));
391   } else {
392     BBPreds.insert(pred_begin(BB), pred_end(BB));
393   }
395   // Walk the preds of DestBB.
396   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
397     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
398     if (BBPreds.count(Pred)) {   // Common predecessor?
399       BBI = DestBB->begin();
400       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
401         const Value *V1 = PN->getIncomingValueForBlock(Pred);
402         const Value *V2 = PN->getIncomingValueForBlock(BB);
404         // If V2 is a phi node in BB, look up what the mapped value will be.
405         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
406           if (V2PN->getParent() == BB)
407             V2 = V2PN->getIncomingValueForBlock(Pred);
409         // If there is a conflict, bail out.
410         if (V1 != V2) return false;
411       }
412     }
413   }
415   return true;
419 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
420 /// an unconditional branch in it.
421 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
422   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
423   BasicBlock *DestBB = BI->getSuccessor(0);
425   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
427   // If the destination block has a single pred, then this is a trivial edge,
428   // just collapse it.
429   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
430     if (SinglePred != DestBB) {
431       // Remember if SinglePred was the entry block of the function.  If so, we
432       // will need to move BB back to the entry position.
433       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
434       MergeBasicBlockIntoOnlyPred(DestBB, this);
436       if (isEntry && BB != &BB->getParent()->getEntryBlock())
437         BB->moveBefore(&BB->getParent()->getEntryBlock());
439       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
440       return;
441     }
442   }
444   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
445   // to handle the new incoming edges it is about to have.
446   PHINode *PN;
447   for (BasicBlock::iterator BBI = DestBB->begin();
448        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
449     // Remove the incoming value for BB, and remember it.
450     Value *InVal = PN->removeIncomingValue(BB, false);
452     // Two options: either the InVal is a phi node defined in BB or it is some
453     // value that dominates BB.
454     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
455     if (InValPhi && InValPhi->getParent() == BB) {
456       // Add all of the input values of the input PHI as inputs of this phi.
457       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
458         PN->addIncoming(InValPhi->getIncomingValue(i),
459                         InValPhi->getIncomingBlock(i));
460     } else {
461       // Otherwise, add one instance of the dominating value for each edge that
462       // we will be adding.
463       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
464         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
465           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
466       } else {
467         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
468           PN->addIncoming(InVal, *PI);
469       }
470     }
471   }
473   // The PHIs are now updated, change everything that refers to BB to use
474   // DestBB and remove BB.
475   BB->replaceAllUsesWith(DestBB);
476   if (DT && !ModifiedDT) {
477     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
478     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
479     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
480     DT->changeImmediateDominator(DestBB, NewIDom);
481     DT->eraseNode(BB);
482   }
483   BB->eraseFromParent();
484   ++NumBlocksElim;
486   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
489 /// SinkCast - Sink the specified cast instruction into its user blocks
490 static bool SinkCast(CastInst *CI) {
491   BasicBlock *DefBB = CI->getParent();
493   /// InsertedCasts - Only insert a cast in each block once.
494   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
496   bool MadeChange = false;
497   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
498        UI != E; ) {
499     Use &TheUse = UI.getUse();
500     Instruction *User = cast<Instruction>(*UI);
502     // Figure out which BB this cast is used in.  For PHI's this is the
503     // appropriate predecessor block.
504     BasicBlock *UserBB = User->getParent();
505     if (PHINode *PN = dyn_cast<PHINode>(User)) {
506       UserBB = PN->getIncomingBlock(TheUse);
507     }
509     // Preincrement use iterator so we don't invalidate it.
510     ++UI;
512     // If this user is in the same block as the cast, don't change the cast.
513     if (UserBB == DefBB) continue;
515     // If we have already inserted a cast into this block, use it.
516     CastInst *&InsertedCast = InsertedCasts[UserBB];
518     if (!InsertedCast) {
519       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
520       InsertedCast =
521         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
522                          InsertPt);
523       MadeChange = true;
524     }
526     // Replace a use of the cast with a use of the new cast.
527     TheUse = InsertedCast;
528     ++NumCastUses;
529   }
531   // If we removed all uses, nuke the cast.
532   if (CI->use_empty()) {
533     CI->eraseFromParent();
534     MadeChange = true;
535   }
537   return MadeChange;
540 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
541 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
542 /// sink it into user blocks to reduce the number of virtual
543 /// registers that must be created and coalesced.
544 ///
545 /// Return true if any changes are made.
546 ///
547 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
548   // If this is a noop copy,
549   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
550   EVT DstVT = TLI.getValueType(CI->getType());
552   // This is an fp<->int conversion?
553   if (SrcVT.isInteger() != DstVT.isInteger())
554     return false;
556   // If this is an extension, it will be a zero or sign extension, which
557   // isn't a noop.
558   if (SrcVT.bitsLT(DstVT)) return false;
560   // If these values will be promoted, find out what they will be promoted
561   // to.  This helps us consider truncates on PPC as noop copies when they
562   // are.
563   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
564       TargetLowering::TypePromoteInteger)
565     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
566   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
567       TargetLowering::TypePromoteInteger)
568     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
570   // If, after promotion, these are the same types, this is a noop copy.
571   if (SrcVT != DstVT)
572     return false;
574   return SinkCast(CI);
577 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
578 /// the number of virtual registers that must be created and coalesced.  This is
579 /// a clear win except on targets with multiple condition code registers
580 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
581 ///
582 /// Return true if any changes are made.
583 static bool OptimizeCmpExpression(CmpInst *CI) {
584   BasicBlock *DefBB = CI->getParent();
586   /// InsertedCmp - Only insert a cmp in each block once.
587   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
589   bool MadeChange = false;
590   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
591        UI != E; ) {
592     Use &TheUse = UI.getUse();
593     Instruction *User = cast<Instruction>(*UI);
595     // Preincrement use iterator so we don't invalidate it.
596     ++UI;
598     // Don't bother for PHI nodes.
599     if (isa<PHINode>(User))
600       continue;
602     // Figure out which BB this cmp is used in.
603     BasicBlock *UserBB = User->getParent();
605     // If this user is in the same block as the cmp, don't change the cmp.
606     if (UserBB == DefBB) continue;
608     // If we have already inserted a cmp into this block, use it.
609     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
611     if (!InsertedCmp) {
612       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
613       InsertedCmp =
614         CmpInst::Create(CI->getOpcode(),
615                         CI->getPredicate(),  CI->getOperand(0),
616                         CI->getOperand(1), "", InsertPt);
617       MadeChange = true;
618     }
620     // Replace a use of the cmp with a use of the new cmp.
621     TheUse = InsertedCmp;
622     ++NumCmpUses;
623   }
625   // If we removed all uses, nuke the cmp.
626   if (CI->use_empty())
627     CI->eraseFromParent();
629   return MadeChange;
632 /// isExtractBitsCandidateUse - Check if the candidates could
633 /// be combined with shift instruction, which includes:
634 /// 1. Truncate instruction
635 /// 2. And instruction and the imm is a mask of the low bits:
636 /// imm & (imm+1) == 0
637 static bool isExtractBitsCandidateUse(Instruction *User) {
638   if (!isa<TruncInst>(User)) {
639     if (User->getOpcode() != Instruction::And ||
640         !isa<ConstantInt>(User->getOperand(1)))
641       return false;
643     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
645     if ((Cimm & (Cimm + 1)).getBoolValue())
646       return false;
647   }
648   return true;
651 /// SinkShiftAndTruncate - sink both shift and truncate instruction
652 /// to the use of truncate's BB.
653 static bool
654 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
655                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
656                      const TargetLowering &TLI) {
657   BasicBlock *UserBB = User->getParent();
658   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
659   TruncInst *TruncI = dyn_cast<TruncInst>(User);
660   bool MadeChange = false;
662   for (Value::user_iterator TruncUI = TruncI->user_begin(),
663                             TruncE = TruncI->user_end();
664        TruncUI != TruncE;) {
666     Use &TruncTheUse = TruncUI.getUse();
667     Instruction *TruncUser = cast<Instruction>(*TruncUI);
668     // Preincrement use iterator so we don't invalidate it.
670     ++TruncUI;
672     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
673     if (!ISDOpcode)
674       continue;
676     // If the use is actually a legal node, there will not be an implicit
677     // truncate.
678     if (TLI.isOperationLegalOrCustom(ISDOpcode,
679                                      EVT::getEVT(TruncUser->getType())))
680       continue;
682     // Don't bother for PHI nodes.
683     if (isa<PHINode>(TruncUser))
684       continue;
686     BasicBlock *TruncUserBB = TruncUser->getParent();
688     if (UserBB == TruncUserBB)
689       continue;
691     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
692     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
694     if (!InsertedShift && !InsertedTrunc) {
695       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
696       // Sink the shift
697       if (ShiftI->getOpcode() == Instruction::AShr)
698         InsertedShift =
699             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
700       else
701         InsertedShift =
702             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
704       // Sink the trunc
705       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
706       TruncInsertPt++;
708       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
709                                        TruncI->getType(), "", TruncInsertPt);
711       MadeChange = true;
713       TruncTheUse = InsertedTrunc;
714     }
715   }
716   return MadeChange;
719 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
720 /// the uses could potentially be combined with this shift instruction and
721 /// generate BitExtract instruction. It will only be applied if the architecture
722 /// supports BitExtract instruction. Here is an example:
723 /// BB1:
724 ///   %x.extract.shift = lshr i64 %arg1, 32
725 /// BB2:
726 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
727 /// ==>
728 ///
729 /// BB2:
730 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
731 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
732 ///
733 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
734 /// instruction.
735 /// Return true if any changes are made.
736 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
737                                 const TargetLowering &TLI) {
738   BasicBlock *DefBB = ShiftI->getParent();
740   /// Only insert instructions in each block once.
741   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
743   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
745   bool MadeChange = false;
746   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
747        UI != E;) {
748     Use &TheUse = UI.getUse();
749     Instruction *User = cast<Instruction>(*UI);
750     // Preincrement use iterator so we don't invalidate it.
751     ++UI;
753     // Don't bother for PHI nodes.
754     if (isa<PHINode>(User))
755       continue;
757     if (!isExtractBitsCandidateUse(User))
758       continue;
760     BasicBlock *UserBB = User->getParent();
762     if (UserBB == DefBB) {
763       // If the shift and truncate instruction are in the same BB. The use of
764       // the truncate(TruncUse) may still introduce another truncate if not
765       // legal. In this case, we would like to sink both shift and truncate
766       // instruction to the BB of TruncUse.
767       // for example:
768       // BB1:
769       // i64 shift.result = lshr i64 opnd, imm
770       // trunc.result = trunc shift.result to i16
771       //
772       // BB2:
773       //   ----> We will have an implicit truncate here if the architecture does
774       //   not have i16 compare.
775       // cmp i16 trunc.result, opnd2
776       //
777       if (isa<TruncInst>(User) && shiftIsLegal
778           // If the type of the truncate is legal, no trucate will be
779           // introduced in other basic blocks.
780           && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
781         MadeChange =
782             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
784       continue;
785     }
786     // If we have already inserted a shift into this block, use it.
787     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
789     if (!InsertedShift) {
790       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
792       if (ShiftI->getOpcode() == Instruction::AShr)
793         InsertedShift =
794             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
795       else
796         InsertedShift =
797             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
799       MadeChange = true;
800     }
802     // Replace a use of the shift with a use of the new shift.
803     TheUse = InsertedShift;
804   }
806   // If we removed all uses, nuke the shift.
807   if (ShiftI->use_empty())
808     ShiftI->eraseFromParent();
810   return MadeChange;
813 namespace {
814 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
815 protected:
816   void replaceCall(Value *With) override {
817     CI->replaceAllUsesWith(With);
818     CI->eraseFromParent();
819   }
820   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
821       if (ConstantInt *SizeCI =
822                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
823         return SizeCI->isAllOnesValue();
824     return false;
825   }
826 };
827 } // end anonymous namespace
829 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
830   BasicBlock *BB = CI->getParent();
832   // Lower inline assembly if we can.
833   // If we found an inline asm expession, and if the target knows how to
834   // lower it to normal LLVM code, do so now.
835   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
836     if (TLI->ExpandInlineAsm(CI)) {
837       // Avoid invalidating the iterator.
838       CurInstIterator = BB->begin();
839       // Avoid processing instructions out of order, which could cause
840       // reuse before a value is defined.
841       SunkAddrs.clear();
842       return true;
843     }
844     // Sink address computing for memory operands into the block.
845     if (OptimizeInlineAsmInst(CI))
846       return true;
847   }
849   // Lower all uses of llvm.objectsize.*
850   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
851   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
852     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
853     Type *ReturnTy = CI->getType();
854     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
856     // Substituting this can cause recursive simplifications, which can
857     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
858     // happens.
859     WeakVH IterHandle(CurInstIterator);
861     replaceAndRecursivelySimplify(CI, RetVal,
862                                   TLI ? TLI->getDataLayout() : nullptr,
863                                   TLInfo, ModifiedDT ? nullptr : DT);
865     // If the iterator instruction was recursively deleted, start over at the
866     // start of the block.
867     if (IterHandle != CurInstIterator) {
868       CurInstIterator = BB->begin();
869       SunkAddrs.clear();
870     }
871     return true;
872   }
874   if (II && TLI) {
875     SmallVector<Value*, 2> PtrOps;
876     Type *AccessTy;
877     if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
878       while (!PtrOps.empty())
879         if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
880           return true;
881   }
883   // From here on out we're working with named functions.
884   if (!CI->getCalledFunction()) return false;
886   // We'll need DataLayout from here on out.
887   const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
888   if (!TD) return false;
890   // Lower all default uses of _chk calls.  This is very similar
891   // to what InstCombineCalls does, but here we are only lowering calls
892   // that have the default "don't know" as the objectsize.  Anything else
893   // should be left alone.
894   CodeGenPrepareFortifiedLibCalls Simplifier;
895   return Simplifier.fold(CI, TD, TLInfo);
898 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
899 /// instructions to the predecessor to enable tail call optimizations. The
900 /// case it is currently looking for is:
901 /// @code
902 /// bb0:
903 ///   %tmp0 = tail call i32 @f0()
904 ///   br label %return
905 /// bb1:
906 ///   %tmp1 = tail call i32 @f1()
907 ///   br label %return
908 /// bb2:
909 ///   %tmp2 = tail call i32 @f2()
910 ///   br label %return
911 /// return:
912 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
913 ///   ret i32 %retval
914 /// @endcode
915 ///
916 /// =>
917 ///
918 /// @code
919 /// bb0:
920 ///   %tmp0 = tail call i32 @f0()
921 ///   ret i32 %tmp0
922 /// bb1:
923 ///   %tmp1 = tail call i32 @f1()
924 ///   ret i32 %tmp1
925 /// bb2:
926 ///   %tmp2 = tail call i32 @f2()
927 ///   ret i32 %tmp2
928 /// @endcode
929 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
930   if (!TLI)
931     return false;
933   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
934   if (!RI)
935     return false;
937   PHINode *PN = nullptr;
938   BitCastInst *BCI = nullptr;
939   Value *V = RI->getReturnValue();
940   if (V) {
941     BCI = dyn_cast<BitCastInst>(V);
942     if (BCI)
943       V = BCI->getOperand(0);
945     PN = dyn_cast<PHINode>(V);
946     if (!PN)
947       return false;
948   }
950   if (PN && PN->getParent() != BB)
951     return false;
953   // It's not safe to eliminate the sign / zero extension of the return value.
954   // See llvm::isInTailCallPosition().
955   const Function *F = BB->getParent();
956   AttributeSet CallerAttrs = F->getAttributes();
957   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
958       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
959     return false;
961   // Make sure there are no instructions between the PHI and return, or that the
962   // return is the first instruction in the block.
963   if (PN) {
964     BasicBlock::iterator BI = BB->begin();
965     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
966     if (&*BI == BCI)
967       // Also skip over the bitcast.
968       ++BI;
969     if (&*BI != RI)
970       return false;
971   } else {
972     BasicBlock::iterator BI = BB->begin();
973     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
974     if (&*BI != RI)
975       return false;
976   }
978   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
979   /// call.
980   SmallVector<CallInst*, 4> TailCalls;
981   if (PN) {
982     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
983       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
984       // Make sure the phi value is indeed produced by the tail call.
985       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
986           TLI->mayBeEmittedAsTailCall(CI))
987         TailCalls.push_back(CI);
988     }
989   } else {
990     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
991     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
992       if (!VisitedBBs.insert(*PI))
993         continue;
995       BasicBlock::InstListType &InstList = (*PI)->getInstList();
996       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
997       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
998       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
999       if (RI == RE)
1000         continue;
1002       CallInst *CI = dyn_cast<CallInst>(&*RI);
1003       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
1004         TailCalls.push_back(CI);
1005     }
1006   }
1008   bool Changed = false;
1009   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1010     CallInst *CI = TailCalls[i];
1011     CallSite CS(CI);
1013     // Conservatively require the attributes of the call to match those of the
1014     // return. Ignore noalias because it doesn't affect the call sequence.
1015     AttributeSet CalleeAttrs = CS.getAttributes();
1016     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1017           removeAttribute(Attribute::NoAlias) !=
1018         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1019           removeAttribute(Attribute::NoAlias))
1020       continue;
1022     // Make sure the call instruction is followed by an unconditional branch to
1023     // the return block.
1024     BasicBlock *CallBB = CI->getParent();
1025     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1026     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1027       continue;
1029     // Duplicate the return into CallBB.
1030     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1031     ModifiedDT = Changed = true;
1032     ++NumRetsDup;
1033   }
1035   // If we eliminated all predecessors of the block, delete the block now.
1036   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1037     BB->eraseFromParent();
1039   return Changed;
1042 //===----------------------------------------------------------------------===//
1043 // Memory Optimization
1044 //===----------------------------------------------------------------------===//
1046 namespace {
1048 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1049 /// which holds actual Value*'s for register values.
1050 struct ExtAddrMode : public TargetLowering::AddrMode {
1051   Value *BaseReg;
1052   Value *ScaledReg;
1053   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1054   void print(raw_ostream &OS) const;
1055   void dump() const;
1057   bool operator==(const ExtAddrMode& O) const {
1058     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1059            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1060            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1061   }
1062 };
1064 #ifndef NDEBUG
1065 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1066   AM.print(OS);
1067   return OS;
1069 #endif
1071 void ExtAddrMode::print(raw_ostream &OS) const {
1072   bool NeedPlus = false;
1073   OS << "[";
1074   if (BaseGV) {
1075     OS << (NeedPlus ? " + " : "")
1076        << "GV:";
1077     BaseGV->printAsOperand(OS, /*PrintType=*/false);
1078     NeedPlus = true;
1079   }
1081   if (BaseOffs)
1082     OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
1084   if (BaseReg) {
1085     OS << (NeedPlus ? " + " : "")
1086        << "Base:";
1087     BaseReg->printAsOperand(OS, /*PrintType=*/false);
1088     NeedPlus = true;
1089   }
1090   if (Scale) {
1091     OS << (NeedPlus ? " + " : "")
1092        << Scale << "*";
1093     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1094   }
1096   OS << ']';
1099 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1100 void ExtAddrMode::dump() const {
1101   print(dbgs());
1102   dbgs() << '\n';
1104 #endif
1106 /// \brief This class provides transaction based operation on the IR.
1107 /// Every change made through this class is recorded in the internal state and
1108 /// can be undone (rollback) until commit is called.
1109 class TypePromotionTransaction {
1111   /// \brief This represents the common interface of the individual transaction.
1112   /// Each class implements the logic for doing one specific modification on
1113   /// the IR via the TypePromotionTransaction.
1114   class TypePromotionAction {
1115   protected:
1116     /// The Instruction modified.
1117     Instruction *Inst;
1119   public:
1120     /// \brief Constructor of the action.
1121     /// The constructor performs the related action on the IR.
1122     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1124     virtual ~TypePromotionAction() {}
1126     /// \brief Undo the modification done by this action.
1127     /// When this method is called, the IR must be in the same state as it was
1128     /// before this action was applied.
1129     /// \pre Undoing the action works if and only if the IR is in the exact same
1130     /// state as it was directly after this action was applied.
1131     virtual void undo() = 0;
1133     /// \brief Advocate every change made by this action.
1134     /// When the results on the IR of the action are to be kept, it is important
1135     /// to call this function, otherwise hidden information may be kept forever.
1136     virtual void commit() {
1137       // Nothing to be done, this action is not doing anything.
1138     }
1139   };
1141   /// \brief Utility to remember the position of an instruction.
1142   class InsertionHandler {
1143     /// Position of an instruction.
1144     /// Either an instruction:
1145     /// - Is the first in a basic block: BB is used.
1146     /// - Has a previous instructon: PrevInst is used.
1147     union {
1148       Instruction *PrevInst;
1149       BasicBlock *BB;
1150     } Point;
1151     /// Remember whether or not the instruction had a previous instruction.
1152     bool HasPrevInstruction;
1154   public:
1155     /// \brief Record the position of \p Inst.
1156     InsertionHandler(Instruction *Inst) {
1157       BasicBlock::iterator It = Inst;
1158       HasPrevInstruction = (It != (Inst->getParent()->begin()));
1159       if (HasPrevInstruction)
1160         Point.PrevInst = --It;
1161       else
1162         Point.BB = Inst->getParent();
1163     }
1165     /// \brief Insert \p Inst at the recorded position.
1166     void insert(Instruction *Inst) {
1167       if (HasPrevInstruction) {
1168         if (Inst->getParent())
1169           Inst->removeFromParent();
1170         Inst->insertAfter(Point.PrevInst);
1171       } else {
1172         Instruction *Position = Point.BB->getFirstInsertionPt();
1173         if (Inst->getParent())
1174           Inst->moveBefore(Position);
1175         else
1176           Inst->insertBefore(Position);
1177       }
1178     }
1179   };
1181   /// \brief Move an instruction before another.
1182   class InstructionMoveBefore : public TypePromotionAction {
1183     /// Original position of the instruction.
1184     InsertionHandler Position;
1186   public:
1187     /// \brief Move \p Inst before \p Before.
1188     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1189         : TypePromotionAction(Inst), Position(Inst) {
1190       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1191       Inst->moveBefore(Before);
1192     }
1194     /// \brief Move the instruction back to its original position.
1195     void undo() override {
1196       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1197       Position.insert(Inst);
1198     }
1199   };
1201   /// \brief Set the operand of an instruction with a new value.
1202   class OperandSetter : public TypePromotionAction {
1203     /// Original operand of the instruction.
1204     Value *Origin;
1205     /// Index of the modified instruction.
1206     unsigned Idx;
1208   public:
1209     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1210     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1211         : TypePromotionAction(Inst), Idx(Idx) {
1212       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1213                    << "for:" << *Inst << "\n"
1214                    << "with:" << *NewVal << "\n");
1215       Origin = Inst->getOperand(Idx);
1216       Inst->setOperand(Idx, NewVal);
1217     }
1219     /// \brief Restore the original value of the instruction.
1220     void undo() override {
1221       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1222                    << "for: " << *Inst << "\n"
1223                    << "with: " << *Origin << "\n");
1224       Inst->setOperand(Idx, Origin);
1225     }
1226   };
1228   /// \brief Hide the operands of an instruction.
1229   /// Do as if this instruction was not using any of its operands.
1230   class OperandsHider : public TypePromotionAction {
1231     /// The list of original operands.
1232     SmallVector<Value *, 4> OriginalValues;
1234   public:
1235     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1236     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1237       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1238       unsigned NumOpnds = Inst->getNumOperands();
1239       OriginalValues.reserve(NumOpnds);
1240       for (unsigned It = 0; It < NumOpnds; ++It) {
1241         // Save the current operand.
1242         Value *Val = Inst->getOperand(It);
1243         OriginalValues.push_back(Val);
1244         // Set a dummy one.
1245         // We could use OperandSetter here, but that would implied an overhead
1246         // that we are not willing to pay.
1247         Inst->setOperand(It, UndefValue::get(Val->getType()));
1248       }
1249     }
1251     /// \brief Restore the original list of uses.
1252     void undo() override {
1253       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1254       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1255         Inst->setOperand(It, OriginalValues[It]);
1256     }
1257   };
1259   /// \brief Build a truncate instruction.
1260   class TruncBuilder : public TypePromotionAction {
1261   public:
1262     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1263     /// result.
1264     /// trunc Opnd to Ty.
1265     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1266       IRBuilder<> Builder(Opnd);
1267       Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1268       DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1269     }
1271     /// \brief Get the built instruction.
1272     Instruction *getBuiltInstruction() { return Inst; }
1274     /// \brief Remove the built instruction.
1275     void undo() override {
1276       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1277       Inst->eraseFromParent();
1278     }
1279   };
1281   /// \brief Build a sign extension instruction.
1282   class SExtBuilder : public TypePromotionAction {
1283   public:
1284     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1285     /// result.
1286     /// sext Opnd to Ty.
1287     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1288         : TypePromotionAction(Inst) {
1289       IRBuilder<> Builder(InsertPt);
1290       Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1291       DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1292     }
1294     /// \brief Get the built instruction.
1295     Instruction *getBuiltInstruction() { return Inst; }
1297     /// \brief Remove the built instruction.
1298     void undo() override {
1299       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1300       Inst->eraseFromParent();
1301     }
1302   };
1304   /// \brief Mutate an instruction to another type.
1305   class TypeMutator : public TypePromotionAction {
1306     /// Record the original type.
1307     Type *OrigTy;
1309   public:
1310     /// \brief Mutate the type of \p Inst into \p NewTy.
1311     TypeMutator(Instruction *Inst, Type *NewTy)
1312         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1313       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1314                    << "\n");
1315       Inst->mutateType(NewTy);
1316     }
1318     /// \brief Mutate the instruction back to its original type.
1319     void undo() override {
1320       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1321                    << "\n");
1322       Inst->mutateType(OrigTy);
1323     }
1324   };
1326   /// \brief Replace the uses of an instruction by another instruction.
1327   class UsesReplacer : public TypePromotionAction {
1328     /// Helper structure to keep track of the replaced uses.
1329     struct InstructionAndIdx {
1330       /// The instruction using the instruction.
1331       Instruction *Inst;
1332       /// The index where this instruction is used for Inst.
1333       unsigned Idx;
1334       InstructionAndIdx(Instruction *Inst, unsigned Idx)
1335           : Inst(Inst), Idx(Idx) {}
1336     };
1338     /// Keep track of the original uses (pair Instruction, Index).
1339     SmallVector<InstructionAndIdx, 4> OriginalUses;
1340     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1342   public:
1343     /// \brief Replace all the use of \p Inst by \p New.
1344     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1345       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1346                    << "\n");
1347       // Record the original uses.
1348       for (Use &U : Inst->uses()) {
1349         Instruction *UserI = cast<Instruction>(U.getUser());
1350         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1351       }
1352       // Now, we can replace the uses.
1353       Inst->replaceAllUsesWith(New);
1354     }
1356     /// \brief Reassign the original uses of Inst to Inst.
1357     void undo() override {
1358       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1359       for (use_iterator UseIt = OriginalUses.begin(),
1360                         EndIt = OriginalUses.end();
1361            UseIt != EndIt; ++UseIt) {
1362         UseIt->Inst->setOperand(UseIt->Idx, Inst);
1363       }
1364     }
1365   };
1367   /// \brief Remove an instruction from the IR.
1368   class InstructionRemover : public TypePromotionAction {
1369     /// Original position of the instruction.
1370     InsertionHandler Inserter;
1371     /// Helper structure to hide all the link to the instruction. In other
1372     /// words, this helps to do as if the instruction was removed.
1373     OperandsHider Hider;
1374     /// Keep track of the uses replaced, if any.
1375     UsesReplacer *Replacer;
1377   public:
1378     /// \brief Remove all reference of \p Inst and optinally replace all its
1379     /// uses with New.
1380     /// \pre If !Inst->use_empty(), then New != nullptr
1381     InstructionRemover(Instruction *Inst, Value *New = nullptr)
1382         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1383           Replacer(nullptr) {
1384       if (New)
1385         Replacer = new UsesReplacer(Inst, New);
1386       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1387       Inst->removeFromParent();
1388     }
1390     ~InstructionRemover() { delete Replacer; }
1392     /// \brief Really remove the instruction.
1393     void commit() override { delete Inst; }
1395     /// \brief Resurrect the instruction and reassign it to the proper uses if
1396     /// new value was provided when build this action.
1397     void undo() override {
1398       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1399       Inserter.insert(Inst);
1400       if (Replacer)
1401         Replacer->undo();
1402       Hider.undo();
1403     }
1404   };
1406 public:
1407   /// Restoration point.
1408   /// The restoration point is a pointer to an action instead of an iterator
1409   /// because the iterator may be invalidated but not the pointer.
1410   typedef const TypePromotionAction *ConstRestorationPt;
1411   /// Advocate every changes made in that transaction.
1412   void commit();
1413   /// Undo all the changes made after the given point.
1414   void rollback(ConstRestorationPt Point);
1415   /// Get the current restoration point.
1416   ConstRestorationPt getRestorationPoint() const;
1418   /// \name API for IR modification with state keeping to support rollback.
1419   /// @{
1420   /// Same as Instruction::setOperand.
1421   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1422   /// Same as Instruction::eraseFromParent.
1423   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
1424   /// Same as Value::replaceAllUsesWith.
1425   void replaceAllUsesWith(Instruction *Inst, Value *New);
1426   /// Same as Value::mutateType.
1427   void mutateType(Instruction *Inst, Type *NewTy);
1428   /// Same as IRBuilder::createTrunc.
1429   Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1430   /// Same as IRBuilder::createSExt.
1431   Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1432   /// Same as Instruction::moveBefore.
1433   void moveBefore(Instruction *Inst, Instruction *Before);
1434   /// @}
1436 private:
1437   /// The ordered list of actions made so far.
1438   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1439   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
1440 };
1442 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1443                                           Value *NewVal) {
1444   Actions.push_back(
1445       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
1448 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1449                                                 Value *NewVal) {
1450   Actions.push_back(
1451       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
1454 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1455                                                   Value *New) {
1456   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
1459 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1460   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
1463 Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1464                                                    Type *Ty) {
1465   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1466   Instruction *I = Ptr->getBuiltInstruction();
1467   Actions.push_back(std::move(Ptr));
1468   return I;
1471 Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1472                                                   Value *Opnd, Type *Ty) {
1473   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1474   Instruction *I = Ptr->getBuiltInstruction();
1475   Actions.push_back(std::move(Ptr));
1476   return I;
1479 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1480                                           Instruction *Before) {
1481   Actions.push_back(
1482       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
1485 TypePromotionTransaction::ConstRestorationPt
1486 TypePromotionTransaction::getRestorationPoint() const {
1487   return !Actions.empty() ? Actions.back().get() : nullptr;
1490 void TypePromotionTransaction::commit() {
1491   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1492        ++It)
1493     (*It)->commit();
1494   Actions.clear();
1497 void TypePromotionTransaction::rollback(
1498     TypePromotionTransaction::ConstRestorationPt Point) {
1499   while (!Actions.empty() && Point != Actions.back().get()) {
1500     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
1501     Curr->undo();
1502   }
1505 /// \brief A helper class for matching addressing modes.
1506 ///
1507 /// This encapsulates the logic for matching the target-legal addressing modes.
1508 class AddressingModeMatcher {
1509   SmallVectorImpl<Instruction*> &AddrModeInsts;
1510   const TargetLowering &TLI;
1512   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1513   /// the memory instruction that we're computing this address for.
1514   Type *AccessTy;
1515   Instruction *MemoryInst;
1517   /// AddrMode - This is the addressing mode that we're building up.  This is
1518   /// part of the return value of this addressing mode matching stuff.
1519   ExtAddrMode &AddrMode;
1521   /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1522   const SetOfInstrs &InsertedTruncs;
1523   /// A map from the instructions to their type before promotion.
1524   InstrToOrigTy &PromotedInsts;
1525   /// The ongoing transaction where every action should be registered.
1526   TypePromotionTransaction &TPT;
1528   /// IgnoreProfitability - This is set to true when we should not do
1529   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
1530   /// always returns true.
1531   bool IgnoreProfitability;
1533   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1534                         const TargetLowering &T, Type *AT,
1535                         Instruction *MI, ExtAddrMode &AM,
1536                         const SetOfInstrs &InsertedTruncs,
1537                         InstrToOrigTy &PromotedInsts,
1538                         TypePromotionTransaction &TPT)
1539       : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1540         InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1541     IgnoreProfitability = false;
1542   }
1543 public:
1545   /// Match - Find the maximal addressing mode that a load/store of V can fold,
1546   /// give an access type of AccessTy.  This returns a list of involved
1547   /// instructions in AddrModeInsts.
1548   /// \p InsertedTruncs The truncate instruction inserted by other
1549   /// CodeGenPrepare
1550   /// optimizations.
1551   /// \p PromotedInsts maps the instructions to their type before promotion.
1552   /// \p The ongoing transaction where every action should be registered.
1553   static ExtAddrMode Match(Value *V, Type *AccessTy,
1554                            Instruction *MemoryInst,
1555                            SmallVectorImpl<Instruction*> &AddrModeInsts,
1556                            const TargetLowering &TLI,
1557                            const SetOfInstrs &InsertedTruncs,
1558                            InstrToOrigTy &PromotedInsts,
1559                            TypePromotionTransaction &TPT) {
1560     ExtAddrMode Result;
1562     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1563                                          MemoryInst, Result, InsertedTruncs,
1564                                          PromotedInsts, TPT).MatchAddr(V, 0);
1565     (void)Success; assert(Success && "Couldn't select *anything*?");
1566     return Result;
1567   }
1568 private:
1569   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1570   bool MatchAddr(Value *V, unsigned Depth);
1571   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1572                           bool *MovedAway = nullptr);
1573   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1574                                             ExtAddrMode &AMBefore,
1575                                             ExtAddrMode &AMAfter);
1576   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1577   bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1578                              Value *PromotedOperand) const;
1579 };
1581 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1582 /// Return true and update AddrMode if this addr mode is legal for the target,
1583 /// false if not.
1584 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1585                                              unsigned Depth) {
1586   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1587   // mode.  Just process that directly.
1588   if (Scale == 1)
1589     return MatchAddr(ScaleReg, Depth);
1591   // If the scale is 0, it takes nothing to add this.
1592   if (Scale == 0)
1593     return true;
1595   // If we already have a scale of this value, we can add to it, otherwise, we
1596   // need an available scale field.
1597   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1598     return false;
1600   ExtAddrMode TestAddrMode = AddrMode;
1602   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
1603   // [A+B + A*7] -> [B+A*8].
1604   TestAddrMode.Scale += Scale;
1605   TestAddrMode.ScaledReg = ScaleReg;
1607   // If the new address isn't legal, bail out.
1608   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1609     return false;
1611   // It was legal, so commit it.
1612   AddrMode = TestAddrMode;
1614   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
1615   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
1616   // X*Scale + C*Scale to addr mode.
1617   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
1618   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
1619       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1620     TestAddrMode.ScaledReg = AddLHS;
1621     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1623     // If this addressing mode is legal, commit it and remember that we folded
1624     // this instruction.
1625     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1626       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1627       AddrMode = TestAddrMode;
1628       return true;
1629     }
1630   }
1632   // Otherwise, not (x+c)*scale, just return what we have.
1633   return true;
1636 /// MightBeFoldableInst - This is a little filter, which returns true if an
1637 /// addressing computation involving I might be folded into a load/store
1638 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
1639 /// the set of instructions that MatchOperationAddr can.
1640 static bool MightBeFoldableInst(Instruction *I) {
1641   switch (I->getOpcode()) {
1642   case Instruction::BitCast:
1643     // Don't touch identity bitcasts.
1644     if (I->getType() == I->getOperand(0)->getType())
1645       return false;
1646     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1647   case Instruction::PtrToInt:
1648     // PtrToInt is always a noop, as we know that the int type is pointer sized.
1649     return true;
1650   case Instruction::IntToPtr:
1651     // We know the input is intptr_t, so this is foldable.
1652     return true;
1653   case Instruction::Add:
1654     return true;
1655   case Instruction::Mul:
1656   case Instruction::Shl:
1657     // Can only handle X*C and X << C.
1658     return isa<ConstantInt>(I->getOperand(1));
1659   case Instruction::GetElementPtr:
1660     return true;
1661   default:
1662     return false;
1663   }
1666 /// \brief Hepler class to perform type promotion.
1667 class TypePromotionHelper {
1668   /// \brief Utility function to check whether or not a sign extension of
1669   /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1670   /// using the operands of \p Inst or promoting \p Inst.
1671   /// In other words, check if:
1672   /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1673   /// #1 Promotion applies:
1674   /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1675   /// #2 Operand reuses:
1676   /// sext opnd1 to ConsideredSExtType.
1677   /// \p PromotedInsts maps the instructions to their type before promotion.
1678   static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1679                             const InstrToOrigTy &PromotedInsts);
1681   /// \brief Utility function to determine if \p OpIdx should be promoted when
1682   /// promoting \p Inst.
1683   static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1684     if (isa<SelectInst>(Inst) && OpIdx == 0)
1685       return false;
1686     return true;
1687   }
1689   /// \brief Utility function to promote the operand of \p SExt when this
1690   /// operand is a promotable trunc or sext.
1691   /// \p PromotedInsts maps the instructions to their type before promotion.
1692   /// \p CreatedInsts[out] contains how many non-free instructions have been
1693   /// created to promote the operand of SExt.
1694   /// Should never be called directly.
1695   /// \return The promoted value which is used instead of SExt.
1696   static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1697                                               TypePromotionTransaction &TPT,
1698                                               InstrToOrigTy &PromotedInsts,
1699                                               unsigned &CreatedInsts);
1701   /// \brief Utility function to promote the operand of \p SExt when this
1702   /// operand is promotable and is not a supported trunc or sext.
1703   /// \p PromotedInsts maps the instructions to their type before promotion.
1704   /// \p CreatedInsts[out] contains how many non-free instructions have been
1705   /// created to promote the operand of SExt.
1706   /// Should never be called directly.
1707   /// \return The promoted value which is used instead of SExt.
1708   static Value *promoteOperandForOther(Instruction *SExt,
1709                                        TypePromotionTransaction &TPT,
1710                                        InstrToOrigTy &PromotedInsts,
1711                                        unsigned &CreatedInsts);
1713 public:
1714   /// Type for the utility function that promotes the operand of SExt.
1715   typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1716                            InstrToOrigTy &PromotedInsts,
1717                            unsigned &CreatedInsts);
1718   /// \brief Given a sign extend instruction \p SExt, return the approriate
1719   /// action to promote the operand of \p SExt instead of using SExt.
1720   /// \return NULL if no promotable action is possible with the current
1721   /// sign extension.
1722   /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1723   /// the others CodeGenPrepare optimizations. This information is important
1724   /// because we do not want to promote these instructions as CodeGenPrepare
1725   /// will reinsert them later. Thus creating an infinite loop: create/remove.
1726   /// \p PromotedInsts maps the instructions to their type before promotion.
1727   static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1728                           const TargetLowering &TLI,
1729                           const InstrToOrigTy &PromotedInsts);
1730 };
1732 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1733                                         Type *ConsideredSExtType,
1734                                         const InstrToOrigTy &PromotedInsts) {
1735   // We can always get through sext.
1736   if (isa<SExtInst>(Inst))
1737     return true;
1739   // We can get through binary operator, if it is legal. In other words, the
1740   // binary operator must have a nuw or nsw flag.
1741   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1742   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1743       (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1744     return true;
1746   // Check if we can do the following simplification.
1747   // sext(trunc(sext)) --> sext
1748   if (!isa<TruncInst>(Inst))
1749     return false;
1751   Value *OpndVal = Inst->getOperand(0);
1752   // Check if we can use this operand in the sext.
1753   // If the type is larger than the result type of the sign extension,
1754   // we cannot.
1755   if (OpndVal->getType()->getIntegerBitWidth() >
1756       ConsideredSExtType->getIntegerBitWidth())
1757     return false;
1759   // If the operand of the truncate is not an instruction, we will not have
1760   // any information on the dropped bits.
1761   // (Actually we could for constant but it is not worth the extra logic).
1762   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1763   if (!Opnd)
1764     return false;
1766   // Check if the source of the type is narrow enough.
1767   // I.e., check that trunc just drops sign extended bits.
1768   // #1 get the type of the operand.
1769   const Type *OpndType;
1770   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1771   if (It != PromotedInsts.end())
1772     OpndType = It->second;
1773   else if (isa<SExtInst>(Opnd))
1774     OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1775   else
1776     return false;
1778   // #2 check that the truncate just drop sign extended bits.
1779   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1780     return true;
1782   return false;
1785 TypePromotionHelper::Action TypePromotionHelper::getAction(
1786     Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1787     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1788   Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1789   Type *SExtTy = SExt->getType();
1790   // If the operand of the sign extension is not an instruction, we cannot
1791   // get through.
1792   // If it, check we can get through.
1793   if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1794     return nullptr;
1796   // Do not promote if the operand has been added by codegenprepare.
1797   // Otherwise, it means we are undoing an optimization that is likely to be
1798   // redone, thus causing potential infinite loop.
1799   if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1800     return nullptr;
1802   // SExt or Trunc instructions.
1803   // Return the related handler.
1804   if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1805     return promoteOperandForTruncAndSExt;
1807   // Regular instruction.
1808   // Abort early if we will have to insert non-free instructions.
1809   if (!SExtOpnd->hasOneUse() &&
1810       !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1811     return nullptr;
1812   return promoteOperandForOther;
1815 Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1816     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1817     InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1818   // By construction, the operand of SExt is an instruction. Otherwise we cannot
1819   // get through it and this method should not be called.
1820   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1821   // Replace sext(trunc(opnd)) or sext(sext(opnd))
1822   // => sext(opnd).
1823   TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1824   CreatedInsts = 0;
1826   // Remove dead code.
1827   if (SExtOpnd->use_empty())
1828     TPT.eraseInstruction(SExtOpnd);
1830   // Check if the sext is still needed.
1831   if (SExt->getType() != SExt->getOperand(0)->getType())
1832     return SExt;
1834   // At this point we have: sext ty opnd to ty.
1835   // Reassign the uses of SExt to the opnd and remove SExt.
1836   Value *NextVal = SExt->getOperand(0);
1837   TPT.eraseInstruction(SExt, NextVal);
1838   return NextVal;
1841 Value *
1842 TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1843                                             TypePromotionTransaction &TPT,
1844                                             InstrToOrigTy &PromotedInsts,
1845                                             unsigned &CreatedInsts) {
1846   // By construction, the operand of SExt is an instruction. Otherwise we cannot
1847   // get through it and this method should not be called.
1848   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1849   CreatedInsts = 0;
1850   if (!SExtOpnd->hasOneUse()) {
1851     // SExtOpnd will be promoted.
1852     // All its uses, but SExt, will need to use a truncated value of the
1853     // promoted version.
1854     // Create the truncate now.
1855     Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1856     Trunc->removeFromParent();
1857     // Insert it just after the definition.
1858     Trunc->insertAfter(SExtOpnd);
1860     TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1861     // Restore the operand of SExt (which has been replace by the previous call
1862     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1863     TPT.setOperand(SExt, 0, SExtOpnd);
1864   }
1866   // Get through the Instruction:
1867   // 1. Update its type.
1868   // 2. Replace the uses of SExt by Inst.
1869   // 3. Sign extend each operand that needs to be sign extended.
1871   // Remember the original type of the instruction before promotion.
1872   // This is useful to know that the high bits are sign extended bits.
1873   PromotedInsts.insert(
1874       std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1875   // Step #1.
1876   TPT.mutateType(SExtOpnd, SExt->getType());
1877   // Step #2.
1878   TPT.replaceAllUsesWith(SExt, SExtOpnd);
1879   // Step #3.
1880   Instruction *SExtForOpnd = SExt;
1882   DEBUG(dbgs() << "Propagate SExt to operands\n");
1883   for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1884        ++OpIdx) {
1885     DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1886     if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1887         !shouldSExtOperand(SExtOpnd, OpIdx)) {
1888       DEBUG(dbgs() << "No need to propagate\n");
1889       continue;
1890     }
1891     // Check if we can statically sign extend the operand.
1892     Value *Opnd = SExtOpnd->getOperand(OpIdx);
1893     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1894       DEBUG(dbgs() << "Statically sign extend\n");
1895       TPT.setOperand(
1896           SExtOpnd, OpIdx,
1897           ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1898       continue;
1899     }
1900     // UndefValue are typed, so we have to statically sign extend them.
1901     if (isa<UndefValue>(Opnd)) {
1902       DEBUG(dbgs() << "Statically sign extend\n");
1903       TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1904       continue;
1905     }
1907     // Otherwise we have to explicity sign extend the operand.
1908     // Check if SExt was reused to sign extend an operand.
1909     if (!SExtForOpnd) {
1910       // If yes, create a new one.
1911       DEBUG(dbgs() << "More operands to sext\n");
1912       SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1913       ++CreatedInsts;
1914     }
1916     TPT.setOperand(SExtForOpnd, 0, Opnd);
1918     // Move the sign extension before the insertion point.
1919     TPT.moveBefore(SExtForOpnd, SExtOpnd);
1920     TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1921     // If more sext are required, new instructions will have to be created.
1922     SExtForOpnd = nullptr;
1923   }
1924   if (SExtForOpnd == SExt) {
1925     DEBUG(dbgs() << "Sign extension is useless now\n");
1926     TPT.eraseInstruction(SExt);
1927   }
1928   return SExtOpnd;
1931 /// IsPromotionProfitable - Check whether or not promoting an instruction
1932 /// to a wider type was profitable.
1933 /// \p MatchedSize gives the number of instructions that have been matched
1934 /// in the addressing mode after the promotion was applied.
1935 /// \p SizeWithPromotion gives the number of created instructions for
1936 /// the promotion plus the number of instructions that have been
1937 /// matched in the addressing mode before the promotion.
1938 /// \p PromotedOperand is the value that has been promoted.
1939 /// \return True if the promotion is profitable, false otherwise.
1940 bool
1941 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1942                                              unsigned SizeWithPromotion,
1943                                              Value *PromotedOperand) const {
1944   // We folded less instructions than what we created to promote the operand.
1945   // This is not profitable.
1946   if (MatchedSize < SizeWithPromotion)
1947     return false;
1948   if (MatchedSize > SizeWithPromotion)
1949     return true;
1950   // The promotion is neutral but it may help folding the sign extension in
1951   // loads for instance.
1952   // Check that we did not create an illegal instruction.
1953   Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1954   if (!PromotedInst)
1955     return false;
1956   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1957   // If the ISDOpcode is undefined, it was undefined before the promotion.
1958   if (!ISDOpcode)
1959     return true;
1960   // Otherwise, check if the promoted instruction is legal or not.
1961   return TLI.isOperationLegalOrCustom(ISDOpcode,
1962                                       EVT::getEVT(PromotedInst->getType()));
1965 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
1966 /// fold the operation into the addressing mode.  If so, update the addressing
1967 /// mode and return true, otherwise return false without modifying AddrMode.
1968 /// If \p MovedAway is not NULL, it contains the information of whether or
1969 /// not AddrInst has to be folded into the addressing mode on success.
1970 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1971 /// because it has been moved away.
1972 /// Thus AddrInst must not be added in the matched instructions.
1973 /// This state can happen when AddrInst is a sext, since it may be moved away.
1974 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
1975 /// not be referenced anymore.
1976 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
1977                                                unsigned Depth,
1978                                                bool *MovedAway) {
1979   // Avoid exponential behavior on extremely deep expression trees.
1980   if (Depth >= 5) return false;
1982   // By default, all matched instructions stay in place.
1983   if (MovedAway)
1984     *MovedAway = false;
1986   switch (Opcode) {
1987   case Instruction::PtrToInt:
1988     // PtrToInt is always a noop, as we know that the int type is pointer sized.
1989     return MatchAddr(AddrInst->getOperand(0), Depth);
1990   case Instruction::IntToPtr:
1991     // This inttoptr is a no-op if the integer type is pointer sized.
1992     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
1993         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
1994       return MatchAddr(AddrInst->getOperand(0), Depth);
1995     return false;
1996   case Instruction::BitCast:
1997     // BitCast is always a noop, and we can handle it as long as it is
1998     // int->int or pointer->pointer (we don't want int<->fp or something).
1999     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2000          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2001         // Don't touch identity bitcasts.  These were probably put here by LSR,
2002         // and we don't want to mess around with them.  Assume it knows what it
2003         // is doing.
2004         AddrInst->getOperand(0)->getType() != AddrInst->getType())
2005       return MatchAddr(AddrInst->getOperand(0), Depth);
2006     return false;
2007   case Instruction::Add: {
2008     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
2009     ExtAddrMode BackupAddrMode = AddrMode;
2010     unsigned OldSize = AddrModeInsts.size();
2011     // Start a transaction at this point.
2012     // The LHS may match but not the RHS.
2013     // Therefore, we need a higher level restoration point to undo partially
2014     // matched operation.
2015     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2016         TPT.getRestorationPoint();
2018     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2019         MatchAddr(AddrInst->getOperand(0), Depth+1))
2020       return true;
2022     // Restore the old addr mode info.
2023     AddrMode = BackupAddrMode;
2024     AddrModeInsts.resize(OldSize);
2025     TPT.rollback(LastKnownGood);
2027     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
2028     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2029         MatchAddr(AddrInst->getOperand(1), Depth+1))
2030       return true;
2032     // Otherwise we definitely can't merge the ADD in.
2033     AddrMode = BackupAddrMode;
2034     AddrModeInsts.resize(OldSize);
2035     TPT.rollback(LastKnownGood);
2036     break;
2037   }
2038   //case Instruction::Or:
2039   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2040   //break;
2041   case Instruction::Mul:
2042   case Instruction::Shl: {
2043     // Can only handle X*C and X << C.
2044     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2045     if (!RHS) return false;
2046     int64_t Scale = RHS->getSExtValue();
2047     if (Opcode == Instruction::Shl)
2048       Scale = 1LL << Scale;
2050     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2051   }
2052   case Instruction::GetElementPtr: {
2053     // Scan the GEP.  We check it if it contains constant offsets and at most
2054     // one variable offset.
2055     int VariableOperand = -1;
2056     unsigned VariableScale = 0;
2058     int64_t ConstantOffset = 0;
2059     const DataLayout *TD = TLI.getDataLayout();
2060     gep_type_iterator GTI = gep_type_begin(AddrInst);
2061     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2062       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2063         const StructLayout *SL = TD->getStructLayout(STy);
2064         unsigned Idx =
2065           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2066         ConstantOffset += SL->getElementOffset(Idx);
2067       } else {
2068         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2069         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2070           ConstantOffset += CI->getSExtValue()*TypeSize;
2071         } else if (TypeSize) {  // Scales of zero don't do anything.
2072           // We only allow one variable index at the moment.
2073           if (VariableOperand != -1)
2074             return false;
2076           // Remember the variable index.
2077           VariableOperand = i;
2078           VariableScale = TypeSize;
2079         }
2080       }
2081     }
2083     // A common case is for the GEP to only do a constant offset.  In this case,
2084     // just add it to the disp field and check validity.
2085     if (VariableOperand == -1) {
2086       AddrMode.BaseOffs += ConstantOffset;
2087       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2088         // Check to see if we can fold the base pointer in too.
2089         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2090           return true;
2091       }
2092       AddrMode.BaseOffs -= ConstantOffset;
2093       return false;
2094     }
2096     // Save the valid addressing mode in case we can't match.
2097     ExtAddrMode BackupAddrMode = AddrMode;
2098     unsigned OldSize = AddrModeInsts.size();
2100     // See if the scale and offset amount is valid for this target.
2101     AddrMode.BaseOffs += ConstantOffset;
2103     // Match the base operand of the GEP.
2104     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2105       // If it couldn't be matched, just stuff the value in a register.
2106       if (AddrMode.HasBaseReg) {
2107         AddrMode = BackupAddrMode;
2108         AddrModeInsts.resize(OldSize);
2109         return false;
2110       }
2111       AddrMode.HasBaseReg = true;
2112       AddrMode.BaseReg = AddrInst->getOperand(0);
2113     }
2115     // Match the remaining variable portion of the GEP.
2116     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2117                           Depth)) {
2118       // If it couldn't be matched, try stuffing the base into a register
2119       // instead of matching it, and retrying the match of the scale.
2120       AddrMode = BackupAddrMode;
2121       AddrModeInsts.resize(OldSize);
2122       if (AddrMode.HasBaseReg)
2123         return false;
2124       AddrMode.HasBaseReg = true;
2125       AddrMode.BaseReg = AddrInst->getOperand(0);
2126       AddrMode.BaseOffs += ConstantOffset;
2127       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2128                             VariableScale, Depth)) {
2129         // If even that didn't work, bail.
2130         AddrMode = BackupAddrMode;
2131         AddrModeInsts.resize(OldSize);
2132         return false;
2133       }
2134     }
2136     return true;
2137   }
2138   case Instruction::SExt: {
2139     // Try to move this sext out of the way of the addressing mode.
2140     Instruction *SExt = cast<Instruction>(AddrInst);
2141     // Ask for a method for doing so.
2142     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
2143         SExt, InsertedTruncs, TLI, PromotedInsts);
2144     if (!TPH)
2145       return false;
2147     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2148         TPT.getRestorationPoint();
2149     unsigned CreatedInsts = 0;
2150     Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
2151     // SExt has been moved away.
2152     // Thus either it will be rematched later in the recursive calls or it is
2153     // gone. Anyway, we must not fold it into the addressing mode at this point.
2154     // E.g.,
2155     // op = add opnd, 1
2156     // idx = sext op
2157     // addr = gep base, idx
2158     // is now:
2159     // promotedOpnd = sext opnd           <- no match here
2160     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
2161     // addr = gep base, op                <- match
2162     if (MovedAway)
2163       *MovedAway = true;
2165     assert(PromotedOperand &&
2166            "TypePromotionHelper should have filtered out those cases");
2168     ExtAddrMode BackupAddrMode = AddrMode;
2169     unsigned OldSize = AddrModeInsts.size();
2171     if (!MatchAddr(PromotedOperand, Depth) ||
2172         !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2173                                PromotedOperand)) {
2174       AddrMode = BackupAddrMode;
2175       AddrModeInsts.resize(OldSize);
2176       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2177       TPT.rollback(LastKnownGood);
2178       return false;
2179     }
2180     return true;
2181   }
2182   }
2183   return false;
2186 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2187 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
2188 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
2189 /// or intptr_t for the target.
2190 ///
2191 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2192   // Start a transaction at this point that we will rollback if the matching
2193   // fails.
2194   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2195       TPT.getRestorationPoint();
2196   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2197     // Fold in immediates if legal for the target.
2198     AddrMode.BaseOffs += CI->getSExtValue();
2199     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2200       return true;
2201     AddrMode.BaseOffs -= CI->getSExtValue();
2202   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2203     // If this is a global variable, try to fold it into the addressing mode.
2204     if (!AddrMode.BaseGV) {
2205       AddrMode.BaseGV = GV;
2206       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2207         return true;
2208       AddrMode.BaseGV = nullptr;
2209     }
2210   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2211     ExtAddrMode BackupAddrMode = AddrMode;
2212     unsigned OldSize = AddrModeInsts.size();
2214     // Check to see if it is possible to fold this operation.
2215     bool MovedAway = false;
2216     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2217       // This instruction may have been move away. If so, there is nothing
2218       // to check here.
2219       if (MovedAway)
2220         return true;
2221       // Okay, it's possible to fold this.  Check to see if it is actually
2222       // *profitable* to do so.  We use a simple cost model to avoid increasing
2223       // register pressure too much.
2224       if (I->hasOneUse() ||
2225           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2226         AddrModeInsts.push_back(I);
2227         return true;
2228       }
2230       // It isn't profitable to do this, roll back.
2231       //cerr << "NOT FOLDING: " << *I;
2232       AddrMode = BackupAddrMode;
2233       AddrModeInsts.resize(OldSize);
2234       TPT.rollback(LastKnownGood);
2235     }
2236   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2237     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2238       return true;
2239     TPT.rollback(LastKnownGood);
2240   } else if (isa<ConstantPointerNull>(Addr)) {
2241     // Null pointer gets folded without affecting the addressing mode.
2242     return true;
2243   }
2245   // Worse case, the target should support [reg] addressing modes. :)
2246   if (!AddrMode.HasBaseReg) {
2247     AddrMode.HasBaseReg = true;
2248     AddrMode.BaseReg = Addr;
2249     // Still check for legality in case the target supports [imm] but not [i+r].
2250     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2251       return true;
2252     AddrMode.HasBaseReg = false;
2253     AddrMode.BaseReg = nullptr;
2254   }
2256   // If the base register is already taken, see if we can do [r+r].
2257   if (AddrMode.Scale == 0) {
2258     AddrMode.Scale = 1;
2259     AddrMode.ScaledReg = Addr;
2260     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2261       return true;
2262     AddrMode.Scale = 0;
2263     AddrMode.ScaledReg = nullptr;
2264   }
2265   // Couldn't match.
2266   TPT.rollback(LastKnownGood);
2267   return false;
2270 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2271 /// inline asm call are due to memory operands.  If so, return true, otherwise
2272 /// return false.
2273 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2274                                     const TargetLowering &TLI) {
2275   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2276   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2277     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2279     // Compute the constraint code and ConstraintType to use.
2280     TLI.ComputeConstraintToUse(OpInfo, SDValue());
2282     // If this asm operand is our Value*, and if it isn't an indirect memory
2283     // operand, we can't fold it!
2284     if (OpInfo.CallOperandVal == OpVal &&
2285         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2286          !OpInfo.isIndirect))
2287       return false;
2288   }
2290   return true;
2293 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2294 /// memory use.  If we find an obviously non-foldable instruction, return true.
2295 /// Add the ultimately found memory instructions to MemoryUses.
2296 static bool FindAllMemoryUses(Instruction *I,
2297                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2298                               SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2299                               const TargetLowering &TLI) {
2300   // If we already considered this instruction, we're done.
2301   if (!ConsideredInsts.insert(I))
2302     return false;
2304   // If this is an obviously unfoldable instruction, bail out.
2305   if (!MightBeFoldableInst(I))
2306     return true;
2308   // Loop over all the uses, recursively processing them.
2309   for (Use &U : I->uses()) {
2310     Instruction *UserI = cast<Instruction>(U.getUser());
2312     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2313       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2314       continue;
2315     }
2317     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2318       unsigned opNo = U.getOperandNo();
2319       if (opNo == 0) return true; // Storing addr, not into addr.
2320       MemoryUses.push_back(std::make_pair(SI, opNo));
2321       continue;
2322     }
2324     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2325       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2326       if (!IA) return true;
2328       // If this is a memory operand, we're cool, otherwise bail out.
2329       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2330         return true;
2331       continue;
2332     }
2334     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2335       return true;
2336   }
2338   return false;
2341 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2342 /// the use site that we're folding it into.  If so, there is no cost to
2343 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
2344 /// that we know are live at the instruction already.
2345 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2346                                                    Value *KnownLive2) {
2347   // If Val is either of the known-live values, we know it is live!
2348   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
2349     return true;
2351   // All values other than instructions and arguments (e.g. constants) are live.
2352   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2354   // If Val is a constant sized alloca in the entry block, it is live, this is
2355   // true because it is just a reference to the stack/frame pointer, which is
2356   // live for the whole function.
2357   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2358     if (AI->isStaticAlloca())
2359       return true;
2361   // Check to see if this value is already used in the memory instruction's
2362   // block.  If so, it's already live into the block at the very least, so we
2363   // can reasonably fold it.
2364   return Val->isUsedInBasicBlock(MemoryInst->getParent());
2367 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2368 /// mode of the machine to fold the specified instruction into a load or store
2369 /// that ultimately uses it.  However, the specified instruction has multiple
2370 /// uses.  Given this, it may actually increase register pressure to fold it
2371 /// into the load.  For example, consider this code:
2372 ///
2373 ///     X = ...
2374 ///     Y = X+1
2375 ///     use(Y)   -> nonload/store
2376 ///     Z = Y+1
2377 ///     load Z
2378 ///
2379 /// In this case, Y has multiple uses, and can be folded into the load of Z
2380 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
2381 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
2382 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
2383 /// number of computations either.
2384 ///
2385 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
2386 /// X was live across 'load Z' for other reasons, we actually *would* want to
2387 /// fold the addressing mode in the Z case.  This would make Y die earlier.
2388 bool AddressingModeMatcher::
2389 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2390                                      ExtAddrMode &AMAfter) {
2391   if (IgnoreProfitability) return true;
2393   // AMBefore is the addressing mode before this instruction was folded into it,
2394   // and AMAfter is the addressing mode after the instruction was folded.  Get
2395   // the set of registers referenced by AMAfter and subtract out those
2396   // referenced by AMBefore: this is the set of values which folding in this
2397   // address extends the lifetime of.
2398   //
2399   // Note that there are only two potential values being referenced here,
2400   // BaseReg and ScaleReg (global addresses are always available, as are any
2401   // folded immediates).
2402   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2404   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2405   // lifetime wasn't extended by adding this instruction.
2406   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2407     BaseReg = nullptr;
2408   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2409     ScaledReg = nullptr;
2411   // If folding this instruction (and it's subexprs) didn't extend any live
2412   // ranges, we're ok with it.
2413   if (!BaseReg && !ScaledReg)
2414     return true;
2416   // If all uses of this instruction are ultimately load/store/inlineasm's,
2417   // check to see if their addressing modes will include this instruction.  If
2418   // so, we can fold it into all uses, so it doesn't matter if it has multiple
2419   // uses.
2420   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2421   SmallPtrSet<Instruction*, 16> ConsideredInsts;
2422   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2423     return false;  // Has a non-memory, non-foldable use!
2425   // Now that we know that all uses of this instruction are part of a chain of
2426   // computation involving only operations that could theoretically be folded
2427   // into a memory use, loop over each of these uses and see if they could
2428   // *actually* fold the instruction.
2429   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2430   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2431     Instruction *User = MemoryUses[i].first;
2432     unsigned OpNo = MemoryUses[i].second;
2434     // Get the access type of this use.  If the use isn't a pointer, we don't
2435     // know what it accesses.
2436     Value *Address = User->getOperand(OpNo);
2437     if (!Address->getType()->isPointerTy())
2438       return false;
2439     Type *AddressAccessTy = Address->getType()->getPointerElementType();
2441     // Do a match against the root of this address, ignoring profitability. This
2442     // will tell us if the addressing mode for the memory operation will
2443     // *actually* cover the shared instruction.
2444     ExtAddrMode Result;
2445     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2446         TPT.getRestorationPoint();
2447     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2448                                   MemoryInst, Result, InsertedTruncs,
2449                                   PromotedInsts, TPT);
2450     Matcher.IgnoreProfitability = true;
2451     bool Success = Matcher.MatchAddr(Address, 0);
2452     (void)Success; assert(Success && "Couldn't select *anything*?");
2454     // The match was to check the profitability, the changes made are not
2455     // part of the original matcher. Therefore, they should be dropped
2456     // otherwise the original matcher will not present the right state.
2457     TPT.rollback(LastKnownGood);
2459     // If the match didn't cover I, then it won't be shared by it.
2460     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2461                   I) == MatchedAddrModeInsts.end())
2462       return false;
2464     MatchedAddrModeInsts.clear();
2465   }
2467   return true;
2470 } // end anonymous namespace
2472 /// IsNonLocalValue - Return true if the specified values are defined in a
2473 /// different basic block than BB.
2474 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2475   if (Instruction *I = dyn_cast<Instruction>(V))
2476     return I->getParent() != BB;
2477   return false;
2480 /// OptimizeMemoryInst - Load and Store Instructions often have
2481 /// addressing modes that can do significant amounts of computation.  As such,
2482 /// instruction selection will try to get the load or store to do as much
2483 /// computation as possible for the program.  The problem is that isel can only
2484 /// see within a single block.  As such, we sink as much legal addressing mode
2485 /// stuff into the block as possible.
2486 ///
2487 /// This method is used to optimize both load/store and inline asms with memory
2488 /// operands.
2489 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2490                                         Type *AccessTy) {
2491   Value *Repl = Addr;
2493   // Try to collapse single-value PHI nodes.  This is necessary to undo
2494   // unprofitable PRE transformations.
2495   SmallVector<Value*, 8> worklist;
2496   SmallPtrSet<Value*, 16> Visited;
2497   worklist.push_back(Addr);
2499   // Use a worklist to iteratively look through PHI nodes, and ensure that
2500   // the addressing mode obtained from the non-PHI roots of the graph
2501   // are equivalent.
2502   Value *Consensus = nullptr;
2503   unsigned NumUsesConsensus = 0;
2504   bool IsNumUsesConsensusValid = false;
2505   SmallVector<Instruction*, 16> AddrModeInsts;
2506   ExtAddrMode AddrMode;
2507   TypePromotionTransaction TPT;
2508   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2509       TPT.getRestorationPoint();
2510   while (!worklist.empty()) {
2511     Value *V = worklist.back();
2512     worklist.pop_back();
2514     // Break use-def graph loops.
2515     if (!Visited.insert(V)) {
2516       Consensus = nullptr;
2517       break;
2518     }
2520     // For a PHI node, push all of its incoming values.
2521     if (PHINode *P = dyn_cast<PHINode>(V)) {
2522       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2523         worklist.push_back(P->getIncomingValue(i));
2524       continue;
2525     }
2527     // For non-PHIs, determine the addressing mode being computed.
2528     SmallVector<Instruction*, 16> NewAddrModeInsts;
2529     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2530         V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2531         PromotedInsts, TPT);
2533     // This check is broken into two cases with very similar code to avoid using
2534     // getNumUses() as much as possible. Some values have a lot of uses, so
2535     // calling getNumUses() unconditionally caused a significant compile-time
2536     // regression.
2537     if (!Consensus) {
2538       Consensus = V;
2539       AddrMode = NewAddrMode;
2540       AddrModeInsts = NewAddrModeInsts;
2541       continue;
2542     } else if (NewAddrMode == AddrMode) {
2543       if (!IsNumUsesConsensusValid) {
2544         NumUsesConsensus = Consensus->getNumUses();
2545         IsNumUsesConsensusValid = true;
2546       }
2548       // Ensure that the obtained addressing mode is equivalent to that obtained
2549       // for all other roots of the PHI traversal.  Also, when choosing one
2550       // such root as representative, select the one with the most uses in order
2551       // to keep the cost modeling heuristics in AddressingModeMatcher
2552       // applicable.
2553       unsigned NumUses = V->getNumUses();
2554       if (NumUses > NumUsesConsensus) {
2555         Consensus = V;
2556         NumUsesConsensus = NumUses;
2557         AddrModeInsts = NewAddrModeInsts;
2558       }
2559       continue;
2560     }
2562     Consensus = nullptr;
2563     break;
2564   }
2566   // If the addressing mode couldn't be determined, or if multiple different
2567   // ones were determined, bail out now.
2568   if (!Consensus) {
2569     TPT.rollback(LastKnownGood);
2570     return false;
2571   }
2572   TPT.commit();
2574   // Check to see if any of the instructions supersumed by this addr mode are
2575   // non-local to I's BB.
2576   bool AnyNonLocal = false;
2577   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2578     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2579       AnyNonLocal = true;
2580       break;
2581     }
2582   }
2584   // If all the instructions matched are already in this BB, don't do anything.
2585   if (!AnyNonLocal) {
2586     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
2587     return false;
2588   }
2590   // Insert this computation right after this user.  Since our caller is
2591   // scanning from the top of the BB to the bottom, reuse of the expr are
2592   // guaranteed to happen later.
2593   IRBuilder<> Builder(MemoryInst);
2595   // Now that we determined the addressing expression we want to use and know
2596   // that we have to sink it into this block.  Check to see if we have already
2597   // done this for some other load/store instr in this block.  If so, reuse the
2598   // computation.
2599   Value *&SunkAddr = SunkAddrs[Addr];
2600   if (SunkAddr) {
2601     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2602                  << *MemoryInst);
2603     if (SunkAddr->getType() != Addr->getType())
2604       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2605   } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2606                TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2607     // By default, we use the GEP-based method when AA is used later. This
2608     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2609     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2610                  << *MemoryInst);
2611     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2612     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
2614     // First, find the pointer.
2615     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2616       ResultPtr = AddrMode.BaseReg;
2617       AddrMode.BaseReg = nullptr;
2618     }
2620     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2621       // We can't add more than one pointer together, nor can we scale a
2622       // pointer (both of which seem meaningless).
2623       if (ResultPtr || AddrMode.Scale != 1)
2624         return false;
2626       ResultPtr = AddrMode.ScaledReg;
2627       AddrMode.Scale = 0;
2628     }
2630     if (AddrMode.BaseGV) {
2631       if (ResultPtr)
2632         return false;
2634       ResultPtr = AddrMode.BaseGV;
2635     }
2637     // If the real base value actually came from an inttoptr, then the matcher
2638     // will look through it and provide only the integer value. In that case,
2639     // use it here.
2640     if (!ResultPtr && AddrMode.BaseReg) {
2641       ResultPtr =
2642         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
2643       AddrMode.BaseReg = nullptr;
2644     } else if (!ResultPtr && AddrMode.Scale == 1) {
2645       ResultPtr =
2646         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2647       AddrMode.Scale = 0;
2648     }
2650     if (!ResultPtr &&
2651         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2652       SunkAddr = Constant::getNullValue(Addr->getType());
2653     } else if (!ResultPtr) {
2654       return false;
2655     } else {
2656       Type *I8PtrTy =
2657         Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2659       // Start with the base register. Do this first so that subsequent address
2660       // matching finds it last, which will prevent it from trying to match it
2661       // as the scaled value in case it happens to be a mul. That would be
2662       // problematic if we've sunk a different mul for the scale, because then
2663       // we'd end up sinking both muls.
2664       if (AddrMode.BaseReg) {
2665         Value *V = AddrMode.BaseReg;
2666         if (V->getType() != IntPtrTy)
2667           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2669         ResultIndex = V;
2670       }
2672       // Add the scale value.
2673       if (AddrMode.Scale) {
2674         Value *V = AddrMode.ScaledReg;
2675         if (V->getType() == IntPtrTy) {
2676           // done.
2677         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2678                    cast<IntegerType>(V->getType())->getBitWidth()) {
2679           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2680         } else {
2681           // It is only safe to sign extend the BaseReg if we know that the math
2682           // required to create it did not overflow before we extend it. Since
2683           // the original IR value was tossed in favor of a constant back when
2684           // the AddrMode was created we need to bail out gracefully if widths
2685           // do not match instead of extending it.
2686           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2687           if (I && (ResultIndex != AddrMode.BaseReg))
2688             I->eraseFromParent();
2689           return false;
2690         }
2692         if (AddrMode.Scale != 1)
2693           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2694                                 "sunkaddr");
2695         if (ResultIndex)
2696           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2697         else
2698           ResultIndex = V;
2699       }
2701       // Add in the Base Offset if present.
2702       if (AddrMode.BaseOffs) {
2703         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2704         if (ResultIndex) {
2705           // We need to add this separately from the scale above to help with
2706           // SDAG consecutive load/store merging.
2707           if (ResultPtr->getType() != I8PtrTy)
2708             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2709           ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2710         }
2712         ResultIndex = V;
2713       }
2715       if (!ResultIndex) {
2716         SunkAddr = ResultPtr;
2717       } else {
2718         if (ResultPtr->getType() != I8PtrTy)
2719           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2720         SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2721       }
2723       if (SunkAddr->getType() != Addr->getType())
2724         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2725     }
2726   } else {
2727     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2728                  << *MemoryInst);
2729     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2730     Value *Result = nullptr;
2732     // Start with the base register. Do this first so that subsequent address
2733     // matching finds it last, which will prevent it from trying to match it
2734     // as the scaled value in case it happens to be a mul. That would be
2735     // problematic if we've sunk a different mul for the scale, because then
2736     // we'd end up sinking both muls.
2737     if (AddrMode.BaseReg) {
2738       Value *V = AddrMode.BaseReg;
2739       if (V->getType()->isPointerTy())
2740         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2741       if (V->getType() != IntPtrTy)
2742         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2743       Result = V;
2744     }
2746     // Add the scale value.
2747     if (AddrMode.Scale) {
2748       Value *V = AddrMode.ScaledReg;
2749       if (V->getType() == IntPtrTy) {
2750         // done.
2751       } else if (V->getType()->isPointerTy()) {
2752         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2753       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2754                  cast<IntegerType>(V->getType())->getBitWidth()) {
2755         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2756       } else {
2757         // It is only safe to sign extend the BaseReg if we know that the math
2758         // required to create it did not overflow before we extend it. Since
2759         // the original IR value was tossed in favor of a constant back when
2760         // the AddrMode was created we need to bail out gracefully if widths
2761         // do not match instead of extending it.
2762         Instruction *I = dyn_cast<Instruction>(Result);
2763         if (I && (Result != AddrMode.BaseReg))
2764           I->eraseFromParent();
2765         return false;
2766       }
2767       if (AddrMode.Scale != 1)
2768         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2769                               "sunkaddr");
2770       if (Result)
2771         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2772       else
2773         Result = V;
2774     }
2776     // Add in the BaseGV if present.
2777     if (AddrMode.BaseGV) {
2778       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2779       if (Result)
2780         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2781       else
2782         Result = V;
2783     }
2785     // Add in the Base Offset if present.
2786     if (AddrMode.BaseOffs) {
2787       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2788       if (Result)
2789         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2790       else
2791         Result = V;
2792     }
2794     if (!Result)
2795       SunkAddr = Constant::getNullValue(Addr->getType());
2796     else
2797       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2798   }
2800   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2802   // If we have no uses, recursively delete the value and all dead instructions
2803   // using it.
2804   if (Repl->use_empty()) {
2805     // This can cause recursive deletion, which can invalidate our iterator.
2806     // Use a WeakVH to hold onto it in case this happens.
2807     WeakVH IterHandle(CurInstIterator);
2808     BasicBlock *BB = CurInstIterator->getParent();
2810     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2812     if (IterHandle != CurInstIterator) {
2813       // If the iterator instruction was recursively deleted, start over at the
2814       // start of the block.
2815       CurInstIterator = BB->begin();
2816       SunkAddrs.clear();
2817     }
2818   }
2819   ++NumMemoryInsts;
2820   return true;
2823 /// OptimizeInlineAsmInst - If there are any memory operands, use
2824 /// OptimizeMemoryInst to sink their address computing into the block when
2825 /// possible / profitable.
2826 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2827   bool MadeChange = false;
2829   TargetLowering::AsmOperandInfoVector
2830     TargetConstraints = TLI->ParseConstraints(CS);
2831   unsigned ArgNo = 0;
2832   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2833     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2835     // Compute the constraint code and ConstraintType to use.
2836     TLI->ComputeConstraintToUse(OpInfo, SDValue());
2838     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2839         OpInfo.isIndirect) {
2840       Value *OpVal = CS->getArgOperand(ArgNo++);
2841       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2842     } else if (OpInfo.Type == InlineAsm::isInput)
2843       ArgNo++;
2844   }
2846   return MadeChange;
2849 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2850 /// basic block as the load, unless conditions are unfavorable. This allows
2851 /// SelectionDAG to fold the extend into the load.
2852 ///
2853 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2854   // Look for a load being extended.
2855   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2856   if (!LI) return false;
2858   // If they're already in the same block, there's nothing to do.
2859   if (LI->getParent() == I->getParent())
2860     return false;
2862   // If the load has other users and the truncate is not free, this probably
2863   // isn't worthwhile.
2864   if (!LI->hasOneUse() &&
2865       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2866               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
2867       !TLI->isTruncateFree(I->getType(), LI->getType()))
2868     return false;
2870   // Check whether the target supports casts folded into loads.
2871   unsigned LType;
2872   if (isa<ZExtInst>(I))
2873     LType = ISD::ZEXTLOAD;
2874   else {
2875     assert(isa<SExtInst>(I) && "Unexpected ext type!");
2876     LType = ISD::SEXTLOAD;
2877   }
2878   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
2879     return false;
2881   // Move the extend into the same block as the load, so that SelectionDAG
2882   // can fold it.
2883   I->removeFromParent();
2884   I->insertAfter(LI);
2885   ++NumExtsMoved;
2886   return true;
2889 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2890   BasicBlock *DefBB = I->getParent();
2892   // If the result of a {s|z}ext and its source are both live out, rewrite all
2893   // other uses of the source with result of extension.
2894   Value *Src = I->getOperand(0);
2895   if (Src->hasOneUse())
2896     return false;
2898   // Only do this xform if truncating is free.
2899   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
2900     return false;
2902   // Only safe to perform the optimization if the source is also defined in
2903   // this block.
2904   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
2905     return false;
2907   bool DefIsLiveOut = false;
2908   for (User *U : I->users()) {
2909     Instruction *UI = cast<Instruction>(U);
2911     // Figure out which BB this ext is used in.
2912     BasicBlock *UserBB = UI->getParent();
2913     if (UserBB == DefBB) continue;
2914     DefIsLiveOut = true;
2915     break;
2916   }
2917   if (!DefIsLiveOut)
2918     return false;
2920   // Make sure none of the uses are PHI nodes.
2921   for (User *U : Src->users()) {
2922     Instruction *UI = cast<Instruction>(U);
2923     BasicBlock *UserBB = UI->getParent();
2924     if (UserBB == DefBB) continue;
2925     // Be conservative. We don't want this xform to end up introducing
2926     // reloads just before load / store instructions.
2927     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
2928       return false;
2929   }
2931   // InsertedTruncs - Only insert one trunc in each block once.
2932   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2934   bool MadeChange = false;
2935   for (Use &U : Src->uses()) {
2936     Instruction *User = cast<Instruction>(U.getUser());
2938     // Figure out which BB this ext is used in.
2939     BasicBlock *UserBB = User->getParent();
2940     if (UserBB == DefBB) continue;
2942     // Both src and def are live in this block. Rewrite the use.
2943     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2945     if (!InsertedTrunc) {
2946       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2947       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
2948       InsertedTruncsSet.insert(InsertedTrunc);
2949     }
2951     // Replace a use of the {s|z}ext source with a use of the result.
2952     U = InsertedTrunc;
2953     ++NumExtUses;
2954     MadeChange = true;
2955   }
2957   return MadeChange;
2960 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2961 /// turned into an explicit branch.
2962 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2963   // FIXME: This should use the same heuristics as IfConversion to determine
2964   // whether a select is better represented as a branch.  This requires that
2965   // branch probability metadata is preserved for the select, which is not the
2966   // case currently.
2968   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2970   // If the branch is predicted right, an out of order CPU can avoid blocking on
2971   // the compare.  Emit cmovs on compares with a memory operand as branches to
2972   // avoid stalls on the load from memory.  If the compare has more than one use
2973   // there's probably another cmov or setcc around so it's not worth emitting a
2974   // branch.
2975   if (!Cmp)
2976     return false;
2978   Value *CmpOp0 = Cmp->getOperand(0);
2979   Value *CmpOp1 = Cmp->getOperand(1);
2981   // We check that the memory operand has one use to avoid uses of the loaded
2982   // value directly after the compare, making branches unprofitable.
2983   return Cmp->hasOneUse() &&
2984          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2985           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2989 /// If we have a SelectInst that will likely profit from branch prediction,
2990 /// turn it into a branch.
2991 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
2992   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2994   // Can we convert the 'select' to CF ?
2995   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
2996     return false;
2998   TargetLowering::SelectSupportKind SelectKind;
2999   if (VectorCond)
3000     SelectKind = TargetLowering::VectorMaskSelect;
3001   else if (SI->getType()->isVectorTy())
3002     SelectKind = TargetLowering::ScalarCondVectorVal;
3003   else
3004     SelectKind = TargetLowering::ScalarValSelect;
3006   // Do we have efficient codegen support for this kind of 'selects' ?
3007   if (TLI->isSelectSupported(SelectKind)) {
3008     // We have efficient codegen support for the select instruction.
3009     // Check if it is profitable to keep this 'select'.
3010     if (!TLI->isPredictableSelectExpensive() ||
3011         !isFormingBranchFromSelectProfitable(SI))
3012       return false;
3013   }
3015   ModifiedDT = true;
3017   // First, we split the block containing the select into 2 blocks.
3018   BasicBlock *StartBlock = SI->getParent();
3019   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3020   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3022   // Create a new block serving as the landing pad for the branch.
3023   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3024                                              NextBlock->getParent(), NextBlock);
3026   // Move the unconditional branch from the block with the select in it into our
3027   // landing pad block.
3028   StartBlock->getTerminator()->eraseFromParent();
3029   BranchInst::Create(NextBlock, SmallBlock);
3031   // Insert the real conditional branch based on the original condition.
3032   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3034   // The select itself is replaced with a PHI Node.
3035   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3036   PN->takeName(SI);
3037   PN->addIncoming(SI->getTrueValue(), StartBlock);
3038   PN->addIncoming(SI->getFalseValue(), SmallBlock);
3039   SI->replaceAllUsesWith(PN);
3040   SI->eraseFromParent();
3042   // Instruct OptimizeBlock to skip to the next block.
3043   CurInstIterator = StartBlock->end();
3044   ++NumSelectsExpanded;
3045   return true;
3048 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3049   SmallVector<int, 16> Mask(SVI->getShuffleMask());
3050   int SplatElem = -1;
3051   for (unsigned i = 0; i < Mask.size(); ++i) {
3052     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3053       return false;
3054     SplatElem = Mask[i];
3055   }
3057   return true;
3060 /// Some targets have expensive vector shifts if the lanes aren't all the same
3061 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3062 /// it's often worth sinking a shufflevector splat down to its use so that
3063 /// codegen can spot all lanes are identical.
3064 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3065   BasicBlock *DefBB = SVI->getParent();
3067   // Only do this xform if variable vector shifts are particularly expensive.
3068   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3069     return false;
3071   // We only expect better codegen by sinking a shuffle if we can recognise a
3072   // constant splat.
3073   if (!isBroadcastShuffle(SVI))
3074     return false;
3076   // InsertedShuffles - Only insert a shuffle in each block once.
3077   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3079   bool MadeChange = false;
3080   for (User *U : SVI->users()) {
3081     Instruction *UI = cast<Instruction>(U);
3083     // Figure out which BB this ext is used in.
3084     BasicBlock *UserBB = UI->getParent();
3085     if (UserBB == DefBB) continue;
3087     // For now only apply this when the splat is used by a shift instruction.
3088     if (!UI->isShift()) continue;
3090     // Everything checks out, sink the shuffle if the user's block doesn't
3091     // already have a copy.
3092     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3094     if (!InsertedShuffle) {
3095       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3096       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3097                                               SVI->getOperand(1),
3098                                               SVI->getOperand(2), "", InsertPt);
3099     }
3101     UI->replaceUsesOfWith(SVI, InsertedShuffle);
3102     MadeChange = true;
3103   }
3105   // If we removed all uses, nuke the shuffle.
3106   if (SVI->use_empty()) {
3107     SVI->eraseFromParent();
3108     MadeChange = true;
3109   }
3111   return MadeChange;
3114 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
3115   if (PHINode *P = dyn_cast<PHINode>(I)) {
3116     // It is possible for very late stage optimizations (such as SimplifyCFG)
3117     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
3118     // trivial PHI, go ahead and zap it here.
3119     if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
3120                                        TLInfo, DT)) {
3121       P->replaceAllUsesWith(V);
3122       P->eraseFromParent();
3123       ++NumPHIsElim;
3124       return true;
3125     }
3126     return false;
3127   }
3129   if (CastInst *CI = dyn_cast<CastInst>(I)) {
3130     // If the source of the cast is a constant, then this should have
3131     // already been constant folded.  The only reason NOT to constant fold
3132     // it is if something (e.g. LSR) was careful to place the constant
3133     // evaluation in a block other than then one that uses it (e.g. to hoist
3134     // the address of globals out of a loop).  If this is the case, we don't
3135     // want to forward-subst the cast.
3136     if (isa<Constant>(CI->getOperand(0)))
3137       return false;
3139     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3140       return true;
3142     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
3143       /// Sink a zext or sext into its user blocks if the target type doesn't
3144       /// fit in one register
3145       if (TLI && TLI->getTypeAction(CI->getContext(),
3146                                     TLI->getValueType(CI->getType())) ==
3147                      TargetLowering::TypeExpandInteger) {
3148         return SinkCast(CI);
3149       } else {
3150         bool MadeChange = MoveExtToFormExtLoad(I);
3151         return MadeChange | OptimizeExtUses(I);
3152       }
3153     }
3154     return false;
3155   }
3157   if (CmpInst *CI = dyn_cast<CmpInst>(I))
3158     if (!TLI || !TLI->hasMultipleConditionRegisters())
3159       return OptimizeCmpExpression(CI);
3161   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3162     if (TLI)
3163       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3164     return false;
3165   }
3167   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3168     if (TLI)
3169       return OptimizeMemoryInst(I, SI->getOperand(1),
3170                                 SI->getOperand(0)->getType());
3171     return false;
3172   }
3174   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3176   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3177                 BinOp->getOpcode() == Instruction::LShr)) {
3178     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3179     if (TLI && CI && TLI->hasExtractBitsInsn())
3180       return OptimizeExtractBits(BinOp, CI, *TLI);
3182     return false;
3183   }
3185   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3186     if (GEPI->hasAllZeroIndices()) {
3187       /// The GEP operand must be a pointer, so must its result -> BitCast
3188       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3189                                         GEPI->getName(), GEPI);
3190       GEPI->replaceAllUsesWith(NC);
3191       GEPI->eraseFromParent();
3192       ++NumGEPsElim;
3193       OptimizeInst(NC);
3194       return true;
3195     }
3196     return false;
3197   }
3199   if (CallInst *CI = dyn_cast<CallInst>(I))
3200     return OptimizeCallInst(CI);
3202   if (SelectInst *SI = dyn_cast<SelectInst>(I))
3203     return OptimizeSelectInst(SI);
3205   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3206     return OptimizeShuffleVectorInst(SVI);
3208   return false;
3211 // In this pass we look for GEP and cast instructions that are used
3212 // across basic blocks and rewrite them to improve basic-block-at-a-time
3213 // selection.
3214 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
3215   SunkAddrs.clear();
3216   bool MadeChange = false;
3218   CurInstIterator = BB.begin();
3219   while (CurInstIterator != BB.end())
3220     MadeChange |= OptimizeInst(CurInstIterator++);
3222   MadeChange |= DupRetToEnableTailCallOpts(&BB);
3224   return MadeChange;
3227 // llvm.dbg.value is far away from the value then iSel may not be able
3228 // handle it properly. iSel will drop llvm.dbg.value if it can not
3229 // find a node corresponding to the value.
3230 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3231   bool MadeChange = false;
3232   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3233     Instruction *PrevNonDbgInst = nullptr;
3234     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3235       Instruction *Insn = BI; ++BI;
3236       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3237       // Leave dbg.values that refer to an alloca alone. These
3238       // instrinsics describe the address of a variable (= the alloca)
3239       // being taken.  They should not be moved next to the alloca
3240       // (and to the beginning of the scope), but rather stay close to
3241       // where said address is used.
3242       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
3243         PrevNonDbgInst = Insn;
3244         continue;
3245       }
3247       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3248       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3249         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3250         DVI->removeFromParent();
3251         if (isa<PHINode>(VI))
3252           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3253         else
3254           DVI->insertAfter(VI);
3255         MadeChange = true;
3256         ++NumDbgValueMoved;
3257       }
3258     }
3259   }
3260   return MadeChange;
3263 // If there is a sequence that branches based on comparing a single bit
3264 // against zero that can be combined into a single instruction, and the
3265 // target supports folding these into a single instruction, sink the
3266 // mask and compare into the branch uses. Do this before OptimizeBlock ->
3267 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3268 // searched for.
3269 bool CodeGenPrepare::sinkAndCmp(Function &F) {
3270   if (!EnableAndCmpSinking)
3271     return false;
3272   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3273     return false;
3274   bool MadeChange = false;
3275   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3276     BasicBlock *BB = I++;
3278     // Does this BB end with the following?
3279     //   %andVal = and %val, #single-bit-set
3280     //   %icmpVal = icmp %andResult, 0
3281     //   br i1 %cmpVal label %dest1, label %dest2"
3282     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3283     if (!Brcc || !Brcc->isConditional())
3284       continue;
3285     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3286     if (!Cmp || Cmp->getParent() != BB)
3287       continue;
3288     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3289     if (!Zero || !Zero->isZero())
3290       continue;
3291     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3292     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3293       continue;
3294     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3295     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3296       continue;
3297     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3299     // Push the "and; icmp" for any users that are conditional branches.
3300     // Since there can only be one branch use per BB, we don't need to keep
3301     // track of which BBs we insert into.
3302     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3303          UI != E; ) {
3304       Use &TheUse = *UI;
3305       // Find brcc use.
3306       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3307       ++UI;
3308       if (!BrccUser || !BrccUser->isConditional())
3309         continue;
3310       BasicBlock *UserBB = BrccUser->getParent();
3311       if (UserBB == BB) continue;
3312       DEBUG(dbgs() << "found Brcc use\n");
3314       // Sink the "and; icmp" to use.
3315       MadeChange = true;
3316       BinaryOperator *NewAnd =
3317         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3318                                   BrccUser);
3319       CmpInst *NewCmp =
3320         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3321                         "", BrccUser);
3322       TheUse = NewCmp;
3323       ++NumAndCmpsMoved;
3324       DEBUG(BrccUser->getParent()->dump());
3325     }
3326   }
3327   return MadeChange;