BasicBlockUtils.cpp revision 605e2b518445d86491e1a0c812f7c85193d3517a
1//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
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 manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/BasicBlockUtils.h"
16#include "llvm/Function.h"
17#include "llvm/Instructions.h"
18#include "llvm/IntrinsicInst.h"
19#include "llvm/Constant.h"
20#include "llvm/Type.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/Dominators.h"
23#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Analysis/MemoryDependenceAnalysis.h"
25#include "llvm/Target/TargetData.h"
26#include "llvm/Transforms/Utils/Local.h"
27#include "llvm/Transforms/Scalar.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/ValueHandle.h"
30#include <algorithm>
31using namespace llvm;
32
33/// DeleteDeadBlock - Delete the specified block, which must have no
34/// predecessors.
35void llvm::DeleteDeadBlock(BasicBlock *BB) {
36  assert((pred_begin(BB) == pred_end(BB) ||
37         // Can delete self loop.
38         BB->getSinglePredecessor() == BB) && "Block is not dead!");
39  TerminatorInst *BBTerm = BB->getTerminator();
40
41  // Loop through all of our successors and make sure they know that one
42  // of their predecessors is going away.
43  for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
44    BBTerm->getSuccessor(i)->removePredecessor(BB);
45
46  // Zap all the instructions in the block.
47  while (!BB->empty()) {
48    Instruction &I = BB->back();
49    // If this instruction is used, replace uses with an arbitrary value.
50    // Because control flow can't get here, we don't care what we replace the
51    // value with.  Note that since this block is unreachable, and all values
52    // contained within it must dominate their uses, that all uses will
53    // eventually be removed (they are themselves dead).
54    if (!I.use_empty())
55      I.replaceAllUsesWith(UndefValue::get(I.getType()));
56    BB->getInstList().pop_back();
57  }
58
59  // Zap the block!
60  BB->eraseFromParent();
61}
62
63/// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
64/// any single-entry PHI nodes in it, fold them away.  This handles the case
65/// when all entries to the PHI nodes in a block are guaranteed equal, such as
66/// when the block has exactly one predecessor.
67void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P) {
68  if (!isa<PHINode>(BB->begin())) return;
69
70  AliasAnalysis *AA = 0;
71  MemoryDependenceAnalysis *MemDep = 0;
72  if (P) {
73    AA = P->getAnalysisIfAvailable<AliasAnalysis>();
74    MemDep = P->getAnalysisIfAvailable<MemoryDependenceAnalysis>();
75  }
76
77  while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
78    if (PN->getIncomingValue(0) != PN)
79      PN->replaceAllUsesWith(PN->getIncomingValue(0));
80    else
81      PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
82
83    if (MemDep)
84      MemDep->removeInstruction(PN);  // Memdep updates AA itself.
85    else if (AA && isa<PointerType>(PN->getType()))
86      AA->deleteValue(PN);
87
88    PN->eraseFromParent();
89  }
90}
91
92
93/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
94/// is dead. Also recursively delete any operands that become dead as
95/// a result. This includes tracing the def-use list from the PHI to see if
96/// it is ultimately unused or if it reaches an unused cycle.
97bool llvm::DeleteDeadPHIs(BasicBlock *BB) {
98  // Recursively deleting a PHI may cause multiple PHIs to be deleted
99  // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
100  SmallVector<WeakVH, 8> PHIs;
101  for (BasicBlock::iterator I = BB->begin();
102       PHINode *PN = dyn_cast<PHINode>(I); ++I)
103    PHIs.push_back(PN);
104
105  bool Changed = false;
106  for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
107    if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
108      Changed |= RecursivelyDeleteDeadPHINode(PN);
109
110  return Changed;
111}
112
113/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
114/// if possible.  The return value indicates success or failure.
115bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
116  // Don't merge away blocks who have their address taken.
117  if (BB->hasAddressTaken()) return false;
118
119  // Can't merge if there are multiple predecessors, or no predecessors.
120  BasicBlock *PredBB = BB->getUniquePredecessor();
121  if (!PredBB) return false;
122
123  // Don't break self-loops.
124  if (PredBB == BB) return false;
125  // Don't break invokes.
126  if (isa<InvokeInst>(PredBB->getTerminator())) return false;
127
128  succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
129  BasicBlock *OnlySucc = BB;
130  for (; SI != SE; ++SI)
131    if (*SI != OnlySucc) {
132      OnlySucc = 0;     // There are multiple distinct successors!
133      break;
134    }
135
136  // Can't merge if there are multiple successors.
137  if (!OnlySucc) return false;
138
139  // Can't merge if there is PHI loop.
140  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
141    if (PHINode *PN = dyn_cast<PHINode>(BI)) {
142      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
143        if (PN->getIncomingValue(i) == PN)
144          return false;
145    } else
146      break;
147  }
148
149  // Begin by getting rid of unneeded PHIs.
150  if (isa<PHINode>(BB->front()))
151    FoldSingleEntryPHINodes(BB, P);
152
153  // Delete the unconditional branch from the predecessor...
154  PredBB->getInstList().pop_back();
155
156  // Make all PHI nodes that referred to BB now refer to Pred as their
157  // source...
158  BB->replaceAllUsesWith(PredBB);
159
160  // Move all definitions in the successor to the predecessor...
161  PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
162
163  // Inherit predecessors name if it exists.
164  if (!PredBB->hasName())
165    PredBB->takeName(BB);
166
167  // Finally, erase the old block and update dominator info.
168  if (P) {
169    if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
170      if (DomTreeNode *DTN = DT->getNode(BB)) {
171        DomTreeNode *PredDTN = DT->getNode(PredBB);
172        SmallVector<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
173        for (SmallVector<DomTreeNode*, 8>::iterator DI = Children.begin(),
174             DE = Children.end(); DI != DE; ++DI)
175          DT->changeImmediateDominator(*DI, PredDTN);
176
177        DT->eraseNode(BB);
178      }
179
180      if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
181        LI->removeBlock(BB);
182
183      if (MemoryDependenceAnalysis *MD =
184            P->getAnalysisIfAvailable<MemoryDependenceAnalysis>())
185        MD->invalidateCachedPredecessors();
186    }
187  }
188
189  BB->eraseFromParent();
190  return true;
191}
192
193/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
194/// with a value, then remove and delete the original instruction.
195///
196void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
197                                BasicBlock::iterator &BI, Value *V) {
198  Instruction &I = *BI;
199  // Replaces all of the uses of the instruction with uses of the value
200  I.replaceAllUsesWith(V);
201
202  // Make sure to propagate a name if there is one already.
203  if (I.hasName() && !V->hasName())
204    V->takeName(&I);
205
206  // Delete the unnecessary instruction now...
207  BI = BIL.erase(BI);
208}
209
210
211/// ReplaceInstWithInst - Replace the instruction specified by BI with the
212/// instruction specified by I.  The original instruction is deleted and BI is
213/// updated to point to the new instruction.
214///
215void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
216                               BasicBlock::iterator &BI, Instruction *I) {
217  assert(I->getParent() == 0 &&
218         "ReplaceInstWithInst: Instruction already inserted into basic block!");
219
220  // Insert the new instruction into the basic block...
221  BasicBlock::iterator New = BIL.insert(BI, I);
222
223  // Replace all uses of the old instruction, and delete it.
224  ReplaceInstWithValue(BIL, BI, I);
225
226  // Move BI back to point to the newly inserted instruction
227  BI = New;
228}
229
230/// ReplaceInstWithInst - Replace the instruction specified by From with the
231/// instruction specified by To.
232///
233void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
234  BasicBlock::iterator BI(From);
235  ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
236}
237
238/// GetSuccessorNumber - Search for the specified successor of basic block BB
239/// and return its position in the terminator instruction's list of
240/// successors.  It is an error to call this with a block that is not a
241/// successor.
242unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
243  TerminatorInst *Term = BB->getTerminator();
244#ifndef NDEBUG
245  unsigned e = Term->getNumSuccessors();
246#endif
247  for (unsigned i = 0; ; ++i) {
248    assert(i != e && "Didn't find edge?");
249    if (Term->getSuccessor(i) == Succ)
250      return i;
251  }
252  return 0;
253}
254
255/// SplitEdge -  Split the edge connecting specified block. Pass P must
256/// not be NULL.
257BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
258  unsigned SuccNum = GetSuccessorNumber(BB, Succ);
259
260  // If this is a critical edge, let SplitCriticalEdge do it.
261  TerminatorInst *LatchTerm = BB->getTerminator();
262  if (SplitCriticalEdge(LatchTerm, SuccNum, P))
263    return LatchTerm->getSuccessor(SuccNum);
264
265  // If the edge isn't critical, then BB has a single successor or Succ has a
266  // single pred.  Split the block.
267  BasicBlock::iterator SplitPoint;
268  if (BasicBlock *SP = Succ->getSinglePredecessor()) {
269    // If the successor only has a single pred, split the top of the successor
270    // block.
271    assert(SP == BB && "CFG broken");
272    SP = NULL;
273    return SplitBlock(Succ, Succ->begin(), P);
274  }
275
276  // Otherwise, if BB has a single successor, split it at the bottom of the
277  // block.
278  assert(BB->getTerminator()->getNumSuccessors() == 1 &&
279         "Should have a single succ!");
280  return SplitBlock(BB, BB->getTerminator(), P);
281}
282
283/// SplitBlock - Split the specified block at the specified instruction - every
284/// thing before SplitPt stays in Old and everything starting with SplitPt moves
285/// to a new block.  The two blocks are joined by an unconditional branch and
286/// the loop info is updated.
287///
288BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
289  BasicBlock::iterator SplitIt = SplitPt;
290  while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
291    ++SplitIt;
292  BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
293
294  // The new block lives in whichever loop the old one did. This preserves
295  // LCSSA as well, because we force the split point to be after any PHI nodes.
296  if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
297    if (Loop *L = LI->getLoopFor(Old))
298      L->addBasicBlockToLoop(New, LI->getBase());
299
300  if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
301    // Old dominates New. New node dominates all other nodes dominated by Old.
302    if (DomTreeNode *OldNode = DT->getNode(Old)) {
303      std::vector<DomTreeNode *> Children;
304      for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
305           I != E; ++I)
306        Children.push_back(*I);
307
308      DomTreeNode *NewNode = DT->addNewBlock(New,Old);
309      for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
310             E = Children.end(); I != E; ++I)
311        DT->changeImmediateDominator(*I, NewNode);
312    }
313  }
314
315  return New;
316}
317
318/// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
319/// analysis information.
320static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
321                                      ArrayRef<BasicBlock *> Preds,
322                                      Pass *P, bool &HasLoopExit) {
323  if (!P) return;
324
325  LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
326  Loop *L = LI ? LI->getLoopFor(OldBB) : 0;
327
328  // If we need to preserve loop analyses, collect some information about how
329  // this split will affect loops.
330  bool IsLoopEntry = !!L;
331  bool SplitMakesNewLoopHeader = false;
332  if (LI) {
333    bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
334    for (ArrayRef<BasicBlock*>::iterator
335           i = Preds.begin(), e = Preds.end(); i != e; ++i) {
336      BasicBlock *Pred = *i;
337
338      // If we need to preserve LCSSA, determine if any of the preds is a loop
339      // exit.
340      if (PreserveLCSSA)
341        if (Loop *PL = LI->getLoopFor(Pred))
342          if (!PL->contains(OldBB))
343            HasLoopExit = true;
344
345      // If we need to preserve LoopInfo, note whether any of the preds crosses
346      // an interesting loop boundary.
347      if (!L) continue;
348      if (L->contains(Pred))
349        IsLoopEntry = false;
350      else
351        SplitMakesNewLoopHeader = true;
352    }
353  }
354
355  // Update dominator tree if available.
356  DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
357  if (DT)
358    DT->splitBlock(NewBB);
359
360  if (!L) return;
361
362  if (IsLoopEntry) {
363    // Add the new block to the nearest enclosing loop (and not an adjacent
364    // loop). To find this, examine each of the predecessors and determine which
365    // loops enclose them, and select the most-nested loop which contains the
366    // loop containing the block being split.
367    Loop *InnermostPredLoop = 0;
368    for (ArrayRef<BasicBlock*>::iterator
369           i = Preds.begin(), e = Preds.end(); i != e; ++i) {
370      BasicBlock *Pred = *i;
371      if (Loop *PredLoop = LI->getLoopFor(Pred)) {
372        // Seek a loop which actually contains the block being split (to avoid
373        // adjacent loops).
374        while (PredLoop && !PredLoop->contains(OldBB))
375          PredLoop = PredLoop->getParentLoop();
376
377        // Select the most-nested of these loops which contains the block.
378        if (PredLoop && PredLoop->contains(OldBB) &&
379            (!InnermostPredLoop ||
380             InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
381          InnermostPredLoop = PredLoop;
382      }
383    }
384
385    if (InnermostPredLoop)
386      InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
387  } else {
388    L->addBasicBlockToLoop(NewBB, LI->getBase());
389    if (SplitMakesNewLoopHeader)
390      L->moveToHeader(NewBB);
391  }
392}
393
394/// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
395/// from NewBB. This also updates AliasAnalysis, if available.
396static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
397                           ArrayRef<BasicBlock*> Preds, BranchInst *BI,
398                           Pass *P, bool HasLoopExit) {
399  // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
400  AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
401  for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
402    PHINode *PN = cast<PHINode>(I++);
403
404    // Check to see if all of the values coming in are the same.  If so, we
405    // don't need to create a new PHI node, unless it's needed for LCSSA.
406    Value *InVal = 0;
407    if (!HasLoopExit) {
408      InVal = PN->getIncomingValueForBlock(Preds[0]);
409      for (unsigned i = 1, e = Preds.size(); i != e; ++i)
410        if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
411          InVal = 0;
412          break;
413        }
414    }
415
416    if (InVal) {
417      // If all incoming values for the new PHI would be the same, just don't
418      // make a new PHI.  Instead, just remove the incoming values from the old
419      // PHI.
420      for (unsigned i = 0, e = Preds.size(); i != e; ++i)
421        PN->removeIncomingValue(Preds[i], false);
422    } else {
423      // If the values coming into the block are not the same, we need a PHI.
424      // Create the new PHI node, insert it into NewBB at the end of the block
425      PHINode *NewPHI =
426        PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
427      if (AA) AA->copyValue(PN, NewPHI);
428
429      // Move all of the PHI values for 'Preds' to the new PHI.
430      for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
431        Value *V = PN->removeIncomingValue(Preds[i], false);
432        NewPHI->addIncoming(V, Preds[i]);
433      }
434
435      InVal = NewPHI;
436    }
437
438    // Add an incoming value to the PHI node in the loop for the preheader
439    // edge.
440    PN->addIncoming(InVal, NewBB);
441  }
442}
443
444/// SplitBlockPredecessors - This method transforms BB by introducing a new
445/// basic block into the function, and moving some of the predecessors of BB to
446/// be predecessors of the new block.  The new predecessors are indicated by the
447/// Preds array, which has NumPreds elements in it.  The new block is given a
448/// suffix of 'Suffix'.
449///
450/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
451/// LoopInfo, and LCCSA but no other analyses. In particular, it does not
452/// preserve LoopSimplify (because it's complicated to handle the case where one
453/// of the edges being split is an exit of a loop with other exits).
454///
455BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
456                                         BasicBlock *const *Preds,
457                                         unsigned NumPreds, const char *Suffix,
458                                         Pass *P) {
459  // Create new basic block, insert right before the original block.
460  BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
461                                         BB->getParent(), BB);
462
463  // The new block unconditionally branches to the old block.
464  BranchInst *BI = BranchInst::Create(BB, NewBB);
465
466  // Move the edges from Preds to point to NewBB instead of BB.
467  for (unsigned i = 0; i != NumPreds; ++i) {
468    // This is slightly more strict than necessary; the minimum requirement
469    // is that there be no more than one indirectbr branching to BB. And
470    // all BlockAddress uses would need to be updated.
471    assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
472           "Cannot split an edge from an IndirectBrInst");
473    Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
474  }
475
476  // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
477  // node becomes an incoming value for BB's phi node.  However, if the Preds
478  // list is empty, we need to insert dummy entries into the PHI nodes in BB to
479  // account for the newly created predecessor.
480  if (NumPreds == 0) {
481    // Insert dummy values as the incoming value.
482    for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
483      cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
484    return NewBB;
485  }
486
487  // Update DominatorTree, LoopInfo, and LCCSA analysis information.
488  bool HasLoopExit = false;
489  UpdateAnalysisInformation(BB, NewBB, ArrayRef<BasicBlock*>(Preds, NumPreds),
490                            P, HasLoopExit);
491
492  // Update the PHI nodes in BB with the values coming from NewBB.
493  UpdatePHINodes(BB, NewBB, ArrayRef<BasicBlock*>(Preds, NumPreds), BI,
494                 P, HasLoopExit);
495  return NewBB;
496}
497
498/// SplitLandingPadPredecessors - This method transforms the landing pad,
499/// OrigBB, by introducing two new basic blocks into the function. One of those
500/// new basic blocks gets the predecessors listed in Preds. The other basic
501/// block gets the remaining predecessors of OrigBB. The landingpad instruction
502/// OrigBB is clone into both of the new basic blocks. The new blocks are given
503/// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
504///
505/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
506/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
507/// it does not preserve LoopSimplify (because it's complicated to handle the
508/// case where one of the edges being split is an exit of a loop with other
509/// exits).
510///
511void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
512                                       ArrayRef<BasicBlock*> Preds,
513                                       const char *Suffix1, const char *Suffix2,
514                                       Pass *P,
515                                       SmallVectorImpl<BasicBlock*> &NewBBs) {
516  assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
517
518  // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
519  // it right before the original block.
520  BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
521                                          OrigBB->getName() + Suffix1,
522                                          OrigBB->getParent(), OrigBB);
523  NewBBs.push_back(NewBB1);
524
525  // The new block unconditionally branches to the old block.
526  BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
527
528  // Move the edges from Preds to point to NewBB1 instead of OrigBB.
529  for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
530    // This is slightly more strict than necessary; the minimum requirement
531    // is that there be no more than one indirectbr branching to BB. And
532    // all BlockAddress uses would need to be updated.
533    assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
534           "Cannot split an edge from an IndirectBrInst");
535    Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
536  }
537
538  // Update DominatorTree, LoopInfo, and LCCSA analysis information.
539  bool HasLoopExit = false;
540  UpdateAnalysisInformation(OrigBB, NewBB1, Preds, P, HasLoopExit);
541
542  // Update the PHI nodes in OrigBB with the values coming from NewBB1.
543  UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, P, HasLoopExit);
544
545  // Move the remaining edges from OrigBB to point to NewBB2.
546  SmallVector<BasicBlock*, 8> NewBB2Preds;
547  for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
548       i != e; ) {
549    BasicBlock *Pred = *i++;
550    if (Pred == NewBB1) continue;
551    assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
552           "Cannot split an edge from an IndirectBrInst");
553    NewBB2Preds.push_back(Pred);
554    e = pred_end(OrigBB);
555  }
556
557  BasicBlock *NewBB2 = 0;
558  if (!NewBB2Preds.empty()) {
559    // Create another basic block for the rest of OrigBB's predecessors.
560    NewBB2 = BasicBlock::Create(OrigBB->getContext(),
561                                OrigBB->getName() + Suffix2,
562                                OrigBB->getParent(), OrigBB);
563    NewBBs.push_back(NewBB2);
564
565    // The new block unconditionally branches to the old block.
566    BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
567
568    // Move the remaining edges from OrigBB to point to NewBB2.
569    for (SmallVectorImpl<BasicBlock*>::iterator
570           i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
571      (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
572
573    // Update DominatorTree, LoopInfo, and LCCSA analysis information.
574    HasLoopExit = false;
575    UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, P, HasLoopExit);
576
577    // Update the PHI nodes in OrigBB with the values coming from NewBB2.
578    UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, P, HasLoopExit);
579  }
580
581  LandingPadInst *LPad = OrigBB->getLandingPadInst();
582  Instruction *Clone1 = LPad->clone();
583  Clone1->setName(Twine("lpad") + Suffix1);
584  NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
585
586  if (NewBB2) {
587    Instruction *Clone2 = LPad->clone();
588    Clone2->setName(Twine("lpad") + Suffix2);
589    NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
590
591    // Create a PHI node for the two cloned landingpad instructions.
592    PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
593    PN->addIncoming(Clone1, NewBB1);
594    PN->addIncoming(Clone2, NewBB2);
595    LPad->replaceAllUsesWith(PN);
596    LPad->eraseFromParent();
597  } else {
598    // There is no second clone. Just replace the landing pad with the first
599    // clone.
600    LPad->replaceAllUsesWith(Clone1);
601    LPad->eraseFromParent();
602  }
603}
604
605/// FindFunctionBackedges - Analyze the specified function to find all of the
606/// loop backedges in the function and return them.  This is a relatively cheap
607/// (compared to computing dominators and loop info) analysis.
608///
609/// The output is added to Result, as pairs of <from,to> edge info.
610void llvm::FindFunctionBackedges(const Function &F,
611     SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
612  const BasicBlock *BB = &F.getEntryBlock();
613  if (succ_begin(BB) == succ_end(BB))
614    return;
615
616  SmallPtrSet<const BasicBlock*, 8> Visited;
617  SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
618  SmallPtrSet<const BasicBlock*, 8> InStack;
619
620  Visited.insert(BB);
621  VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
622  InStack.insert(BB);
623  do {
624    std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
625    const BasicBlock *ParentBB = Top.first;
626    succ_const_iterator &I = Top.second;
627
628    bool FoundNew = false;
629    while (I != succ_end(ParentBB)) {
630      BB = *I++;
631      if (Visited.insert(BB)) {
632        FoundNew = true;
633        break;
634      }
635      // Successor is in VisitStack, it's a back edge.
636      if (InStack.count(BB))
637        Result.push_back(std::make_pair(ParentBB, BB));
638    }
639
640    if (FoundNew) {
641      // Go down one level if there is a unvisited successor.
642      InStack.insert(BB);
643      VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
644    } else {
645      // Go up one level.
646      InStack.erase(VisitStack.pop_back_val().first);
647    }
648  } while (!VisitStack.empty());
649}
650
651/// FoldReturnIntoUncondBranch - This method duplicates the specified return
652/// instruction into a predecessor which ends in an unconditional branch. If
653/// the return instruction returns a value defined by a PHI, propagate the
654/// right value into the return. It returns the new return instruction in the
655/// predecessor.
656ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
657                                             BasicBlock *Pred) {
658  Instruction *UncondBranch = Pred->getTerminator();
659  // Clone the return and add it to the end of the predecessor.
660  Instruction *NewRet = RI->clone();
661  Pred->getInstList().push_back(NewRet);
662
663  // If the return instruction returns a value, and if the value was a
664  // PHI node in "BB", propagate the right value into the return.
665  for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
666       i != e; ++i)
667    if (PHINode *PN = dyn_cast<PHINode>(*i))
668      if (PN->getParent() == BB)
669        *i = PN->getIncomingValueForBlock(Pred);
670
671  // Update any PHI nodes in the returning block to realize that we no
672  // longer branch to them.
673  BB->removePredecessor(Pred);
674  UncondBranch->eraseFromParent();
675  return cast<ReturnInst>(NewRet);
676}
677
678/// GetFirstDebugLocInBasicBlock - Return first valid DebugLoc entry in a
679/// given basic block.
680DebugLoc llvm::GetFirstDebugLocInBasicBlock(const BasicBlock *BB) {
681  if (const Instruction *I = BB->getFirstNonPHI())
682    return I->getDebugLoc();
683  // Scanning entire block may be too expensive, if the first instruction
684  // does not have valid location info.
685  return DebugLoc();
686}
687