MachineBasicBlock.cpp 24 KB

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