refactor TryToSimplifyUncondBranchFromEmptyBlock out of SimplifyCFG.
[oota-llvm.git] / lib / Transforms / Utils / Local.cpp
1 //===-- Local.cpp - Functions to perform local transformations ------------===//
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 family of functions perform various local transformations to the
11 // program.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/GlobalAlias.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/Analysis/ProfileInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Support/CFG.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm;
35
36 //===----------------------------------------------------------------------===//
37 //  Local analysis.
38 //
39
40 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
41 /// from this value cannot trap.  If it is not obviously safe to load from the
42 /// specified pointer, we do a quick local scan of the basic block containing
43 /// ScanFrom, to determine if the address is already accessed.
44 bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
45   // If it is an alloca it is always safe to load from.
46   if (isa<AllocaInst>(V)) return true;
47
48   // If it is a global variable it is mostly safe to load from.
49   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
50     // Don't try to evaluate aliases.  External weak GV can be null.
51     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
52
53   // Otherwise, be a little bit agressive by scanning the local block where we
54   // want to check to see if the pointer is already being loaded or stored
55   // from/to.  If so, the previous load or store would have already trapped,
56   // so there is no harm doing an extra load (also, CSE will later eliminate
57   // the load entirely).
58   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
59
60   while (BBI != E) {
61     --BBI;
62
63     // If we see a free or a call which may write to memory (i.e. which might do
64     // a free) the pointer could be marked invalid.
65     if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
66         !isa<DbgInfoIntrinsic>(BBI))
67       return false;
68
69     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
70       if (LI->getOperand(0) == V) return true;
71     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
72       if (SI->getOperand(1) == V) return true;
73     }
74   }
75   return false;
76 }
77
78
79 //===----------------------------------------------------------------------===//
80 //  Local constant propagation.
81 //
82
83 // ConstantFoldTerminator - If a terminator instruction is predicated on a
84 // constant value, convert it into an unconditional branch to the constant
85 // destination.
86 //
87 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
88   TerminatorInst *T = BB->getTerminator();
89
90   // Branch - See if we are conditional jumping on constant
91   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
92     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
93     BasicBlock *Dest1 = BI->getSuccessor(0);
94     BasicBlock *Dest2 = BI->getSuccessor(1);
95
96     if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
97       // Are we branching on constant?
98       // YES.  Change to unconditional branch...
99       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
100       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
101
102       //cerr << "Function: " << T->getParent()->getParent()
103       //     << "\nRemoving branch from " << T->getParent()
104       //     << "\n\nTo: " << OldDest << endl;
105
106       // Let the basic block know that we are letting go of it.  Based on this,
107       // it will adjust it's PHI nodes.
108       assert(BI->getParent() && "Terminator not inserted in block!");
109       OldDest->removePredecessor(BI->getParent());
110
111       // Set the unconditional destination, and change the insn to be an
112       // unconditional branch.
113       BI->setUnconditionalDest(Destination);
114       return true;
115     }
116     
117     if (Dest2 == Dest1) {       // Conditional branch to same location?
118       // This branch matches something like this:
119       //     br bool %cond, label %Dest, label %Dest
120       // and changes it into:  br label %Dest
121
122       // Let the basic block know that we are letting go of one copy of it.
123       assert(BI->getParent() && "Terminator not inserted in block!");
124       Dest1->removePredecessor(BI->getParent());
125
126       // Change a conditional branch to unconditional.
127       BI->setUnconditionalDest(Dest1);
128       return true;
129     }
130     return false;
131   }
132   
133   if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
134     // If we are switching on a constant, we can convert the switch into a
135     // single branch instruction!
136     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
137     BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
138     BasicBlock *DefaultDest = TheOnlyDest;
139     assert(TheOnlyDest == SI->getDefaultDest() &&
140            "Default destination is not successor #0?");
141
142     // Figure out which case it goes to.
143     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
144       // Found case matching a constant operand?
145       if (SI->getSuccessorValue(i) == CI) {
146         TheOnlyDest = SI->getSuccessor(i);
147         break;
148       }
149
150       // Check to see if this branch is going to the same place as the default
151       // dest.  If so, eliminate it as an explicit compare.
152       if (SI->getSuccessor(i) == DefaultDest) {
153         // Remove this entry.
154         DefaultDest->removePredecessor(SI->getParent());
155         SI->removeCase(i);
156         --i; --e;  // Don't skip an entry...
157         continue;
158       }
159
160       // Otherwise, check to see if the switch only branches to one destination.
161       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
162       // destinations.
163       if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
164     }
165
166     if (CI && !TheOnlyDest) {
167       // Branching on a constant, but not any of the cases, go to the default
168       // successor.
169       TheOnlyDest = SI->getDefaultDest();
170     }
171
172     // If we found a single destination that we can fold the switch into, do so
173     // now.
174     if (TheOnlyDest) {
175       // Insert the new branch.
176       BranchInst::Create(TheOnlyDest, SI);
177       BasicBlock *BB = SI->getParent();
178
179       // Remove entries from PHI nodes which we no longer branch to...
180       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
181         // Found case matching a constant operand?
182         BasicBlock *Succ = SI->getSuccessor(i);
183         if (Succ == TheOnlyDest)
184           TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
185         else
186           Succ->removePredecessor(BB);
187       }
188
189       // Delete the old switch.
190       BB->getInstList().erase(SI);
191       return true;
192     }
193     
194     if (SI->getNumSuccessors() == 2) {
195       // Otherwise, we can fold this switch into a conditional branch
196       // instruction if it has only one non-default destination.
197       Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
198                                  SI->getSuccessorValue(1), "cond");
199       // Insert the new branch.
200       BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
201
202       // Delete the old switch.
203       SI->eraseFromParent();
204       return true;
205     }
206     return false;
207   }
208
209   if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
210     // indirectbr blockaddress(@F, @BB) -> br label @BB
211     if (BlockAddress *BA =
212           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
213       BasicBlock *TheOnlyDest = BA->getBasicBlock();
214       // Insert the new branch.
215       BranchInst::Create(TheOnlyDest, IBI);
216       
217       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
218         if (IBI->getDestination(i) == TheOnlyDest)
219           TheOnlyDest = 0;
220         else
221           IBI->getDestination(i)->removePredecessor(IBI->getParent());
222       }
223       IBI->eraseFromParent();
224       
225       // If we didn't find our destination in the IBI successor list, then we
226       // have undefined behavior.  Replace the unconditional branch with an
227       // 'unreachable' instruction.
228       if (TheOnlyDest) {
229         BB->getTerminator()->eraseFromParent();
230         new UnreachableInst(BB->getContext(), BB);
231       }
232       
233       return true;
234     }
235   }
236   
237   return false;
238 }
239
240
241 //===----------------------------------------------------------------------===//
242 //  Local dead code elimination...
243 //
244
245 /// isInstructionTriviallyDead - Return true if the result produced by the
246 /// instruction is not used, and the instruction has no side effects.
247 ///
248 bool llvm::isInstructionTriviallyDead(Instruction *I) {
249   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
250
251   // We don't want debug info removed by anything this general.
252   if (isa<DbgInfoIntrinsic>(I)) return false;
253
254   if (!I->mayHaveSideEffects()) return true;
255
256   // Special case intrinsics that "may have side effects" but can be deleted
257   // when dead.
258   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
259     // Safe to delete llvm.stacksave if dead.
260     if (II->getIntrinsicID() == Intrinsic::stacksave)
261       return true;
262   return false;
263 }
264
265 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
266 /// trivially dead instruction, delete it.  If that makes any of its operands
267 /// trivially dead, delete them too, recursively.
268 void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
269   Instruction *I = dyn_cast<Instruction>(V);
270   if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
271     return;
272   
273   SmallVector<Instruction*, 16> DeadInsts;
274   DeadInsts.push_back(I);
275   
276   while (!DeadInsts.empty()) {
277     I = DeadInsts.pop_back_val();
278
279     // Null out all of the instruction's operands to see if any operand becomes
280     // dead as we go.
281     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
282       Value *OpV = I->getOperand(i);
283       I->setOperand(i, 0);
284       
285       if (!OpV->use_empty()) continue;
286     
287       // If the operand is an instruction that became dead as we nulled out the
288       // operand, and if it is 'trivially' dead, delete it in a future loop
289       // iteration.
290       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
291         if (isInstructionTriviallyDead(OpI))
292           DeadInsts.push_back(OpI);
293     }
294     
295     I->eraseFromParent();
296   }
297 }
298
299 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
300 /// dead PHI node, due to being a def-use chain of single-use nodes that
301 /// either forms a cycle or is terminated by a trivially dead instruction,
302 /// delete it.  If that makes any of its operands trivially dead, delete them
303 /// too, recursively.
304 void
305 llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
306   // We can remove a PHI if it is on a cycle in the def-use graph
307   // where each node in the cycle has degree one, i.e. only one use,
308   // and is an instruction with no side effects.
309   if (!PN->hasOneUse())
310     return;
311
312   SmallPtrSet<PHINode *, 4> PHIs;
313   PHIs.insert(PN);
314   for (Instruction *J = cast<Instruction>(*PN->use_begin());
315        J->hasOneUse() && !J->mayHaveSideEffects();
316        J = cast<Instruction>(*J->use_begin()))
317     // If we find a PHI more than once, we're on a cycle that
318     // won't prove fruitful.
319     if (PHINode *JP = dyn_cast<PHINode>(J))
320       if (!PHIs.insert(cast<PHINode>(JP))) {
321         // Break the cycle and delete the PHI and its operands.
322         JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
323         RecursivelyDeleteTriviallyDeadInstructions(JP);
324         break;
325       }
326 }
327
328 //===----------------------------------------------------------------------===//
329 //  Control Flow Graph Restructuring...
330 //
331
332 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
333 /// predecessor is known to have one successor (DestBB!).  Eliminate the edge
334 /// between them, moving the instructions in the predecessor into DestBB and
335 /// deleting the predecessor block.
336 ///
337 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
338   // If BB has single-entry PHI nodes, fold them.
339   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
340     Value *NewVal = PN->getIncomingValue(0);
341     // Replace self referencing PHI with undef, it must be dead.
342     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
343     PN->replaceAllUsesWith(NewVal);
344     PN->eraseFromParent();
345   }
346   
347   BasicBlock *PredBB = DestBB->getSinglePredecessor();
348   assert(PredBB && "Block doesn't have a single predecessor!");
349   
350   // Splice all the instructions from PredBB to DestBB.
351   PredBB->getTerminator()->eraseFromParent();
352   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
353   
354   // Anything that branched to PredBB now branches to DestBB.
355   PredBB->replaceAllUsesWith(DestBB);
356   
357   if (P) {
358     ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
359     if (PI) {
360       PI->replaceAllUses(PredBB, DestBB);
361       PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
362     }
363   }
364   // Nuke BB.
365   PredBB->eraseFromParent();
366 }
367
368 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
369 /// almost-empty BB ending in an unconditional branch to Succ, into succ.
370 ///
371 /// Assumption: Succ is the single successor for BB.
372 ///
373 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
374   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
375
376   DEBUG(errs() << "Looking to fold " << BB->getName() << " into " 
377         << Succ->getName() << "\n");
378   // Shortcut, if there is only a single predecessor it must be BB and merging
379   // is always safe
380   if (Succ->getSinglePredecessor()) return true;
381
382   // Make a list of the predecessors of BB
383   typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
384   BlockSet BBPreds(pred_begin(BB), pred_end(BB));
385
386   // Use that list to make another list of common predecessors of BB and Succ
387   BlockSet CommonPreds;
388   for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
389         PI != PE; ++PI)
390     if (BBPreds.count(*PI))
391       CommonPreds.insert(*PI);
392
393   // Shortcut, if there are no common predecessors, merging is always safe
394   if (CommonPreds.empty())
395     return true;
396   
397   // Look at all the phi nodes in Succ, to see if they present a conflict when
398   // merging these blocks
399   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
400     PHINode *PN = cast<PHINode>(I);
401
402     // If the incoming value from BB is again a PHINode in
403     // BB which has the same incoming value for *PI as PN does, we can
404     // merge the phi nodes and then the blocks can still be merged
405     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
406     if (BBPN && BBPN->getParent() == BB) {
407       for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
408             PI != PE; PI++) {
409         if (BBPN->getIncomingValueForBlock(*PI) 
410               != PN->getIncomingValueForBlock(*PI)) {
411           DEBUG(errs() << "Can't fold, phi node " << PN->getName() << " in " 
412                 << Succ->getName() << " is conflicting with " 
413                 << BBPN->getName() << " with regard to common predecessor "
414                 << (*PI)->getName() << "\n");
415           return false;
416         }
417       }
418     } else {
419       Value* Val = PN->getIncomingValueForBlock(BB);
420       for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
421             PI != PE; PI++) {
422         // See if the incoming value for the common predecessor is equal to the
423         // one for BB, in which case this phi node will not prevent the merging
424         // of the block.
425         if (Val != PN->getIncomingValueForBlock(*PI)) {
426           DEBUG(errs() << "Can't fold, phi node " << PN->getName() << " in " 
427                 << Succ->getName() << " is conflicting with regard to common "
428                 << "predecessor " << (*PI)->getName() << "\n");
429           return false;
430         }
431       }
432     }
433   }
434
435   return true;
436 }
437
438 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
439 /// unconditional branch, and contains no instructions other than PHI nodes,
440 /// potential debug intrinsics and the branch.  If possible, eliminate BB by
441 /// rewriting all the predecessors to branch to the successor block and return
442 /// true.  If we can't transform, return false.
443 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
444   // We can't eliminate infinite loops.
445   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
446   if (BB == Succ) return false;
447   
448   // Check to see if merging these blocks would cause conflicts for any of the
449   // phi nodes in BB or Succ. If not, we can safely merge.
450   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
451
452   // Check for cases where Succ has multiple predecessors and a PHI node in BB
453   // has uses which will not disappear when the PHI nodes are merged.  It is
454   // possible to handle such cases, but difficult: it requires checking whether
455   // BB dominates Succ, which is non-trivial to calculate in the case where
456   // Succ has multiple predecessors.  Also, it requires checking whether
457   // constructing the necessary self-referential PHI node doesn't intoduce any
458   // conflicts; this isn't too difficult, but the previous code for doing this
459   // was incorrect.
460   //
461   // Note that if this check finds a live use, BB dominates Succ, so BB is
462   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
463   // folding the branch isn't profitable in that case anyway.
464   if (!Succ->getSinglePredecessor()) {
465     BasicBlock::iterator BBI = BB->begin();
466     while (isa<PHINode>(*BBI)) {
467       for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
468            UI != E; ++UI) {
469         if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
470           if (PN->getIncomingBlock(UI) != BB)
471             return false;
472         } else {
473           return false;
474         }
475       }
476       ++BBI;
477     }
478   }
479
480   DEBUG(errs() << "Killing Trivial BB: \n" << *BB);
481   
482   if (isa<PHINode>(Succ->begin())) {
483     // If there is more than one pred of succ, and there are PHI nodes in
484     // the successor, then we need to add incoming edges for the PHI nodes
485     //
486     const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
487     
488     // Loop over all of the PHI nodes in the successor of BB.
489     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
490       PHINode *PN = cast<PHINode>(I);
491       Value *OldVal = PN->removeIncomingValue(BB, false);
492       assert(OldVal && "No entry in PHI for Pred BB!");
493       
494       // If this incoming value is one of the PHI nodes in BB, the new entries
495       // in the PHI node are the entries from the old PHI.
496       if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
497         PHINode *OldValPN = cast<PHINode>(OldVal);
498         for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
499           // Note that, since we are merging phi nodes and BB and Succ might
500           // have common predecessors, we could end up with a phi node with
501           // identical incoming branches. This will be cleaned up later (and
502           // will trigger asserts if we try to clean it up now, without also
503           // simplifying the corresponding conditional branch).
504           PN->addIncoming(OldValPN->getIncomingValue(i),
505                           OldValPN->getIncomingBlock(i));
506       } else {
507         // Add an incoming value for each of the new incoming values.
508         for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
509           PN->addIncoming(OldVal, BBPreds[i]);
510       }
511     }
512   }
513   
514   while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
515     if (Succ->getSinglePredecessor()) {
516       // BB is the only predecessor of Succ, so Succ will end up with exactly
517       // the same predecessors BB had.
518       Succ->getInstList().splice(Succ->begin(),
519                                  BB->getInstList(), BB->begin());
520     } else {
521       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
522       assert(PN->use_empty() && "There shouldn't be any uses here!");
523       PN->eraseFromParent();
524     }
525   }
526     
527   // Everything that jumped to BB now goes to Succ.
528   BB->replaceAllUsesWith(Succ);
529   if (!Succ->hasName()) Succ->takeName(BB);
530   BB->eraseFromParent();              // Delete the old basic block.
531   return true;
532 }
533
534
535
536 /// OnlyUsedByDbgIntrinsics - Return true if the instruction I is only used
537 /// by DbgIntrinsics. If DbgInUses is specified then the vector is filled 
538 /// with the DbgInfoIntrinsic that use the instruction I.
539 bool llvm::OnlyUsedByDbgInfoIntrinsics(Instruction *I, 
540                                SmallVectorImpl<DbgInfoIntrinsic *> *DbgInUses) {
541   if (DbgInUses)
542     DbgInUses->clear();
543
544   for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; 
545        ++UI) {
546     if (DbgInfoIntrinsic *DI = dyn_cast<DbgInfoIntrinsic>(*UI)) {
547       if (DbgInUses)
548         DbgInUses->push_back(DI);
549     } else {
550       if (DbgInUses)
551         DbgInUses->clear();
552       return false;
553     }
554   }
555   return true;
556 }
557