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