Skip debug info one more place. (This one gets
[oota-llvm.git] / lib / Transforms / Scalar / 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/Transforms/Scalar.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Target/TargetAsmInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/Assembly/Writer.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 #include "llvm/Support/PatternMatch.h"
41 using namespace llvm;
42 using namespace llvm::PatternMatch;
43
44 static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
45                                        cl::init(false), cl::Hidden);
46
47 namespace {
48   class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
49     /// TLI - Keep a pointer of a TargetLowering to consult for determining
50     /// transformation profitability.
51     const TargetLowering *TLI;
52
53     /// BackEdges - Keep a set of all the loop back edges.
54     ///
55     SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> BackEdges;
56   public:
57     static char ID; // Pass identification, replacement for typeid
58     explicit CodeGenPrepare(const TargetLowering *tli = 0)
59       : FunctionPass(&ID), TLI(tli) {}
60     bool runOnFunction(Function &F);
61
62   private:
63     bool EliminateMostlyEmptyBlocks(Function &F);
64     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
65     void EliminateMostlyEmptyBlock(BasicBlock *BB);
66     bool OptimizeBlock(BasicBlock &BB);
67     bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
68                             DenseMap<Value*,Value*> &SunkAddrs);
69     bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
70                                DenseMap<Value*,Value*> &SunkAddrs);
71     bool OptimizeExtUses(Instruction *I);
72     void findLoopBackEdges(Function &F);
73   };
74 }
75
76 char CodeGenPrepare::ID = 0;
77 static RegisterPass<CodeGenPrepare> X("codegenprepare",
78                                       "Optimize for code generation");
79
80 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
81   return new CodeGenPrepare(TLI);
82 }
83
84 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
85 ///
86 void CodeGenPrepare::findLoopBackEdges(Function &F) {
87   SmallPtrSet<BasicBlock*, 8> Visited;
88   SmallVector<std::pair<BasicBlock*, succ_iterator>, 8> VisitStack;
89   SmallPtrSet<BasicBlock*, 8> InStack;
90
91   BasicBlock *BB = &F.getEntryBlock();
92   if (succ_begin(BB) == succ_end(BB))
93     return;
94   Visited.insert(BB);
95   VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
96   InStack.insert(BB);
97   do {
98     std::pair<BasicBlock*, succ_iterator> &Top = VisitStack.back();
99     BasicBlock *ParentBB = Top.first;
100     succ_iterator &I = Top.second;
101
102     bool FoundNew = false;
103     while (I != succ_end(ParentBB)) {
104       BB = *I++;
105       if (Visited.insert(BB)) {
106         FoundNew = true;
107         break;
108       }
109       // Successor is in VisitStack, it's a back edge.
110       if (InStack.count(BB))
111         BackEdges.insert(std::make_pair(ParentBB, BB));
112     }
113
114     if (FoundNew) {
115       // Go down one level if there is a unvisited successor.
116       InStack.insert(BB);
117       VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
118     } else {
119       // Go up one level.
120       std::pair<BasicBlock*, succ_iterator> &Pop = VisitStack.back();
121       InStack.erase(Pop.first);
122       VisitStack.pop_back();
123     }
124   } while (!VisitStack.empty());
125 }
126
127
128 bool CodeGenPrepare::runOnFunction(Function &F) {
129   bool EverMadeChange = false;
130
131   // First pass, eliminate blocks that contain only PHI nodes and an
132   // unconditional branch.
133   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
134
135   // Now find loop back edges.
136   findLoopBackEdges(F);
137
138   bool MadeChange = true;
139   while (MadeChange) {
140     MadeChange = false;
141     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
142       MadeChange |= OptimizeBlock(*BB);
143     EverMadeChange |= MadeChange;
144   }
145   return EverMadeChange;
146 }
147
148 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
149 /// and an unconditional branch.  Passes before isel (e.g. LSR/loopsimplify)
150 /// often split edges in ways that are non-optimal for isel.  Start by
151 /// eliminating these blocks so we can split them the way we want them.
152 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
153   bool MadeChange = false;
154   // Note that this intentionally skips the entry block.
155   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
156     BasicBlock *BB = I++;
157
158     // If this block doesn't end with an uncond branch, ignore it.
159     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
160     if (!BI || !BI->isUnconditional())
161       continue;
162
163     // If the instruction before the branch isn't a phi node, then other stuff
164     // is happening here.
165     BasicBlock::iterator BBI = BI;
166     if (BBI != BB->begin()) {
167       --BBI;
168       if (!isa<PHINode>(BBI)) continue;
169     }
170
171     // Do not break infinite loops.
172     BasicBlock *DestBB = BI->getSuccessor(0);
173     if (DestBB == BB)
174       continue;
175
176     if (!CanMergeBlocks(BB, DestBB))
177       continue;
178
179     EliminateMostlyEmptyBlock(BB);
180     MadeChange = true;
181   }
182   return MadeChange;
183 }
184
185 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
186 /// single uncond branch between them, and BB contains no other non-phi
187 /// instructions.
188 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
189                                     const BasicBlock *DestBB) const {
190   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
191   // the successor.  If there are more complex condition (e.g. preheaders),
192   // don't mess around with them.
193   BasicBlock::const_iterator BBI = BB->begin();
194   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
195     for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
196          UI != E; ++UI) {
197       const Instruction *User = cast<Instruction>(*UI);
198       if (User->getParent() != DestBB || !isa<PHINode>(User))
199         return false;
200       // If User is inside DestBB block and it is a PHINode then check
201       // incoming value. If incoming value is not from BB then this is
202       // a complex condition (e.g. preheaders) we want to avoid here.
203       if (User->getParent() == DestBB) {
204         if (const PHINode *UPN = dyn_cast<PHINode>(User))
205           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
206             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
207             if (Insn && Insn->getParent() == BB &&
208                 Insn->getParent() != UPN->getIncomingBlock(I))
209               return false;
210           }
211       }
212     }
213   }
214
215   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
216   // and DestBB may have conflicting incoming values for the block.  If so, we
217   // can't merge the block.
218   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
219   if (!DestBBPN) return true;  // no conflict.
220
221   // Collect the preds of BB.
222   SmallPtrSet<const BasicBlock*, 16> BBPreds;
223   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
224     // It is faster to get preds from a PHI than with pred_iterator.
225     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
226       BBPreds.insert(BBPN->getIncomingBlock(i));
227   } else {
228     BBPreds.insert(pred_begin(BB), pred_end(BB));
229   }
230
231   // Walk the preds of DestBB.
232   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
233     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
234     if (BBPreds.count(Pred)) {   // Common predecessor?
235       BBI = DestBB->begin();
236       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
237         const Value *V1 = PN->getIncomingValueForBlock(Pred);
238         const Value *V2 = PN->getIncomingValueForBlock(BB);
239
240         // If V2 is a phi node in BB, look up what the mapped value will be.
241         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
242           if (V2PN->getParent() == BB)
243             V2 = V2PN->getIncomingValueForBlock(Pred);
244
245         // If there is a conflict, bail out.
246         if (V1 != V2) return false;
247       }
248     }
249   }
250
251   return true;
252 }
253
254
255 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
256 /// an unconditional branch in it.
257 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
258   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
259   BasicBlock *DestBB = BI->getSuccessor(0);
260
261   DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
262
263   // If the destination block has a single pred, then this is a trivial edge,
264   // just collapse it.
265   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
266     if (SinglePred != DestBB) {
267       // Remember if SinglePred was the entry block of the function.  If so, we
268       // will need to move BB back to the entry position.
269       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
270       MergeBasicBlockIntoOnlyPred(DestBB);
271
272       if (isEntry && BB != &BB->getParent()->getEntryBlock())
273         BB->moveBefore(&BB->getParent()->getEntryBlock());
274       
275       DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
276       return;
277     }
278   }
279
280   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
281   // to handle the new incoming edges it is about to have.
282   PHINode *PN;
283   for (BasicBlock::iterator BBI = DestBB->begin();
284        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
285     // Remove the incoming value for BB, and remember it.
286     Value *InVal = PN->removeIncomingValue(BB, false);
287
288     // Two options: either the InVal is a phi node defined in BB or it is some
289     // value that dominates BB.
290     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
291     if (InValPhi && InValPhi->getParent() == BB) {
292       // Add all of the input values of the input PHI as inputs of this phi.
293       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
294         PN->addIncoming(InValPhi->getIncomingValue(i),
295                         InValPhi->getIncomingBlock(i));
296     } else {
297       // Otherwise, add one instance of the dominating value for each edge that
298       // we will be adding.
299       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
300         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
301           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
302       } else {
303         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
304           PN->addIncoming(InVal, *PI);
305       }
306     }
307   }
308
309   // The PHIs are now updated, change everything that refers to BB to use
310   // DestBB and remove BB.
311   BB->replaceAllUsesWith(DestBB);
312   BB->eraseFromParent();
313
314   DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
315 }
316
317
318 /// SplitEdgeNicely - Split the critical edge from TI to its specified
319 /// successor if it will improve codegen.  We only do this if the successor has
320 /// phi nodes (otherwise critical edges are ok).  If there is already another
321 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
322 /// instead of introducing a new block.
323 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
324                      SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> &BackEdges,
325                              Pass *P) {
326   BasicBlock *TIBB = TI->getParent();
327   BasicBlock *Dest = TI->getSuccessor(SuccNum);
328   assert(isa<PHINode>(Dest->begin()) &&
329          "This should only be called if Dest has a PHI!");
330
331   // Do not split edges to EH landing pads.
332   if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
333     if (Invoke->getSuccessor(1) == Dest)
334       return;
335   }
336
337   // As a hack, never split backedges of loops.  Even though the copy for any
338   // PHIs inserted on the backedge would be dead for exits from the loop, we
339   // assume that the cost of *splitting* the backedge would be too high.
340   if (BackEdges.count(std::make_pair(TIBB, Dest)))
341     return;
342
343   if (!FactorCommonPreds) {
344     /// TIPHIValues - This array is lazily computed to determine the values of
345     /// PHIs in Dest that TI would provide.
346     SmallVector<Value*, 32> TIPHIValues;
347
348     // Check to see if Dest has any blocks that can be used as a split edge for
349     // this terminator.
350     for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
351       BasicBlock *Pred = *PI;
352       // To be usable, the pred has to end with an uncond branch to the dest.
353       BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
354       if (!PredBr || !PredBr->isUnconditional())
355         continue;
356       // Must be empty other than the branch and debug info.
357       BasicBlock::iterator I = Pred->begin();
358       while (isa<DbgInfoIntrinsic>(I))
359         I++;
360       if (dyn_cast<Instruction>(I) != PredBr)
361         continue;
362       // Cannot be the entry block; its label does not get emitted.
363       if (Pred == &(Dest->getParent()->getEntryBlock()))
364         continue;
365
366       // Finally, since we know that Dest has phi nodes in it, we have to make
367       // sure that jumping to Pred will have the same effect as going to Dest in
368       // terms of PHI values.
369       PHINode *PN;
370       unsigned PHINo = 0;
371       bool FoundMatch = true;
372       for (BasicBlock::iterator I = Dest->begin();
373            (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
374         if (PHINo == TIPHIValues.size())
375           TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
376
377         // If the PHI entry doesn't work, we can't use this pred.
378         if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
379           FoundMatch = false;
380           break;
381         }
382       }
383
384       // If we found a workable predecessor, change TI to branch to Succ.
385       if (FoundMatch) {
386         Dest->removePredecessor(TIBB);
387         TI->setSuccessor(SuccNum, Pred);
388         return;
389       }
390     }
391
392     SplitCriticalEdge(TI, SuccNum, P, true);
393     return;
394   }
395
396   PHINode *PN;
397   SmallVector<Value*, 8> TIPHIValues;
398   for (BasicBlock::iterator I = Dest->begin();
399        (PN = dyn_cast<PHINode>(I)); ++I)
400     TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
401
402   SmallVector<BasicBlock*, 8> IdenticalPreds;
403   for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
404     BasicBlock *Pred = *PI;
405     if (BackEdges.count(std::make_pair(Pred, Dest)))
406       continue;
407     if (PI == TIBB)
408       IdenticalPreds.push_back(Pred);
409     else {
410       bool Identical = true;
411       unsigned PHINo = 0;
412       for (BasicBlock::iterator I = Dest->begin();
413            (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
414         if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
415           Identical = false;
416           break;
417         }
418       if (Identical)
419         IdenticalPreds.push_back(Pred);
420     }
421   }
422
423   assert(!IdenticalPreds.empty());
424   SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
425                          ".critedge", P);
426 }
427
428
429 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
430 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
431 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
432 /// registers that must be created and coalesced.
433 ///
434 /// Return true if any changes are made.
435 ///
436 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
437   // If this is a noop copy,
438   MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
439   MVT DstVT = TLI.getValueType(CI->getType());
440
441   // This is an fp<->int conversion?
442   if (SrcVT.isInteger() != DstVT.isInteger())
443     return false;
444
445   // If this is an extension, it will be a zero or sign extension, which
446   // isn't a noop.
447   if (SrcVT.bitsLT(DstVT)) return false;
448
449   // If these values will be promoted, find out what they will be promoted
450   // to.  This helps us consider truncates on PPC as noop copies when they
451   // are.
452   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
453     SrcVT = TLI.getTypeToTransformTo(SrcVT);
454   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
455     DstVT = TLI.getTypeToTransformTo(DstVT);
456
457   // If, after promotion, these are the same types, this is a noop copy.
458   if (SrcVT != DstVT)
459     return false;
460
461   BasicBlock *DefBB = CI->getParent();
462
463   /// InsertedCasts - Only insert a cast in each block once.
464   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
465
466   bool MadeChange = false;
467   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
468        UI != E; ) {
469     Use &TheUse = UI.getUse();
470     Instruction *User = cast<Instruction>(*UI);
471
472     // Figure out which BB this cast is used in.  For PHI's this is the
473     // appropriate predecessor block.
474     BasicBlock *UserBB = User->getParent();
475     if (PHINode *PN = dyn_cast<PHINode>(User)) {
476       UserBB = PN->getIncomingBlock(UI);
477     }
478
479     // Preincrement use iterator so we don't invalidate it.
480     ++UI;
481
482     // If this user is in the same block as the cast, don't change the cast.
483     if (UserBB == DefBB) continue;
484
485     // If we have already inserted a cast into this block, use it.
486     CastInst *&InsertedCast = InsertedCasts[UserBB];
487
488     if (!InsertedCast) {
489       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
490
491       InsertedCast =
492         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
493                          InsertPt);
494       MadeChange = true;
495     }
496
497     // Replace a use of the cast with a use of the new cast.
498     TheUse = InsertedCast;
499   }
500
501   // If we removed all uses, nuke the cast.
502   if (CI->use_empty()) {
503     CI->eraseFromParent();
504     MadeChange = true;
505   }
506
507   return MadeChange;
508 }
509
510 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
511 /// the number of virtual registers that must be created and coalesced.  This is
512 /// a clear win except on targets with multiple condition code registers
513 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
514 ///
515 /// Return true if any changes are made.
516 static bool OptimizeCmpExpression(CmpInst *CI) {
517   BasicBlock *DefBB = CI->getParent();
518
519   /// InsertedCmp - Only insert a cmp in each block once.
520   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
521
522   bool MadeChange = false;
523   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
524        UI != E; ) {
525     Use &TheUse = UI.getUse();
526     Instruction *User = cast<Instruction>(*UI);
527
528     // Preincrement use iterator so we don't invalidate it.
529     ++UI;
530
531     // Don't bother for PHI nodes.
532     if (isa<PHINode>(User))
533       continue;
534
535     // Figure out which BB this cmp is used in.
536     BasicBlock *UserBB = User->getParent();
537
538     // If this user is in the same block as the cmp, don't change the cmp.
539     if (UserBB == DefBB) continue;
540
541     // If we have already inserted a cmp into this block, use it.
542     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
543
544     if (!InsertedCmp) {
545       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
546
547       InsertedCmp =
548         CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
549                         CI->getOperand(1), "", InsertPt);
550       MadeChange = true;
551     }
552
553     // Replace a use of the cmp with a use of the new cmp.
554     TheUse = InsertedCmp;
555   }
556
557   // If we removed all uses, nuke the cmp.
558   if (CI->use_empty())
559     CI->eraseFromParent();
560
561   return MadeChange;
562 }
563
564 //===----------------------------------------------------------------------===//
565 // Addressing Mode Analysis and Optimization
566 //===----------------------------------------------------------------------===//
567
568 //===----------------------------------------------------------------------===//
569 // Memory Optimization
570 //===----------------------------------------------------------------------===//
571
572 /// IsNonLocalValue - Return true if the specified values are defined in a
573 /// different basic block than BB.
574 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
575   if (Instruction *I = dyn_cast<Instruction>(V))
576     return I->getParent() != BB;
577   return false;
578 }
579
580 /// OptimizeMemoryInst - Load and Store Instructions have often have
581 /// addressing modes that can do significant amounts of computation.  As such,
582 /// instruction selection will try to get the load or store to do as much
583 /// computation as possible for the program.  The problem is that isel can only
584 /// see within a single block.  As such, we sink as much legal addressing mode
585 /// stuff into the block as possible.
586 ///
587 /// This method is used to optimize both load/store and inline asms with memory
588 /// operands.
589 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
590                                         const Type *AccessTy,
591                                         DenseMap<Value*,Value*> &SunkAddrs) {
592   // Figure out what addressing mode will be built up for this operation.
593   SmallVector<Instruction*, 16> AddrModeInsts;
594   ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
595                                                       AddrModeInsts, *TLI);
596
597   // Check to see if any of the instructions supersumed by this addr mode are
598   // non-local to I's BB.
599   bool AnyNonLocal = false;
600   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
601     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
602       AnyNonLocal = true;
603       break;
604     }
605   }
606
607   // If all the instructions matched are already in this BB, don't do anything.
608   if (!AnyNonLocal) {
609     DEBUG(cerr << "CGP: Found      local addrmode: " << AddrMode << "\n");
610     return false;
611   }
612
613   // Insert this computation right after this user.  Since our caller is
614   // scanning from the top of the BB to the bottom, reuse of the expr are
615   // guaranteed to happen later.
616   BasicBlock::iterator InsertPt = MemoryInst;
617
618   // Now that we determined the addressing expression we want to use and know
619   // that we have to sink it into this block.  Check to see if we have already
620   // done this for some other load/store instr in this block.  If so, reuse the
621   // computation.
622   Value *&SunkAddr = SunkAddrs[Addr];
623   if (SunkAddr) {
624     DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
625                << *MemoryInst);
626     if (SunkAddr->getType() != Addr->getType())
627       SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
628   } else {
629     DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
630                << *MemoryInst);
631     const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
632
633     Value *Result = 0;
634     // Start with the scale value.
635     if (AddrMode.Scale) {
636       Value *V = AddrMode.ScaledReg;
637       if (V->getType() == IntPtrTy) {
638         // done.
639       } else if (isa<PointerType>(V->getType())) {
640         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
641       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
642                  cast<IntegerType>(V->getType())->getBitWidth()) {
643         V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
644       } else {
645         V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
646       }
647       if (AddrMode.Scale != 1)
648         V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
649                                                           AddrMode.Scale),
650                                       "sunkaddr", InsertPt);
651       Result = V;
652     }
653
654     // Add in the base register.
655     if (AddrMode.BaseReg) {
656       Value *V = AddrMode.BaseReg;
657       if (V->getType() != IntPtrTy)
658         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
659       if (Result)
660         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
661       else
662         Result = V;
663     }
664
665     // Add in the BaseGV if present.
666     if (AddrMode.BaseGV) {
667       Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
668                                   InsertPt);
669       if (Result)
670         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
671       else
672         Result = V;
673     }
674
675     // Add in the Base Offset if present.
676     if (AddrMode.BaseOffs) {
677       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
678       if (Result)
679         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
680       else
681         Result = V;
682     }
683
684     if (Result == 0)
685       SunkAddr = Constant::getNullValue(Addr->getType());
686     else
687       SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
688   }
689
690   MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
691
692   if (Addr->use_empty())
693     RecursivelyDeleteTriviallyDeadInstructions(Addr);
694   return true;
695 }
696
697 /// OptimizeInlineAsmInst - If there are any memory operands, use
698 /// OptimizeMemoryInst to sink their address computing into the block when
699 /// possible / profitable.
700 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
701                                            DenseMap<Value*,Value*> &SunkAddrs) {
702   bool MadeChange = false;
703   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
704
705   // Do a prepass over the constraints, canonicalizing them, and building up the
706   // ConstraintOperands list.
707   std::vector<InlineAsm::ConstraintInfo>
708     ConstraintInfos = IA->ParseConstraints();
709
710   /// ConstraintOperands - Information about all of the constraints.
711   std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
712   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
713   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
714     ConstraintOperands.
715       push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
716     TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
717
718     // Compute the value type for each operand.
719     switch (OpInfo.Type) {
720     case InlineAsm::isOutput:
721       if (OpInfo.isIndirect)
722         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
723       break;
724     case InlineAsm::isInput:
725       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
726       break;
727     case InlineAsm::isClobber:
728       // Nothing to do.
729       break;
730     }
731
732     // Compute the constraint code and ConstraintType to use.
733     TLI->ComputeConstraintToUse(OpInfo, SDValue(),
734                              OpInfo.ConstraintType == TargetLowering::C_Memory);
735
736     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
737         OpInfo.isIndirect) {
738       Value *OpVal = OpInfo.CallOperandVal;
739       MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
740     }
741   }
742
743   return MadeChange;
744 }
745
746 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
747   BasicBlock *DefBB = I->getParent();
748
749   // If both result of the {s|z}xt and its source are live out, rewrite all
750   // other uses of the source with result of extension.
751   Value *Src = I->getOperand(0);
752   if (Src->hasOneUse())
753     return false;
754
755   // Only do this xform if truncating is free.
756   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
757     return false;
758
759   // Only safe to perform the optimization if the source is also defined in
760   // this block.
761   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
762     return false;
763
764   bool DefIsLiveOut = false;
765   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
766        UI != E; ++UI) {
767     Instruction *User = cast<Instruction>(*UI);
768
769     // Figure out which BB this ext is used in.
770     BasicBlock *UserBB = User->getParent();
771     if (UserBB == DefBB) continue;
772     DefIsLiveOut = true;
773     break;
774   }
775   if (!DefIsLiveOut)
776     return false;
777
778   // Make sure non of the uses are PHI nodes.
779   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
780        UI != E; ++UI) {
781     Instruction *User = cast<Instruction>(*UI);
782     BasicBlock *UserBB = User->getParent();
783     if (UserBB == DefBB) continue;
784     // Be conservative. We don't want this xform to end up introducing
785     // reloads just before load / store instructions.
786     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
787       return false;
788   }
789
790   // InsertedTruncs - Only insert one trunc in each block once.
791   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
792
793   bool MadeChange = false;
794   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
795        UI != E; ++UI) {
796     Use &TheUse = UI.getUse();
797     Instruction *User = cast<Instruction>(*UI);
798
799     // Figure out which BB this ext is used in.
800     BasicBlock *UserBB = User->getParent();
801     if (UserBB == DefBB) continue;
802
803     // Both src and def are live in this block. Rewrite the use.
804     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
805
806     if (!InsertedTrunc) {
807       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
808
809       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
810     }
811
812     // Replace a use of the {s|z}ext source with a use of the result.
813     TheUse = InsertedTrunc;
814
815     MadeChange = true;
816   }
817
818   return MadeChange;
819 }
820
821 // In this pass we look for GEP and cast instructions that are used
822 // across basic blocks and rewrite them to improve basic-block-at-a-time
823 // selection.
824 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
825   bool MadeChange = false;
826
827   // Split all critical edges where the dest block has a PHI.
828   TerminatorInst *BBTI = BB.getTerminator();
829   if (BBTI->getNumSuccessors() > 1) {
830     for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
831       BasicBlock *SuccBB = BBTI->getSuccessor(i);
832       if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
833         SplitEdgeNicely(BBTI, i, BackEdges, this);
834     }
835   }
836
837   // Keep track of non-local addresses that have been sunk into this block.
838   // This allows us to avoid inserting duplicate code for blocks with multiple
839   // load/stores of the same address.
840   DenseMap<Value*, Value*> SunkAddrs;
841
842   for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
843     Instruction *I = BBI++;
844
845     if (CastInst *CI = dyn_cast<CastInst>(I)) {
846       // If the source of the cast is a constant, then this should have
847       // already been constant folded.  The only reason NOT to constant fold
848       // it is if something (e.g. LSR) was careful to place the constant
849       // evaluation in a block other than then one that uses it (e.g. to hoist
850       // the address of globals out of a loop).  If this is the case, we don't
851       // want to forward-subst the cast.
852       if (isa<Constant>(CI->getOperand(0)))
853         continue;
854
855       bool Change = false;
856       if (TLI) {
857         Change = OptimizeNoopCopyExpression(CI, *TLI);
858         MadeChange |= Change;
859       }
860
861       if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
862         MadeChange |= OptimizeExtUses(I);
863     } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
864       MadeChange |= OptimizeCmpExpression(CI);
865     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
866       if (TLI)
867         MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
868                                          SunkAddrs);
869     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
870       if (TLI)
871         MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
872                                          SI->getOperand(0)->getType(),
873                                          SunkAddrs);
874     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
875       if (GEPI->hasAllZeroIndices()) {
876         /// The GEP operand must be a pointer, so must its result -> BitCast
877         Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
878                                           GEPI->getName(), GEPI);
879         GEPI->replaceAllUsesWith(NC);
880         GEPI->eraseFromParent();
881         MadeChange = true;
882         BBI = NC;
883       }
884     } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
885       // If we found an inline asm expession, and if the target knows how to
886       // lower it to normal LLVM code, do so now.
887       if (TLI && isa<InlineAsm>(CI->getCalledValue()))
888         if (const TargetAsmInfo *TAI =
889             TLI->getTargetMachine().getTargetAsmInfo()) {
890           if (TAI->ExpandInlineAsm(CI)) {
891             BBI = BB.begin();
892             // Avoid processing instructions out of order, which could cause
893             // reuse before a value is defined.
894             SunkAddrs.clear();
895           } else
896             // Sink address computing for memory operands into the block.
897             MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
898         }
899     }
900   }
901
902   return MadeChange;
903 }