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