7e9fb20ffe8d9a70494737bf796d227e4b7534c6
[oota-llvm.git] / lib / CodeGen / MachineBasicBlock.cpp
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/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/SlotIndexes.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/LeakDetector.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include <algorithm>
34 using namespace llvm;
35
36 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
37   : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
38     AddressTaken(false) {
39   Insts.Parent = this;
40 }
41
42 MachineBasicBlock::~MachineBasicBlock() {
43   LeakDetector::removeGarbageObject(this);
44 }
45
46 /// getSymbol - Return the MCSymbol for this basic block.
47 ///
48 MCSymbol *MachineBasicBlock::getSymbol() const {
49   const MachineFunction *MF = getParent();
50   MCContext &Ctx = MF->getContext();
51   const char *Prefix = Ctx.getAsmInfo().getPrivateGlobalPrefix();
52   return Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
53                                Twine(MF->getFunctionNumber()) + "_" +
54                                Twine(getNumber()));
55 }
56
57
58 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
59   MBB.print(OS);
60   return OS;
61 }
62
63 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
64 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
65 /// MBB to be on the right operand list for registers.
66 ///
67 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
68 /// gets the next available unique MBB number. If it is removed from a
69 /// MachineFunction, it goes back to being #-1.
70 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
71   MachineFunction &MF = *N->getParent();
72   N->Number = MF.addToMBBNumbering(N);
73
74   // Make sure the instructions have their operands in the reginfo lists.
75   MachineRegisterInfo &RegInfo = MF.getRegInfo();
76   for (MachineBasicBlock::instr_iterator
77          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
78     I->AddRegOperandsToUseLists(RegInfo);
79
80   LeakDetector::removeGarbageObject(N);
81 }
82
83 void 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.
93 void 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.
108 void 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   if (MachineFunction *MF = N->getParent()->getParent())
113     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
114
115   N->setParent(0);
116
117   LeakDetector::addGarbageObject(N);
118 }
119
120 /// transferNodesFromList (MI) - When moving a range of instructions from one
121 /// MBB list to another, we need to update the parent pointers and the use/def
122 /// lists.
123 void ilist_traits<MachineInstr>::
124 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
125                       ilist_iterator<MachineInstr> first,
126                       ilist_iterator<MachineInstr> last) {
127   assert(Parent->getParent() == fromList.Parent->getParent() &&
128         "MachineInstr parent mismatch!");
129
130   // Splice within the same MBB -> no change.
131   if (Parent == fromList.Parent) return;
132
133   // If splicing between two blocks within the same function, just update the
134   // parent pointers.
135   for (; first != last; ++first)
136     first->setParent(Parent);
137 }
138
139 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
140   assert(!MI->getParent() && "MI is still in a block!");
141   Parent->getParent()->DeleteMachineInstr(MI);
142 }
143
144 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
145   instr_iterator I = instr_begin(), E = instr_end();
146   while (I != E && I->isPHI())
147     ++I;
148   assert((I == E || !I->isInsideBundle()) &&
149          "First non-phi MI cannot be inside a bundle!");
150   return I;
151 }
152
153 MachineBasicBlock::iterator
154 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
155   iterator E = end();
156   while (I != E && (I->isPHI() || I->isLabel() || I->isDebugValue()))
157     ++I;
158   // FIXME: This needs to change if we wish to bundle labels / dbg_values
159   // inside the bundle.
160   assert((I == E || !I->isInsideBundle()) &&
161          "First non-phi / non-label instruction is inside a bundle!");
162   return I;
163 }
164
165 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
166   iterator B = begin(), E = end(), I = E;
167   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
168     ; /*noop */
169   while (I != E && !I->isTerminator())
170     ++I;
171   return I;
172 }
173
174 MachineBasicBlock::const_iterator
175 MachineBasicBlock::getFirstTerminator() const {
176   const_iterator B = begin(), E = end(), I = E;
177   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
178     ; /*noop */
179   while (I != E && !I->isTerminator())
180     ++I;
181   return I;
182 }
183
184 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
185   instr_iterator B = instr_begin(), E = instr_end(), I = E;
186   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
187     ; /*noop */
188   while (I != E && !I->isTerminator())
189     ++I;
190   return I;
191 }
192
193 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
194   // Skip over end-of-block dbg_value instructions.
195   instr_iterator B = instr_begin(), I = instr_end();
196   while (I != B) {
197     --I;
198     // Return instruction that starts a bundle.
199     if (I->isDebugValue() || I->isInsideBundle())
200       continue;
201     return I;
202   }
203   // The block is all debug values.
204   return end();
205 }
206
207 MachineBasicBlock::const_iterator
208 MachineBasicBlock::getLastNonDebugInstr() const {
209   // Skip over end-of-block dbg_value instructions.
210   const_instr_iterator B = instr_begin(), I = instr_end();
211   while (I != B) {
212     --I;
213     // Return instruction that starts a bundle.
214     if (I->isDebugValue() || I->isInsideBundle())
215       continue;
216     return I;
217   }
218   // The block is all debug values.
219   return end();
220 }
221
222 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
223   // A block with a landing pad successor only has one other successor.
224   if (succ_size() > 2)
225     return 0;
226   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
227     if ((*I)->isLandingPad())
228       return *I;
229   return 0;
230 }
231
232 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
233 void MachineBasicBlock::dump() const {
234   print(dbgs());
235 }
236 #endif
237
238 StringRef MachineBasicBlock::getName() const {
239   if (const BasicBlock *LBB = getBasicBlock())
240     return LBB->getName();
241   else
242     return "(null)";
243 }
244
245 /// Return a hopefully unique identifier for this block.
246 std::string MachineBasicBlock::getFullName() const {
247   std::string Name;
248   if (getParent())
249     Name = (getParent()->getName() + ":").str();
250   if (getBasicBlock())
251     Name += getBasicBlock()->getName();
252   else
253     Name += (Twine("BB") + Twine(getNumber())).str();
254   return Name;
255 }
256
257 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
258   const MachineFunction *MF = getParent();
259   if (!MF) {
260     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
261        << " is null\n";
262     return;
263   }
264
265   if (Indexes)
266     OS << Indexes->getMBBStartIdx(this) << '\t';
267
268   OS << "BB#" << getNumber() << ": ";
269
270   const char *Comma = "";
271   if (const BasicBlock *LBB = getBasicBlock()) {
272     OS << Comma << "derived from LLVM BB ";
273     WriteAsOperand(OS, LBB, /*PrintType=*/false);
274     Comma = ", ";
275   }
276   if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
277   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
278   if (Alignment)
279     OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
280        << " bytes)";
281
282   OS << '\n';
283
284   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
285   if (!livein_empty()) {
286     if (Indexes) OS << '\t';
287     OS << "    Live Ins:";
288     for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
289       OS << ' ' << PrintReg(*I, TRI);
290     OS << '\n';
291   }
292   // Print the preds of this block according to the CFG.
293   if (!pred_empty()) {
294     if (Indexes) OS << '\t';
295     OS << "    Predecessors according to CFG:";
296     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
297       OS << " BB#" << (*PI)->getNumber();
298     OS << '\n';
299   }
300
301   for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
302     if (Indexes) {
303       if (Indexes->hasIndex(I))
304         OS << Indexes->getInstructionIndex(I);
305       OS << '\t';
306     }
307     OS << '\t';
308     if (I->isInsideBundle())
309       OS << "  * ";
310     I->print(OS, &getParent()->getTarget());
311   }
312
313   // Print the successors of this block according to the CFG.
314   if (!succ_empty()) {
315     if (Indexes) OS << '\t';
316     OS << "    Successors according to CFG:";
317     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
318       OS << " BB#" << (*SI)->getNumber();
319       if (!Weights.empty())
320         OS << '(' << *getWeightIterator(SI) << ')';
321     }
322     OS << '\n';
323   }
324 }
325
326 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
327   std::vector<unsigned>::iterator I =
328     std::find(LiveIns.begin(), LiveIns.end(), Reg);
329   if (I != LiveIns.end())
330     LiveIns.erase(I);
331 }
332
333 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
334   livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
335   return I != livein_end();
336 }
337
338 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
339   getParent()->splice(NewAfter, this);
340 }
341
342 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
343   MachineFunction::iterator BBI = NewBefore;
344   getParent()->splice(++BBI, this);
345 }
346
347 void MachineBasicBlock::updateTerminator() {
348   const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
349   // A block with no successors has no concerns with fall-through edges.
350   if (this->succ_empty()) return;
351
352   MachineBasicBlock *TBB = 0, *FBB = 0;
353   SmallVector<MachineOperand, 4> Cond;
354   DebugLoc dl;  // FIXME: this is nowhere
355   bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
356   (void) B;
357   assert(!B && "UpdateTerminators requires analyzable predecessors!");
358   if (Cond.empty()) {
359     if (TBB) {
360       // The block has an unconditional branch. If its successor is now
361       // its layout successor, delete the branch.
362       if (isLayoutSuccessor(TBB))
363         TII->RemoveBranch(*this);
364     } else {
365       // The block has an unconditional fallthrough. If its successor is not
366       // its layout successor, insert a branch. First we have to locate the
367       // only non-landing-pad successor, as that is the fallthrough block.
368       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
369         if ((*SI)->isLandingPad())
370           continue;
371         assert(!TBB && "Found more than one non-landing-pad successor!");
372         TBB = *SI;
373       }
374
375       // If there is no non-landing-pad successor, the block has no
376       // fall-through edges to be concerned with.
377       if (!TBB)
378         return;
379
380       // Finally update the unconditional successor to be reached via a branch
381       // if it would not be reached by fallthrough.
382       if (!isLayoutSuccessor(TBB))
383         TII->InsertBranch(*this, TBB, 0, Cond, dl);
384     }
385   } else {
386     if (FBB) {
387       // The block has a non-fallthrough conditional branch. If one of its
388       // successors is its layout successor, rewrite it to a fallthrough
389       // conditional branch.
390       if (isLayoutSuccessor(TBB)) {
391         if (TII->ReverseBranchCondition(Cond))
392           return;
393         TII->RemoveBranch(*this);
394         TII->InsertBranch(*this, FBB, 0, Cond, dl);
395       } else if (isLayoutSuccessor(FBB)) {
396         TII->RemoveBranch(*this);
397         TII->InsertBranch(*this, TBB, 0, Cond, dl);
398       }
399     } else {
400       // Walk through the successors and find the successor which is not
401       // a landing pad and is not the conditional branch destination (in TBB)
402       // as the fallthrough successor.
403       MachineBasicBlock *FallthroughBB = 0;
404       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
405         if ((*SI)->isLandingPad() || *SI == TBB)
406           continue;
407         assert(!FallthroughBB && "Found more than one fallthrough successor.");
408         FallthroughBB = *SI;
409       }
410       if (!FallthroughBB && canFallThrough()) {
411         // We fallthrough to the same basic block as the conditional jump
412         // targets. Remove the conditional jump, leaving unconditional
413         // fallthrough.
414         // FIXME: This does not seem like a reasonable pattern to support, but it
415         // has been seen in the wild coming out of degenerate ARM test cases.
416         TII->RemoveBranch(*this);
417
418         // Finally update the unconditional successor to be reached via a branch
419         // if it would not be reached by fallthrough.
420         if (!isLayoutSuccessor(TBB))
421           TII->InsertBranch(*this, TBB, 0, Cond, dl);
422         return;
423       }
424
425       // The block has a fallthrough conditional branch.
426       if (isLayoutSuccessor(TBB)) {
427         if (TII->ReverseBranchCondition(Cond)) {
428           // We can't reverse the condition, add an unconditional branch.
429           Cond.clear();
430           TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
431           return;
432         }
433         TII->RemoveBranch(*this);
434         TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
435       } else if (!isLayoutSuccessor(FallthroughBB)) {
436         TII->RemoveBranch(*this);
437         TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
438       }
439     }
440   }
441 }
442
443 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
444
445   // If we see non-zero value for the first time it means we actually use Weight
446   // list, so we fill all Weights with 0's.
447   if (weight != 0 && Weights.empty())
448     Weights.resize(Successors.size());
449
450   if (weight != 0 || !Weights.empty())
451     Weights.push_back(weight);
452
453    Successors.push_back(succ);
454    succ->addPredecessor(this);
455  }
456
457 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
458   succ->removePredecessor(this);
459   succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
460   assert(I != Successors.end() && "Not a current successor!");
461
462   // If Weight list is empty it means we don't use it (disabled optimization).
463   if (!Weights.empty()) {
464     weight_iterator WI = getWeightIterator(I);
465     Weights.erase(WI);
466   }
467
468   Successors.erase(I);
469 }
470
471 MachineBasicBlock::succ_iterator
472 MachineBasicBlock::removeSuccessor(succ_iterator I) {
473   assert(I != Successors.end() && "Not a current successor!");
474
475   // If Weight list is empty it means we don't use it (disabled optimization).
476   if (!Weights.empty()) {
477     weight_iterator WI = getWeightIterator(I);
478     Weights.erase(WI);
479   }
480
481   (*I)->removePredecessor(this);
482   return Successors.erase(I);
483 }
484
485 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
486                                          MachineBasicBlock *New) {
487   if (Old == New)
488     return;
489
490   succ_iterator E = succ_end();
491   succ_iterator NewI = E;
492   succ_iterator OldI = E;
493   for (succ_iterator I = succ_begin(); I != E; ++I) {
494     if (*I == Old) {
495       OldI = I;
496       if (NewI != E)
497         break;
498     }
499     if (*I == New) {
500       NewI = I;
501       if (OldI != E)
502         break;
503     }
504   }
505   assert(OldI != E && "Old is not a successor of this block");
506   Old->removePredecessor(this);
507
508   // If New isn't already a successor, let it take Old's place.
509   if (NewI == E) {
510     New->addPredecessor(this);
511     *OldI = New;
512     return;
513   }
514
515   // New is already a successor.
516   // Update its weight instead of adding a duplicate edge.
517   if (!Weights.empty()) {
518     weight_iterator OldWI = getWeightIterator(OldI);
519     *getWeightIterator(NewI) += *OldWI;
520     Weights.erase(OldWI);
521   }
522   Successors.erase(OldI);
523 }
524
525 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
526   Predecessors.push_back(pred);
527 }
528
529 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
530   pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
531   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
532   Predecessors.erase(I);
533 }
534
535 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
536   if (this == fromMBB)
537     return;
538
539   while (!fromMBB->succ_empty()) {
540     MachineBasicBlock *Succ = *fromMBB->succ_begin();
541     uint32_t Weight = 0;
542
543     // If Weight list is empty it means we don't use it (disabled optimization).
544     if (!fromMBB->Weights.empty())
545       Weight = *fromMBB->Weights.begin();
546
547     addSuccessor(Succ, Weight);
548     fromMBB->removeSuccessor(Succ);
549   }
550 }
551
552 void
553 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
554   if (this == fromMBB)
555     return;
556
557   while (!fromMBB->succ_empty()) {
558     MachineBasicBlock *Succ = *fromMBB->succ_begin();
559     uint32_t Weight = 0;
560     if (!fromMBB->Weights.empty())
561       Weight = *fromMBB->Weights.begin();
562     addSuccessor(Succ, Weight);
563     fromMBB->removeSuccessor(Succ);
564
565     // Fix up any PHI nodes in the successor.
566     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
567            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
568       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
569         MachineOperand &MO = MI->getOperand(i);
570         if (MO.getMBB() == fromMBB)
571           MO.setMBB(this);
572       }
573   }
574 }
575
576 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
577   return std::find(pred_begin(), pred_end(), MBB) != pred_end();
578 }
579
580 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
581   return std::find(succ_begin(), succ_end(), MBB) != succ_end();
582 }
583
584 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
585   MachineFunction::const_iterator I(this);
586   return llvm::next(I) == MachineFunction::const_iterator(MBB);
587 }
588
589 bool MachineBasicBlock::canFallThrough() {
590   MachineFunction::iterator Fallthrough = this;
591   ++Fallthrough;
592   // If FallthroughBlock is off the end of the function, it can't fall through.
593   if (Fallthrough == getParent()->end())
594     return false;
595
596   // If FallthroughBlock isn't a successor, no fallthrough is possible.
597   if (!isSuccessor(Fallthrough))
598     return false;
599
600   // Analyze the branches, if any, at the end of the block.
601   MachineBasicBlock *TBB = 0, *FBB = 0;
602   SmallVector<MachineOperand, 4> Cond;
603   const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
604   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
605     // If we couldn't analyze the branch, examine the last instruction.
606     // If the block doesn't end in a known control barrier, assume fallthrough
607     // is possible. The isPredicated check is needed because this code can be
608     // called during IfConversion, where an instruction which is normally a
609     // Barrier is predicated and thus no longer an actual control barrier.
610     return empty() || !back().isBarrier() || TII->isPredicated(&back());
611   }
612
613   // If there is no branch, control always falls through.
614   if (TBB == 0) return true;
615
616   // If there is some explicit branch to the fallthrough block, it can obviously
617   // reach, even though the branch should get folded to fall through implicitly.
618   if (MachineFunction::iterator(TBB) == Fallthrough ||
619       MachineFunction::iterator(FBB) == Fallthrough)
620     return true;
621
622   // If it's an unconditional branch to some block not the fall through, it
623   // doesn't fall through.
624   if (Cond.empty()) return false;
625
626   // Otherwise, if it is conditional and has no explicit false block, it falls
627   // through.
628   return FBB == 0;
629 }
630
631 MachineBasicBlock *
632 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
633   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
634   // it in this generic function.
635   if (Succ->isLandingPad())
636     return NULL;
637
638   MachineFunction *MF = getParent();
639   DebugLoc dl;  // FIXME: this is nowhere
640
641   // We may need to update this's terminator, but we can't do that if
642   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
643   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
644   MachineBasicBlock *TBB = 0, *FBB = 0;
645   SmallVector<MachineOperand, 4> Cond;
646   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
647     return NULL;
648
649   // Avoid bugpoint weirdness: A block may end with a conditional branch but
650   // jumps to the same MBB is either case. We have duplicate CFG edges in that
651   // case that we can't handle. Since this never happens in properly optimized
652   // code, just skip those edges.
653   if (TBB && TBB == FBB) {
654     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
655                  << getNumber() << '\n');
656     return NULL;
657   }
658
659   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
660   MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
661   DEBUG(dbgs() << "Splitting critical edge:"
662         " BB#" << getNumber()
663         << " -- BB#" << NMBB->getNumber()
664         << " -- BB#" << Succ->getNumber() << '\n');
665
666   // On some targets like Mips, branches may kill virtual registers. Make sure
667   // that LiveVariables is properly updated after updateTerminator replaces the
668   // terminators.
669   LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
670
671   // Collect a list of virtual registers killed by the terminators.
672   SmallVector<unsigned, 4> KilledRegs;
673   if (LV)
674     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
675          I != E; ++I) {
676       MachineInstr *MI = I;
677       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
678            OE = MI->operands_end(); OI != OE; ++OI) {
679         if (!OI->isReg() || OI->getReg() == 0 ||
680             !OI->isUse() || !OI->isKill() || OI->isUndef())
681           continue;
682         unsigned Reg = OI->getReg();
683         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
684             LV->getVarInfo(Reg).removeKill(MI)) {
685           KilledRegs.push_back(Reg);
686           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
687           OI->setIsKill(false);
688         }
689       }
690     }
691
692   ReplaceUsesOfBlockWith(Succ, NMBB);
693   updateTerminator();
694
695   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
696   NMBB->addSuccessor(Succ);
697   if (!NMBB->isLayoutSuccessor(Succ)) {
698     Cond.clear();
699     MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
700   }
701
702   // Fix PHI nodes in Succ so they refer to NMBB instead of this
703   for (MachineBasicBlock::instr_iterator
704          i = Succ->instr_begin(),e = Succ->instr_end();
705        i != e && i->isPHI(); ++i)
706     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
707       if (i->getOperand(ni+1).getMBB() == this)
708         i->getOperand(ni+1).setMBB(NMBB);
709
710   // Inherit live-ins from the successor
711   for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
712          E = Succ->livein_end(); I != E; ++I)
713     NMBB->addLiveIn(*I);
714
715   // Update LiveVariables.
716   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
717   if (LV) {
718     // Restore kills of virtual registers that were killed by the terminators.
719     while (!KilledRegs.empty()) {
720       unsigned Reg = KilledRegs.pop_back_val();
721       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
722         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
723           continue;
724         if (TargetRegisterInfo::isVirtualRegister(Reg))
725           LV->getVarInfo(Reg).Kills.push_back(I);
726         DEBUG(dbgs() << "Restored terminator kill: " << *I);
727         break;
728       }
729     }
730     // Update relevant live-through information.
731     LV->addNewBlock(NMBB, this, Succ);
732   }
733
734   if (MachineDominatorTree *MDT =
735       P->getAnalysisIfAvailable<MachineDominatorTree>()) {
736     // Update dominator information.
737     MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
738
739     bool IsNewIDom = true;
740     for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
741          PI != E; ++PI) {
742       MachineBasicBlock *PredBB = *PI;
743       if (PredBB == NMBB)
744         continue;
745       if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
746         IsNewIDom = false;
747         break;
748       }
749     }
750
751     // We know "this" dominates the newly created basic block.
752     MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
753
754     // If all the other predecessors of "Succ" are dominated by "Succ" itself
755     // then the new block is the new immediate dominator of "Succ". Otherwise,
756     // the new block doesn't dominate anything.
757     if (IsNewIDom)
758       MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
759   }
760
761   if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
762     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
763       // If one or the other blocks were not in a loop, the new block is not
764       // either, and thus LI doesn't need to be updated.
765       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
766         if (TIL == DestLoop) {
767           // Both in the same loop, the NMBB joins loop.
768           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
769         } else if (TIL->contains(DestLoop)) {
770           // Edge from an outer loop to an inner loop.  Add to the outer loop.
771           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
772         } else if (DestLoop->contains(TIL)) {
773           // Edge from an inner loop to an outer loop.  Add to the outer loop.
774           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
775         } else {
776           // Edge from two loops with no containment relation.  Because these
777           // are natural loops, we know that the destination block must be the
778           // header of its loop (adding a branch into a loop elsewhere would
779           // create an irreducible loop).
780           assert(DestLoop->getHeader() == Succ &&
781                  "Should not create irreducible loops!");
782           if (MachineLoop *P = DestLoop->getParentLoop())
783             P->addBasicBlockToLoop(NMBB, MLI->getBase());
784         }
785       }
786     }
787
788   return NMBB;
789 }
790
791 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
792 /// neighboring instructions so the bundle won't be broken by removing MI.
793 static void unbundleSingleMI(MachineInstr *MI) {
794   // Removing the first instruction in a bundle.
795   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
796     MI->unbundleFromSucc();
797   // Removing the last instruction in a bundle.
798   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
799     MI->unbundleFromPred();
800   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
801   // are already fine.
802 }
803
804 MachineBasicBlock::instr_iterator
805 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
806   unbundleSingleMI(I);
807   return Insts.erase(I);
808 }
809
810 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
811   unbundleSingleMI(MI);
812   MI->clearFlag(MachineInstr::BundledPred);
813   MI->clearFlag(MachineInstr::BundledSucc);
814   return Insts.remove(MI);
815 }
816
817 MachineBasicBlock::instr_iterator
818 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
819   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
820          "Cannot insert instruction with bundle flags");
821   // Set the bundle flags when inserting inside a bundle.
822   if (I != instr_end() && I->isBundledWithPred()) {
823     MI->setFlag(MachineInstr::BundledPred);
824     MI->setFlag(MachineInstr::BundledSucc);
825   }
826   return Insts.insert(I, MI);
827 }
828
829 /// removeFromParent - This method unlinks 'this' from the containing function,
830 /// and returns it, but does not delete it.
831 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
832   assert(getParent() && "Not embedded in a function!");
833   getParent()->remove(this);
834   return this;
835 }
836
837
838 /// eraseFromParent - This method unlinks 'this' from the containing function,
839 /// and deletes it.
840 void MachineBasicBlock::eraseFromParent() {
841   assert(getParent() && "Not embedded in a function!");
842   getParent()->erase(this);
843 }
844
845
846 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
847 /// 'Old', change the code and CFG so that it branches to 'New' instead.
848 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
849                                                MachineBasicBlock *New) {
850   assert(Old != New && "Cannot replace self with self!");
851
852   MachineBasicBlock::instr_iterator I = instr_end();
853   while (I != instr_begin()) {
854     --I;
855     if (!I->isTerminator()) break;
856
857     // Scan the operands of this machine instruction, replacing any uses of Old
858     // with New.
859     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
860       if (I->getOperand(i).isMBB() &&
861           I->getOperand(i).getMBB() == Old)
862         I->getOperand(i).setMBB(New);
863   }
864
865   // Update the successor information.
866   replaceSuccessor(Old, New);
867 }
868
869 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
870 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
871 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can be
872 /// null.
873 ///
874 /// Besides DestA and DestB, retain other edges leading to LandingPads
875 /// (currently there can be only one; we don't check or require that here).
876 /// Note it is possible that DestA and/or DestB are LandingPads.
877 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
878                                              MachineBasicBlock *DestB,
879                                              bool isCond) {
880   // The values of DestA and DestB frequently come from a call to the
881   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
882   // values from there.
883   //
884   // 1. If both DestA and DestB are null, then the block ends with no branches
885   //    (it falls through to its successor).
886   // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
887   //    with only an unconditional branch.
888   // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
889   //    with a conditional branch that falls through to a successor (DestB).
890   // 4. If DestA and DestB is set and isCond is true, then the block ends with a
891   //    conditional branch followed by an unconditional branch. DestA is the
892   //    'true' destination and DestB is the 'false' destination.
893
894   bool Changed = false;
895
896   MachineFunction::iterator FallThru =
897     llvm::next(MachineFunction::iterator(this));
898
899   if (DestA == 0 && DestB == 0) {
900     // Block falls through to successor.
901     DestA = FallThru;
902     DestB = FallThru;
903   } else if (DestA != 0 && DestB == 0) {
904     if (isCond)
905       // Block ends in conditional jump that falls through to successor.
906       DestB = FallThru;
907   } else {
908     assert(DestA && DestB && isCond &&
909            "CFG in a bad state. Cannot correct CFG edges");
910   }
911
912   // Remove superfluous edges. I.e., those which aren't destinations of this
913   // basic block, duplicate edges, or landing pads.
914   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
915   MachineBasicBlock::succ_iterator SI = succ_begin();
916   while (SI != succ_end()) {
917     const MachineBasicBlock *MBB = *SI;
918     if (!SeenMBBs.insert(MBB) ||
919         (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
920       // This is a superfluous edge, remove it.
921       SI = removeSuccessor(SI);
922       Changed = true;
923     } else {
924       ++SI;
925     }
926   }
927
928   return Changed;
929 }
930
931 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
932 /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
933 DebugLoc
934 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
935   DebugLoc DL;
936   instr_iterator E = instr_end();
937   if (MBBI == E)
938     return DL;
939
940   // Skip debug declarations, we don't want a DebugLoc from them.
941   while (MBBI != E && MBBI->isDebugValue())
942     MBBI++;
943   if (MBBI != E)
944     DL = MBBI->getDebugLoc();
945   return DL;
946 }
947
948 /// getSuccWeight - Return weight of the edge from this block to MBB.
949 ///
950 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
951   if (Weights.empty())
952     return 0;
953
954   return *getWeightIterator(Succ);
955 }
956
957 /// getWeightIterator - Return wight iterator corresonding to the I successor
958 /// iterator
959 MachineBasicBlock::weight_iterator MachineBasicBlock::
960 getWeightIterator(MachineBasicBlock::succ_iterator I) {
961   assert(Weights.size() == Successors.size() && "Async weight list!");
962   size_t index = std::distance(Successors.begin(), I);
963   assert(index < Weights.size() && "Not a current successor!");
964   return Weights.begin() + index;
965 }
966
967 /// getWeightIterator - Return wight iterator corresonding to the I successor
968 /// iterator
969 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
970 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
971   assert(Weights.size() == Successors.size() && "Async weight list!");
972   const size_t index = std::distance(Successors.begin(), I);
973   assert(index < Weights.size() && "Not a current successor!");
974   return Weights.begin() + index;
975 }
976
977 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
978 /// as of just before "MI".
979 /// 
980 /// Search is localised to a neighborhood of
981 /// Neighborhood instructions before (searching for defs or kills) and N
982 /// instructions after (searching just for defs) MI.
983 MachineBasicBlock::LivenessQueryResult
984 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
985                                            unsigned Reg, MachineInstr *MI,
986                                            unsigned Neighborhood) {
987   unsigned N = Neighborhood;
988   MachineBasicBlock *MBB = MI->getParent();
989
990   // Start by searching backwards from MI, looking for kills, reads or defs.
991
992   MachineBasicBlock::iterator I(MI);
993   // If this is the first insn in the block, don't search backwards.
994   if (I != MBB->begin()) {
995     do {
996       --I;
997
998       MachineOperandIteratorBase::PhysRegInfo Analysis =
999         MIOperands(I).analyzePhysReg(Reg, TRI);
1000
1001       if (Analysis.Defines)
1002         // Outputs happen after inputs so they take precedence if both are
1003         // present.
1004         return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1005
1006       if (Analysis.Kills || Analysis.Clobbers)
1007         // Register killed, so isn't live.
1008         return LQR_Dead;
1009
1010       else if (Analysis.ReadsOverlap)
1011         // Defined or read without a previous kill - live.
1012         return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1013
1014     } while (I != MBB->begin() && --N > 0);
1015   }
1016
1017   // Did we get to the start of the block?
1018   if (I == MBB->begin()) {
1019     // If so, the register's state is definitely defined by the live-in state.
1020     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1021          RAI.isValid(); ++RAI) {
1022       if (MBB->isLiveIn(*RAI))
1023         return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1024     }
1025
1026     return LQR_Dead;
1027   }
1028
1029   N = Neighborhood;
1030
1031   // Try searching forwards from MI, looking for reads or defs.
1032   I = MachineBasicBlock::iterator(MI);
1033   // If this is the last insn in the block, don't search forwards.
1034   if (I != MBB->end()) {
1035     for (++I; I != MBB->end() && N > 0; ++I, --N) {
1036       MachineOperandIteratorBase::PhysRegInfo Analysis =
1037         MIOperands(I).analyzePhysReg(Reg, TRI);
1038
1039       if (Analysis.ReadsOverlap)
1040         // Used, therefore must have been live.
1041         return (Analysis.Reads) ?
1042           LQR_Live : LQR_OverlappingLive;
1043
1044       else if (Analysis.Clobbers || Analysis.Defines)
1045         // Defined (but not read) therefore cannot have been live.
1046         return LQR_Dead;
1047     }
1048   }
1049
1050   // At this point we have no idea of the liveness of the register.
1051   return LQR_Unknown;
1052 }
1053
1054 void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
1055                           bool t) {
1056   OS << "BB#" << MBB->getNumber();
1057 }
1058