MachineBasicBlock.cpp revision 64f865ceca4cdd39fcac3d958071be118cb9c1d3
1//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
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// Collect the sequence of machine instructions for a basic block.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/MachineBasicBlock.h"
15#include "llvm/BasicBlock.h"
16#include "llvm/CodeGen/LiveVariables.h"
17#include "llvm/CodeGen/MachineDominators.h"
18#include "llvm/CodeGen/MachineFunction.h"
19#include "llvm/CodeGen/MachineLoopInfo.h"
20#include "llvm/CodeGen/SlotIndexes.h"
21#include "llvm/MC/MCAsmInfo.h"
22#include "llvm/MC/MCContext.h"
23#include "llvm/Target/TargetRegisterInfo.h"
24#include "llvm/Target/TargetData.h"
25#include "llvm/Target/TargetInstrDesc.h"
26#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Assembly/Writer.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/LeakDetector.h"
33#include "llvm/Support/raw_ostream.h"
34#include <algorithm>
35using namespace llvm;
36
37MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
38  : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
39    AddressTaken(false) {
40  Insts.Parent = this;
41}
42
43MachineBasicBlock::~MachineBasicBlock() {
44  LeakDetector::removeGarbageObject(this);
45}
46
47/// getSymbol - Return the MCSymbol for this basic block.
48///
49MCSymbol *MachineBasicBlock::getSymbol() const {
50  const MachineFunction *MF = getParent();
51  MCContext &Ctx = MF->getContext();
52  const char *Prefix = Ctx.getAsmInfo().getPrivateGlobalPrefix();
53  return Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
54                               Twine(MF->getFunctionNumber()) + "_" +
55                               Twine(getNumber()));
56}
57
58
59raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
60  MBB.print(OS);
61  return OS;
62}
63
64/// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
65/// parent pointer of the MBB, the MBB numbering, and any instructions in the
66/// MBB to be on the right operand list for registers.
67///
68/// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
69/// gets the next available unique MBB number. If it is removed from a
70/// MachineFunction, it goes back to being #-1.
71void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
72  MachineFunction &MF = *N->getParent();
73  N->Number = MF.addToMBBNumbering(N);
74
75  // Make sure the instructions have their operands in the reginfo lists.
76  MachineRegisterInfo &RegInfo = MF.getRegInfo();
77  for (MachineBasicBlock::iterator I = N->begin(), E = N->end(); I != E; ++I)
78    I->AddRegOperandsToUseLists(RegInfo);
79
80  LeakDetector::removeGarbageObject(N);
81}
82
83void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
84  N->getParent()->removeFromMBBNumbering(N->Number);
85  N->Number = -1;
86  LeakDetector::addGarbageObject(N);
87}
88
89
90/// addNodeToList (MI) - When we add an instruction to a basic block
91/// list, we update its parent pointer and add its operands from reg use/def
92/// lists if appropriate.
93void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
94  assert(N->getParent() == 0 && "machine instruction already in a basic block");
95  N->setParent(Parent);
96
97  // Add the instruction's register operands to their corresponding
98  // use/def lists.
99  MachineFunction *MF = Parent->getParent();
100  N->AddRegOperandsToUseLists(MF->getRegInfo());
101
102  LeakDetector::removeGarbageObject(N);
103}
104
105/// removeNodeFromList (MI) - When we remove an instruction from a basic block
106/// list, we update its parent pointer and remove its operands from reg use/def
107/// lists if appropriate.
108void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
109  assert(N->getParent() != 0 && "machine instruction not in a basic block");
110
111  // Remove from the use/def lists.
112  N->RemoveRegOperandsFromUseLists();
113
114  N->setParent(0);
115
116  LeakDetector::addGarbageObject(N);
117}
118
119/// transferNodesFromList (MI) - When moving a range of instructions from one
120/// MBB list to another, we need to update the parent pointers and the use/def
121/// lists.
122void ilist_traits<MachineInstr>::
123transferNodesFromList(ilist_traits<MachineInstr> &fromList,
124                      MachineBasicBlock::iterator first,
125                      MachineBasicBlock::iterator last) {
126  assert(Parent->getParent() == fromList.Parent->getParent() &&
127        "MachineInstr parent mismatch!");
128
129  // Splice within the same MBB -> no change.
130  if (Parent == fromList.Parent) return;
131
132  // If splicing between two blocks within the same function, just update the
133  // parent pointers.
134  for (; first != last; ++first)
135    first->setParent(Parent);
136}
137
138void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
139  assert(!MI->getParent() && "MI is still in a block!");
140  Parent->getParent()->DeleteMachineInstr(MI);
141}
142
143MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
144  iterator I = begin();
145  while (I != end() && I->isPHI())
146    ++I;
147  return I;
148}
149
150MachineBasicBlock::iterator
151MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
152  while (I != end() && (I->isPHI() || I->isLabel() || I->isDebugValue()))
153    ++I;
154  return I;
155}
156
157MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
158  iterator B = begin(), I = end();
159  iterator Term = I;
160  while (I != B) {
161    --I;
162    // Ignore any debug values after the first terminator.
163    if (I->isDebugValue())
164      continue;
165    // Stop once we see a non-debug non-terminator.
166    if (!I->getDesc().isTerminator())
167      break;
168    // Earliest terminator so far.
169    Term = I;
170  }
171  // Return the first terminator, or end().
172  // Everything after Term is terminators and debug values.
173  return Term;
174}
175
176void MachineBasicBlock::dump() const {
177  print(dbgs());
178}
179
180StringRef MachineBasicBlock::getName() const {
181  if (const BasicBlock *LBB = getBasicBlock())
182    return LBB->getName();
183  else
184    return "(null)";
185}
186
187void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
188  const MachineFunction *MF = getParent();
189  if (!MF) {
190    OS << "Can't print out MachineBasicBlock because parent MachineFunction"
191       << " is null\n";
192    return;
193  }
194
195  if (Alignment) { OS << "Alignment " << Alignment << "\n"; }
196
197  if (Indexes)
198    OS << Indexes->getMBBStartIdx(this) << '\t';
199
200  OS << "BB#" << getNumber() << ": ";
201
202  const char *Comma = "";
203  if (const BasicBlock *LBB = getBasicBlock()) {
204    OS << Comma << "derived from LLVM BB ";
205    WriteAsOperand(OS, LBB, /*PrintType=*/false);
206    Comma = ", ";
207  }
208  if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
209  if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
210  OS << '\n';
211
212  const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
213  if (!livein_empty()) {
214    if (Indexes) OS << '\t';
215    OS << "    Live Ins:";
216    for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
217      OS << ' ' << PrintReg(*I, TRI);
218    OS << '\n';
219  }
220  // Print the preds of this block according to the CFG.
221  if (!pred_empty()) {
222    if (Indexes) OS << '\t';
223    OS << "    Predecessors according to CFG:";
224    for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
225      OS << " BB#" << (*PI)->getNumber();
226    OS << '\n';
227  }
228
229  for (const_iterator I = begin(); I != end(); ++I) {
230    if (Indexes) {
231      if (Indexes->hasIndex(I))
232        OS << Indexes->getInstructionIndex(I);
233      OS << '\t';
234    }
235    OS << '\t';
236    I->print(OS, &getParent()->getTarget());
237  }
238
239  // Print the successors of this block according to the CFG.
240  if (!succ_empty()) {
241    if (Indexes) OS << '\t';
242    OS << "    Successors according to CFG:";
243    for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)
244      OS << " BB#" << (*SI)->getNumber();
245    OS << '\n';
246  }
247}
248
249void MachineBasicBlock::removeLiveIn(unsigned Reg) {
250  std::vector<unsigned>::iterator I =
251    std::find(LiveIns.begin(), LiveIns.end(), Reg);
252  assert(I != LiveIns.end() && "Not a live in!");
253  LiveIns.erase(I);
254}
255
256bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
257  livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
258  return I != livein_end();
259}
260
261void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
262  getParent()->splice(NewAfter, this);
263}
264
265void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
266  MachineFunction::iterator BBI = NewBefore;
267  getParent()->splice(++BBI, this);
268}
269
270void MachineBasicBlock::updateTerminator() {
271  const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
272  // A block with no successors has no concerns with fall-through edges.
273  if (this->succ_empty()) return;
274
275  MachineBasicBlock *TBB = 0, *FBB = 0;
276  SmallVector<MachineOperand, 4> Cond;
277  DebugLoc dl;  // FIXME: this is nowhere
278  bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
279  (void) B;
280  assert(!B && "UpdateTerminators requires analyzable predecessors!");
281  if (Cond.empty()) {
282    if (TBB) {
283      // The block has an unconditional branch. If its successor is now
284      // its layout successor, delete the branch.
285      if (isLayoutSuccessor(TBB))
286        TII->RemoveBranch(*this);
287    } else {
288      // The block has an unconditional fallthrough. If its successor is not
289      // its layout successor, insert a branch.
290      TBB = *succ_begin();
291      if (!isLayoutSuccessor(TBB))
292        TII->InsertBranch(*this, TBB, 0, Cond, dl);
293    }
294  } else {
295    if (FBB) {
296      // The block has a non-fallthrough conditional branch. If one of its
297      // successors is its layout successor, rewrite it to a fallthrough
298      // conditional branch.
299      if (isLayoutSuccessor(TBB)) {
300        if (TII->ReverseBranchCondition(Cond))
301          return;
302        TII->RemoveBranch(*this);
303        TII->InsertBranch(*this, FBB, 0, Cond, dl);
304      } else if (isLayoutSuccessor(FBB)) {
305        TII->RemoveBranch(*this);
306        TII->InsertBranch(*this, TBB, 0, Cond, dl);
307      }
308    } else {
309      // The block has a fallthrough conditional branch.
310      MachineBasicBlock *MBBA = *succ_begin();
311      MachineBasicBlock *MBBB = *llvm::next(succ_begin());
312      if (MBBA == TBB) std::swap(MBBB, MBBA);
313      if (isLayoutSuccessor(TBB)) {
314        if (TII->ReverseBranchCondition(Cond)) {
315          // We can't reverse the condition, add an unconditional branch.
316          Cond.clear();
317          TII->InsertBranch(*this, MBBA, 0, Cond, dl);
318          return;
319        }
320        TII->RemoveBranch(*this);
321        TII->InsertBranch(*this, MBBA, 0, Cond, dl);
322      } else if (!isLayoutSuccessor(MBBA)) {
323        TII->RemoveBranch(*this);
324        TII->InsertBranch(*this, TBB, MBBA, Cond, dl);
325      }
326    }
327  }
328}
329
330void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) {
331  Successors.push_back(succ);
332  succ->addPredecessor(this);
333}
334
335void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
336  succ->removePredecessor(this);
337  succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
338  assert(I != Successors.end() && "Not a current successor!");
339  Successors.erase(I);
340}
341
342MachineBasicBlock::succ_iterator
343MachineBasicBlock::removeSuccessor(succ_iterator I) {
344  assert(I != Successors.end() && "Not a current successor!");
345  (*I)->removePredecessor(this);
346  return Successors.erase(I);
347}
348
349void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
350  Predecessors.push_back(pred);
351}
352
353void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
354  std::vector<MachineBasicBlock *>::iterator I =
355    std::find(Predecessors.begin(), Predecessors.end(), pred);
356  assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
357  Predecessors.erase(I);
358}
359
360void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
361  if (this == fromMBB)
362    return;
363
364  while (!fromMBB->succ_empty()) {
365    MachineBasicBlock *Succ = *fromMBB->succ_begin();
366    addSuccessor(Succ);
367    fromMBB->removeSuccessor(Succ);
368  }
369}
370
371void
372MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
373  if (this == fromMBB)
374    return;
375
376  while (!fromMBB->succ_empty()) {
377    MachineBasicBlock *Succ = *fromMBB->succ_begin();
378    addSuccessor(Succ);
379    fromMBB->removeSuccessor(Succ);
380
381    // Fix up any PHI nodes in the successor.
382    for (MachineBasicBlock::iterator MI = Succ->begin(), ME = Succ->end();
383         MI != ME && MI->isPHI(); ++MI)
384      for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
385        MachineOperand &MO = MI->getOperand(i);
386        if (MO.getMBB() == fromMBB)
387          MO.setMBB(this);
388      }
389  }
390}
391
392bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
393  std::vector<MachineBasicBlock *>::const_iterator I =
394    std::find(Successors.begin(), Successors.end(), MBB);
395  return I != Successors.end();
396}
397
398bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
399  MachineFunction::const_iterator I(this);
400  return llvm::next(I) == MachineFunction::const_iterator(MBB);
401}
402
403bool MachineBasicBlock::canFallThrough() {
404  MachineFunction::iterator Fallthrough = this;
405  ++Fallthrough;
406  // If FallthroughBlock is off the end of the function, it can't fall through.
407  if (Fallthrough == getParent()->end())
408    return false;
409
410  // If FallthroughBlock isn't a successor, no fallthrough is possible.
411  if (!isSuccessor(Fallthrough))
412    return false;
413
414  // Analyze the branches, if any, at the end of the block.
415  MachineBasicBlock *TBB = 0, *FBB = 0;
416  SmallVector<MachineOperand, 4> Cond;
417  const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
418  if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
419    // If we couldn't analyze the branch, examine the last instruction.
420    // If the block doesn't end in a known control barrier, assume fallthrough
421    // is possible. The isPredicable check is needed because this code can be
422    // called during IfConversion, where an instruction which is normally a
423    // Barrier is predicated and thus no longer an actual control barrier. This
424    // is over-conservative though, because if an instruction isn't actually
425    // predicated we could still treat it like a barrier.
426    return empty() || !back().getDesc().isBarrier() ||
427           back().getDesc().isPredicable();
428  }
429
430  // If there is no branch, control always falls through.
431  if (TBB == 0) return true;
432
433  // If there is some explicit branch to the fallthrough block, it can obviously
434  // reach, even though the branch should get folded to fall through implicitly.
435  if (MachineFunction::iterator(TBB) == Fallthrough ||
436      MachineFunction::iterator(FBB) == Fallthrough)
437    return true;
438
439  // If it's an unconditional branch to some block not the fall through, it
440  // doesn't fall through.
441  if (Cond.empty()) return false;
442
443  // Otherwise, if it is conditional and has no explicit false block, it falls
444  // through.
445  return FBB == 0;
446}
447
448MachineBasicBlock *
449MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
450  MachineFunction *MF = getParent();
451  DebugLoc dl;  // FIXME: this is nowhere
452
453  // We may need to update this's terminator, but we can't do that if
454  // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
455  const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
456  MachineBasicBlock *TBB = 0, *FBB = 0;
457  SmallVector<MachineOperand, 4> Cond;
458  if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
459    return NULL;
460
461  // Avoid bugpoint weirdness: A block may end with a conditional branch but
462  // jumps to the same MBB is either case. We have duplicate CFG edges in that
463  // case that we can't handle. Since this never happens in properly optimized
464  // code, just skip those edges.
465  if (TBB && TBB == FBB) {
466    DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
467                 << getNumber() << '\n');
468    return NULL;
469  }
470
471  MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
472  MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
473  DEBUG(dbgs() << "Splitting critical edge:"
474        " BB#" << getNumber()
475        << " -- BB#" << NMBB->getNumber()
476        << " -- BB#" << Succ->getNumber() << '\n');
477
478  ReplaceUsesOfBlockWith(Succ, NMBB);
479  updateTerminator();
480
481  // Insert unconditional "jump Succ" instruction in NMBB if necessary.
482  NMBB->addSuccessor(Succ);
483  if (!NMBB->isLayoutSuccessor(Succ)) {
484    Cond.clear();
485    MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
486  }
487
488  // Fix PHI nodes in Succ so they refer to NMBB instead of this
489  for (MachineBasicBlock::iterator i = Succ->begin(), e = Succ->end();
490       i != e && i->isPHI(); ++i)
491    for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
492      if (i->getOperand(ni+1).getMBB() == this)
493        i->getOperand(ni+1).setMBB(NMBB);
494
495  if (LiveVariables *LV =
496        P->getAnalysisIfAvailable<LiveVariables>())
497    LV->addNewBlock(NMBB, this, Succ);
498
499  if (MachineDominatorTree *MDT =
500      P->getAnalysisIfAvailable<MachineDominatorTree>()) {
501    // Update dominator information.
502    MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
503
504    bool IsNewIDom = true;
505    for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
506         PI != E; ++PI) {
507      MachineBasicBlock *PredBB = *PI;
508      if (PredBB == NMBB)
509        continue;
510      if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
511        IsNewIDom = false;
512        break;
513      }
514    }
515
516    // We know "this" dominates the newly created basic block.
517    MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
518
519    // If all the other predecessors of "Succ" are dominated by "Succ" itself
520    // then the new block is the new immediate dominator of "Succ". Otherwise,
521    // the new block doesn't dominate anything.
522    if (IsNewIDom)
523      MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
524  }
525
526  if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
527    if (MachineLoop *TIL = MLI->getLoopFor(this)) {
528      // If one or the other blocks were not in a loop, the new block is not
529      // either, and thus LI doesn't need to be updated.
530      if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
531        if (TIL == DestLoop) {
532          // Both in the same loop, the NMBB joins loop.
533          DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
534        } else if (TIL->contains(DestLoop)) {
535          // Edge from an outer loop to an inner loop.  Add to the outer loop.
536          TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
537        } else if (DestLoop->contains(TIL)) {
538          // Edge from an inner loop to an outer loop.  Add to the outer loop.
539          DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
540        } else {
541          // Edge from two loops with no containment relation.  Because these
542          // are natural loops, we know that the destination block must be the
543          // header of its loop (adding a branch into a loop elsewhere would
544          // create an irreducible loop).
545          assert(DestLoop->getHeader() == Succ &&
546                 "Should not create irreducible loops!");
547          if (MachineLoop *P = DestLoop->getParentLoop())
548            P->addBasicBlockToLoop(NMBB, MLI->getBase());
549        }
550      }
551    }
552
553  return NMBB;
554}
555
556/// removeFromParent - This method unlinks 'this' from the containing function,
557/// and returns it, but does not delete it.
558MachineBasicBlock *MachineBasicBlock::removeFromParent() {
559  assert(getParent() && "Not embedded in a function!");
560  getParent()->remove(this);
561  return this;
562}
563
564
565/// eraseFromParent - This method unlinks 'this' from the containing function,
566/// and deletes it.
567void MachineBasicBlock::eraseFromParent() {
568  assert(getParent() && "Not embedded in a function!");
569  getParent()->erase(this);
570}
571
572
573/// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
574/// 'Old', change the code and CFG so that it branches to 'New' instead.
575void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
576                                               MachineBasicBlock *New) {
577  assert(Old != New && "Cannot replace self with self!");
578
579  MachineBasicBlock::iterator I = end();
580  while (I != begin()) {
581    --I;
582    if (!I->getDesc().isTerminator()) break;
583
584    // Scan the operands of this machine instruction, replacing any uses of Old
585    // with New.
586    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
587      if (I->getOperand(i).isMBB() &&
588          I->getOperand(i).getMBB() == Old)
589        I->getOperand(i).setMBB(New);
590  }
591
592  // Update the successor information.
593  removeSuccessor(Old);
594  addSuccessor(New);
595}
596
597/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
598/// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
599/// DestB, remove any other MBB successors from the CFG.  DestA and DestB can be
600/// null.
601///
602/// Besides DestA and DestB, retain other edges leading to LandingPads
603/// (currently there can be only one; we don't check or require that here).
604/// Note it is possible that DestA and/or DestB are LandingPads.
605bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
606                                             MachineBasicBlock *DestB,
607                                             bool isCond) {
608  // The values of DestA and DestB frequently come from a call to the
609  // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
610  // values from there.
611  //
612  // 1. If both DestA and DestB are null, then the block ends with no branches
613  //    (it falls through to its successor).
614  // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
615  //    with only an unconditional branch.
616  // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
617  //    with a conditional branch that falls through to a successor (DestB).
618  // 4. If DestA and DestB is set and isCond is true, then the block ends with a
619  //    conditional branch followed by an unconditional branch. DestA is the
620  //    'true' destination and DestB is the 'false' destination.
621
622  bool Changed = false;
623
624  MachineFunction::iterator FallThru =
625    llvm::next(MachineFunction::iterator(this));
626
627  if (DestA == 0 && DestB == 0) {
628    // Block falls through to successor.
629    DestA = FallThru;
630    DestB = FallThru;
631  } else if (DestA != 0 && DestB == 0) {
632    if (isCond)
633      // Block ends in conditional jump that falls through to successor.
634      DestB = FallThru;
635  } else {
636    assert(DestA && DestB && isCond &&
637           "CFG in a bad state. Cannot correct CFG edges");
638  }
639
640  // Remove superfluous edges. I.e., those which aren't destinations of this
641  // basic block, duplicate edges, or landing pads.
642  SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
643  MachineBasicBlock::succ_iterator SI = succ_begin();
644  while (SI != succ_end()) {
645    const MachineBasicBlock *MBB = *SI;
646    if (!SeenMBBs.insert(MBB) ||
647        (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
648      // This is a superfluous edge, remove it.
649      SI = removeSuccessor(SI);
650      Changed = true;
651    } else {
652      ++SI;
653    }
654  }
655
656  return Changed;
657}
658
659/// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
660/// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
661DebugLoc
662MachineBasicBlock::findDebugLoc(MachineBasicBlock::iterator &MBBI) {
663  DebugLoc DL;
664  MachineBasicBlock::iterator E = end();
665  if (MBBI != E) {
666    // Skip debug declarations, we don't want a DebugLoc from them.
667    MachineBasicBlock::iterator MBBI2 = MBBI;
668    while (MBBI2 != E && MBBI2->isDebugValue())
669      MBBI2++;
670    if (MBBI2 != E)
671      DL = MBBI2->getDebugLoc();
672  }
673  return DL;
674}
675
676void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
677                          bool t) {
678  OS << "BB#" << MBB->getNumber();
679}
680
681