MachineBasicBlock.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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 I = end();
  134. while (I != begin() && ((--I)->getDesc().isTerminator() || I->isDebugValue()))
  135. ; /*noop */
  136. while (I != end() && !I->getDesc().isTerminator())
  137. ++I;
  138. return I;
  139. }
  140. MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
  141. iterator B = begin(), I = end();
  142. while (I != B) {
  143. --I;
  144. if (I->isDebugValue())
  145. continue;
  146. return I;
  147. }
  148. // The block is all debug values.
  149. return end();
  150. }
  151. const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
  152. // A block with a landing pad successor only has one other successor.
  153. if (succ_size() > 2)
  154. return 0;
  155. for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
  156. if ((*I)->isLandingPad())
  157. return *I;
  158. return 0;
  159. }
  160. void MachineBasicBlock::dump() const {
  161. print(dbgs());
  162. }
  163. StringRef MachineBasicBlock::getName() const {
  164. if (const BasicBlock *LBB = getBasicBlock())
  165. return LBB->getName();
  166. else
  167. return "(null)";
  168. }
  169. void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
  170. const MachineFunction *MF = getParent();
  171. if (!MF) {
  172. OS << "Can't print out MachineBasicBlock because parent MachineFunction"
  173. << " is null\n";
  174. return;
  175. }
  176. if (Alignment) { OS << "Alignment " << Alignment << "\n"; }
  177. if (Indexes)
  178. OS << Indexes->getMBBStartIdx(this) << '\t';
  179. OS << "BB#" << getNumber() << ": ";
  180. const char *Comma = "";
  181. if (const BasicBlock *LBB = getBasicBlock()) {
  182. OS << Comma << "derived from LLVM BB ";
  183. WriteAsOperand(OS, LBB, /*PrintType=*/false);
  184. Comma = ", ";
  185. }
  186. if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
  187. if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
  188. OS << '\n';
  189. const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
  190. if (!livein_empty()) {
  191. if (Indexes) OS << '\t';
  192. OS << " Live Ins:";
  193. for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
  194. OS << ' ' << PrintReg(*I, TRI);
  195. OS << '\n';
  196. }
  197. // Print the preds of this block according to the CFG.
  198. if (!pred_empty()) {
  199. if (Indexes) OS << '\t';
  200. OS << " Predecessors according to CFG:";
  201. for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
  202. OS << " BB#" << (*PI)->getNumber();
  203. OS << '\n';
  204. }
  205. for (const_iterator I = begin(); I != end(); ++I) {
  206. if (Indexes) {
  207. if (Indexes->hasIndex(I))
  208. OS << Indexes->getInstructionIndex(I);
  209. OS << '\t';
  210. }
  211. OS << '\t';
  212. I->print(OS, &getParent()->getTarget());
  213. }
  214. // Print the successors of this block according to the CFG.
  215. if (!succ_empty()) {
  216. if (Indexes) OS << '\t';
  217. OS << " Successors according to CFG:";
  218. for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)
  219. OS << " BB#" << (*SI)->getNumber();
  220. OS << '\n';
  221. }
  222. }
  223. void MachineBasicBlock::removeLiveIn(unsigned Reg) {
  224. std::vector<unsigned>::iterator I =
  225. std::find(LiveIns.begin(), LiveIns.end(), Reg);
  226. assert(I != LiveIns.end() && "Not a live in!");
  227. LiveIns.erase(I);
  228. }
  229. bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
  230. livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
  231. return I != livein_end();
  232. }
  233. void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
  234. getParent()->splice(NewAfter, this);
  235. }
  236. void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
  237. MachineFunction::iterator BBI = NewBefore;
  238. getParent()->splice(++BBI, this);
  239. }
  240. void MachineBasicBlock::updateTerminator() {
  241. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  242. // A block with no successors has no concerns with fall-through edges.
  243. if (this->succ_empty()) return;
  244. MachineBasicBlock *TBB = 0, *FBB = 0;
  245. SmallVector<MachineOperand, 4> Cond;
  246. DebugLoc dl; // FIXME: this is nowhere
  247. bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
  248. (void) B;
  249. assert(!B && "UpdateTerminators requires analyzable predecessors!");
  250. if (Cond.empty()) {
  251. if (TBB) {
  252. // The block has an unconditional branch. If its successor is now
  253. // its layout successor, delete the branch.
  254. if (isLayoutSuccessor(TBB))
  255. TII->RemoveBranch(*this);
  256. } else {
  257. // The block has an unconditional fallthrough. If its successor is not
  258. // its layout successor, insert a branch.
  259. TBB = *succ_begin();
  260. if (!isLayoutSuccessor(TBB))
  261. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  262. }
  263. } else {
  264. if (FBB) {
  265. // The block has a non-fallthrough conditional branch. If one of its
  266. // successors is its layout successor, rewrite it to a fallthrough
  267. // conditional branch.
  268. if (isLayoutSuccessor(TBB)) {
  269. if (TII->ReverseBranchCondition(Cond))
  270. return;
  271. TII->RemoveBranch(*this);
  272. TII->InsertBranch(*this, FBB, 0, Cond, dl);
  273. } else if (isLayoutSuccessor(FBB)) {
  274. TII->RemoveBranch(*this);
  275. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  276. }
  277. } else {
  278. // The block has a fallthrough conditional branch.
  279. MachineBasicBlock *MBBA = *succ_begin();
  280. MachineBasicBlock *MBBB = *llvm::next(succ_begin());
  281. if (MBBA == TBB) std::swap(MBBB, MBBA);
  282. if (isLayoutSuccessor(TBB)) {
  283. if (TII->ReverseBranchCondition(Cond)) {
  284. // We can't reverse the condition, add an unconditional branch.
  285. Cond.clear();
  286. TII->InsertBranch(*this, MBBA, 0, Cond, dl);
  287. return;
  288. }
  289. TII->RemoveBranch(*this);
  290. TII->InsertBranch(*this, MBBA, 0, Cond, dl);
  291. } else if (!isLayoutSuccessor(MBBA)) {
  292. TII->RemoveBranch(*this);
  293. TII->InsertBranch(*this, TBB, MBBA, Cond, dl);
  294. }
  295. }
  296. }
  297. }
  298. void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) {
  299. Successors.push_back(succ);
  300. succ->addPredecessor(this);
  301. }
  302. void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
  303. succ->removePredecessor(this);
  304. succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
  305. assert(I != Successors.end() && "Not a current successor!");
  306. Successors.erase(I);
  307. }
  308. MachineBasicBlock::succ_iterator
  309. MachineBasicBlock::removeSuccessor(succ_iterator I) {
  310. assert(I != Successors.end() && "Not a current successor!");
  311. (*I)->removePredecessor(this);
  312. return Successors.erase(I);
  313. }
  314. void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
  315. Predecessors.push_back(pred);
  316. }
  317. void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
  318. pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
  319. assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
  320. Predecessors.erase(I);
  321. }
  322. void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
  323. if (this == fromMBB)
  324. return;
  325. while (!fromMBB->succ_empty()) {
  326. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  327. addSuccessor(Succ);
  328. fromMBB->removeSuccessor(Succ);
  329. }
  330. }
  331. void
  332. MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
  333. if (this == fromMBB)
  334. return;
  335. while (!fromMBB->succ_empty()) {
  336. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  337. addSuccessor(Succ);
  338. fromMBB->removeSuccessor(Succ);
  339. // Fix up any PHI nodes in the successor.
  340. for (MachineBasicBlock::iterator MI = Succ->begin(), ME = Succ->end();
  341. MI != ME && MI->isPHI(); ++MI)
  342. for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
  343. MachineOperand &MO = MI->getOperand(i);
  344. if (MO.getMBB() == fromMBB)
  345. MO.setMBB(this);
  346. }
  347. }
  348. }
  349. bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
  350. const_succ_iterator I = std::find(Successors.begin(), Successors.end(), MBB);
  351. return I != Successors.end();
  352. }
  353. bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
  354. MachineFunction::const_iterator I(this);
  355. return llvm::next(I) == MachineFunction::const_iterator(MBB);
  356. }
  357. bool MachineBasicBlock::canFallThrough() {
  358. MachineFunction::iterator Fallthrough = this;
  359. ++Fallthrough;
  360. // If FallthroughBlock is off the end of the function, it can't fall through.
  361. if (Fallthrough == getParent()->end())
  362. return false;
  363. // If FallthroughBlock isn't a successor, no fallthrough is possible.
  364. if (!isSuccessor(Fallthrough))
  365. return false;
  366. // Analyze the branches, if any, at the end of the block.
  367. MachineBasicBlock *TBB = 0, *FBB = 0;
  368. SmallVector<MachineOperand, 4> Cond;
  369. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  370. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
  371. // If we couldn't analyze the branch, examine the last instruction.
  372. // If the block doesn't end in a known control barrier, assume fallthrough
  373. // is possible. The isPredicable check is needed because this code can be
  374. // called during IfConversion, where an instruction which is normally a
  375. // Barrier is predicated and thus no longer an actual control barrier. This
  376. // is over-conservative though, because if an instruction isn't actually
  377. // predicated we could still treat it like a barrier.
  378. return empty() || !back().getDesc().isBarrier() ||
  379. back().getDesc().isPredicable();
  380. }
  381. // If there is no branch, control always falls through.
  382. if (TBB == 0) return true;
  383. // If there is some explicit branch to the fallthrough block, it can obviously
  384. // reach, even though the branch should get folded to fall through implicitly.
  385. if (MachineFunction::iterator(TBB) == Fallthrough ||
  386. MachineFunction::iterator(FBB) == Fallthrough)
  387. return true;
  388. // If it's an unconditional branch to some block not the fall through, it
  389. // doesn't fall through.
  390. if (Cond.empty()) return false;
  391. // Otherwise, if it is conditional and has no explicit false block, it falls
  392. // through.
  393. return FBB == 0;
  394. }
  395. MachineBasicBlock *
  396. MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
  397. MachineFunction *MF = getParent();
  398. DebugLoc dl; // FIXME: this is nowhere
  399. // We may need to update this's terminator, but we can't do that if
  400. // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
  401. const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
  402. MachineBasicBlock *TBB = 0, *FBB = 0;
  403. SmallVector<MachineOperand, 4> Cond;
  404. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
  405. return NULL;
  406. // Avoid bugpoint weirdness: A block may end with a conditional branch but
  407. // jumps to the same MBB is either case. We have duplicate CFG edges in that
  408. // case that we can't handle. Since this never happens in properly optimized
  409. // code, just skip those edges.
  410. if (TBB && TBB == FBB) {
  411. DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
  412. << getNumber() << '\n');
  413. return NULL;
  414. }
  415. MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
  416. MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
  417. DEBUG(dbgs() << "Splitting critical edge:"
  418. " BB#" << getNumber()
  419. << " -- BB#" << NMBB->getNumber()
  420. << " -- BB#" << Succ->getNumber() << '\n');
  421. // On some targets like Mips, branches may kill virtual registers. Make sure
  422. // that LiveVariables is properly updated after updateTerminator replaces the
  423. // terminators.
  424. LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
  425. // Collect a list of virtual registers killed by the terminators.
  426. SmallVector<unsigned, 4> KilledRegs;
  427. if (LV)
  428. for (iterator I = getFirstTerminator(), E = end(); I != E; ++I) {
  429. MachineInstr *MI = I;
  430. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  431. OE = MI->operands_end(); OI != OE; ++OI) {
  432. if (!OI->isReg() || !OI->isUse() || !OI->isKill() || OI->isUndef())
  433. continue;
  434. unsigned Reg = OI->getReg();
  435. if (TargetRegisterInfo::isVirtualRegister(Reg) &&
  436. LV->getVarInfo(Reg).removeKill(MI)) {
  437. KilledRegs.push_back(Reg);
  438. DEBUG(dbgs() << "Removing terminator kill: " << *MI);
  439. OI->setIsKill(false);
  440. }
  441. }
  442. }
  443. ReplaceUsesOfBlockWith(Succ, NMBB);
  444. updateTerminator();
  445. // Insert unconditional "jump Succ" instruction in NMBB if necessary.
  446. NMBB->addSuccessor(Succ);
  447. if (!NMBB->isLayoutSuccessor(Succ)) {
  448. Cond.clear();
  449. MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
  450. }
  451. // Fix PHI nodes in Succ so they refer to NMBB instead of this
  452. for (MachineBasicBlock::iterator i = Succ->begin(), e = Succ->end();
  453. i != e && i->isPHI(); ++i)
  454. for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
  455. if (i->getOperand(ni+1).getMBB() == this)
  456. i->getOperand(ni+1).setMBB(NMBB);
  457. // Update LiveVariables.
  458. if (LV) {
  459. // Restore kills of virtual registers that were killed by the terminators.
  460. while (!KilledRegs.empty()) {
  461. unsigned Reg = KilledRegs.pop_back_val();
  462. for (iterator I = end(), E = begin(); I != E;) {
  463. if (!(--I)->addRegisterKilled(Reg, NULL, /* addIfNotFound= */ false))
  464. continue;
  465. LV->getVarInfo(Reg).Kills.push_back(I);
  466. DEBUG(dbgs() << "Restored terminator kill: " << *I);
  467. break;
  468. }
  469. }
  470. // Update relevant live-through information.
  471. LV->addNewBlock(NMBB, this, Succ);
  472. }
  473. if (MachineDominatorTree *MDT =
  474. P->getAnalysisIfAvailable<MachineDominatorTree>()) {
  475. // Update dominator information.
  476. MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
  477. bool IsNewIDom = true;
  478. for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
  479. PI != E; ++PI) {
  480. MachineBasicBlock *PredBB = *PI;
  481. if (PredBB == NMBB)
  482. continue;
  483. if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
  484. IsNewIDom = false;
  485. break;
  486. }
  487. }
  488. // We know "this" dominates the newly created basic block.
  489. MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
  490. // If all the other predecessors of "Succ" are dominated by "Succ" itself
  491. // then the new block is the new immediate dominator of "Succ". Otherwise,
  492. // the new block doesn't dominate anything.
  493. if (IsNewIDom)
  494. MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
  495. }
  496. if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
  497. if (MachineLoop *TIL = MLI->getLoopFor(this)) {
  498. // If one or the other blocks were not in a loop, the new block is not
  499. // either, and thus LI doesn't need to be updated.
  500. if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
  501. if (TIL == DestLoop) {
  502. // Both in the same loop, the NMBB joins loop.
  503. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  504. } else if (TIL->contains(DestLoop)) {
  505. // Edge from an outer loop to an inner loop. Add to the outer loop.
  506. TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
  507. } else if (DestLoop->contains(TIL)) {
  508. // Edge from an inner loop to an outer loop. Add to the outer loop.
  509. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  510. } else {
  511. // Edge from two loops with no containment relation. Because these
  512. // are natural loops, we know that the destination block must be the
  513. // header of its loop (adding a branch into a loop elsewhere would
  514. // create an irreducible loop).
  515. assert(DestLoop->getHeader() == Succ &&
  516. "Should not create irreducible loops!");
  517. if (MachineLoop *P = DestLoop->getParentLoop())
  518. P->addBasicBlockToLoop(NMBB, MLI->getBase());
  519. }
  520. }
  521. }
  522. return NMBB;
  523. }
  524. /// removeFromParent - This method unlinks 'this' from the containing function,
  525. /// and returns it, but does not delete it.
  526. MachineBasicBlock *MachineBasicBlock::removeFromParent() {
  527. assert(getParent() && "Not embedded in a function!");
  528. getParent()->remove(this);
  529. return this;
  530. }
  531. /// eraseFromParent - This method unlinks 'this' from the containing function,
  532. /// and deletes it.
  533. void MachineBasicBlock::eraseFromParent() {
  534. assert(getParent() && "Not embedded in a function!");
  535. getParent()->erase(this);
  536. }
  537. /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
  538. /// 'Old', change the code and CFG so that it branches to 'New' instead.
  539. void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
  540. MachineBasicBlock *New) {
  541. assert(Old != New && "Cannot replace self with self!");
  542. MachineBasicBlock::iterator I = end();
  543. while (I != begin()) {
  544. --I;
  545. if (!I->getDesc().isTerminator()) break;
  546. // Scan the operands of this machine instruction, replacing any uses of Old
  547. // with New.
  548. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  549. if (I->getOperand(i).isMBB() &&
  550. I->getOperand(i).getMBB() == Old)
  551. I->getOperand(i).setMBB(New);
  552. }
  553. // Update the successor information.
  554. removeSuccessor(Old);
  555. addSuccessor(New);
  556. }
  557. /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
  558. /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
  559. /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
  560. /// null.
  561. ///
  562. /// Besides DestA and DestB, retain other edges leading to LandingPads
  563. /// (currently there can be only one; we don't check or require that here).
  564. /// Note it is possible that DestA and/or DestB are LandingPads.
  565. bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
  566. MachineBasicBlock *DestB,
  567. bool isCond) {
  568. // The values of DestA and DestB frequently come from a call to the
  569. // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
  570. // values from there.
  571. //
  572. // 1. If both DestA and DestB are null, then the block ends with no branches
  573. // (it falls through to its successor).
  574. // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
  575. // with only an unconditional branch.
  576. // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
  577. // with a conditional branch that falls through to a successor (DestB).
  578. // 4. If DestA and DestB is set and isCond is true, then the block ends with a
  579. // conditional branch followed by an unconditional branch. DestA is the
  580. // 'true' destination and DestB is the 'false' destination.
  581. bool Changed = false;
  582. MachineFunction::iterator FallThru =
  583. llvm::next(MachineFunction::iterator(this));
  584. if (DestA == 0 && DestB == 0) {
  585. // Block falls through to successor.
  586. DestA = FallThru;
  587. DestB = FallThru;
  588. } else if (DestA != 0 && DestB == 0) {
  589. if (isCond)
  590. // Block ends in conditional jump that falls through to successor.
  591. DestB = FallThru;
  592. } else {
  593. assert(DestA && DestB && isCond &&
  594. "CFG in a bad state. Cannot correct CFG edges");
  595. }
  596. // Remove superfluous edges. I.e., those which aren't destinations of this
  597. // basic block, duplicate edges, or landing pads.
  598. SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
  599. MachineBasicBlock::succ_iterator SI = succ_begin();
  600. while (SI != succ_end()) {
  601. const MachineBasicBlock *MBB = *SI;
  602. if (!SeenMBBs.insert(MBB) ||
  603. (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
  604. // This is a superfluous edge, remove it.
  605. SI = removeSuccessor(SI);
  606. Changed = true;
  607. } else {
  608. ++SI;
  609. }
  610. }
  611. return Changed;
  612. }
  613. /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
  614. /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
  615. DebugLoc
  616. MachineBasicBlock::findDebugLoc(MachineBasicBlock::iterator &MBBI) {
  617. DebugLoc DL;
  618. MachineBasicBlock::iterator E = end();
  619. if (MBBI != E) {
  620. // Skip debug declarations, we don't want a DebugLoc from them.
  621. MachineBasicBlock::iterator MBBI2 = MBBI;
  622. while (MBBI2 != E && MBBI2->isDebugValue())
  623. MBBI2++;
  624. if (MBBI2 != E)
  625. DL = MBBI2->getDebugLoc();
  626. }
  627. return DL;
  628. }
  629. void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
  630. bool t) {
  631. OS << "BB#" << MBB->getNumber();
  632. }