MachineBasicBlock.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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/TargetInstrInfo.h"
  25. #include "llvm/Target/TargetMachine.h"
  26. #include "llvm/Assembly/Writer.h"
  27. #include "llvm/ADT/SmallString.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/LeakDetector.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
  35. : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
  36. AddressTaken(false) {
  37. Insts.Parent = this;
  38. }
  39. MachineBasicBlock::~MachineBasicBlock() {
  40. LeakDetector::removeGarbageObject(this);
  41. }
  42. /// getSymbol - Return the MCSymbol for this basic block.
  43. ///
  44. MCSymbol *MachineBasicBlock::getSymbol() const {
  45. const MachineFunction *MF = getParent();
  46. MCContext &Ctx = MF->getContext();
  47. const char *Prefix = Ctx.getAsmInfo().getPrivateGlobalPrefix();
  48. return Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
  49. Twine(MF->getFunctionNumber()) + "_" +
  50. Twine(getNumber()));
  51. }
  52. raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
  53. MBB.print(OS);
  54. return OS;
  55. }
  56. /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
  57. /// parent pointer of the MBB, the MBB numbering, and any instructions in the
  58. /// MBB to be on the right operand list for registers.
  59. ///
  60. /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
  61. /// gets the next available unique MBB number. If it is removed from a
  62. /// MachineFunction, it goes back to being #-1.
  63. void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
  64. MachineFunction &MF = *N->getParent();
  65. N->Number = MF.addToMBBNumbering(N);
  66. // Make sure the instructions have their operands in the reginfo lists.
  67. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  68. for (MachineBasicBlock::instr_iterator
  69. I = N->instr_begin(), E = N->instr_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. ilist_iterator<MachineInstr> first,
  106. ilist_iterator<MachineInstr> 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. instr_iterator I = instr_begin();
  122. while (I != end() && I->isPHI())
  123. ++I;
  124. assert(!I->isInsideBundle() && "First non-phi MI cannot be inside a bundle!");
  125. return I;
  126. }
  127. MachineBasicBlock::iterator
  128. MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
  129. while (I != end() && (I->isPHI() || I->isLabel() || I->isDebugValue()))
  130. ++I;
  131. // FIXME: This needs to change if we wish to bundle labels / dbg_values
  132. // inside the bundle.
  133. assert(!I->isInsideBundle() &&
  134. "First non-phi / non-label instruction is inside a bundle!");
  135. return I;
  136. }
  137. MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
  138. iterator I = end();
  139. while (I != begin() && ((--I)->isTerminator() || I->isDebugValue()))
  140. ; /*noop */
  141. while (I != end() && !I->isTerminator())
  142. ++I;
  143. return I;
  144. }
  145. MachineBasicBlock::const_iterator
  146. MachineBasicBlock::getFirstTerminator() const {
  147. const_iterator I = end();
  148. while (I != begin() && ((--I)->isTerminator() || I->isDebugValue()))
  149. ; /*noop */
  150. while (I != end() && !I->isTerminator())
  151. ++I;
  152. return I;
  153. }
  154. MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
  155. instr_iterator I = instr_end();
  156. while (I != instr_begin() && ((--I)->isTerminator() || I->isDebugValue()))
  157. ; /*noop */
  158. while (I != instr_end() && !I->isTerminator())
  159. ++I;
  160. return I;
  161. }
  162. MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
  163. // Skip over end-of-block dbg_value instructions.
  164. instr_iterator B = instr_begin(), I = instr_end();
  165. while (I != B) {
  166. --I;
  167. // Return instruction that starts a bundle.
  168. if (I->isDebugValue() || I->isInsideBundle())
  169. continue;
  170. return I;
  171. }
  172. // The block is all debug values.
  173. return end();
  174. }
  175. MachineBasicBlock::const_iterator
  176. MachineBasicBlock::getLastNonDebugInstr() const {
  177. // Skip over end-of-block dbg_value instructions.
  178. const_instr_iterator B = instr_begin(), I = instr_end();
  179. while (I != B) {
  180. --I;
  181. // Return instruction that starts a bundle.
  182. if (I->isDebugValue() || I->isInsideBundle())
  183. continue;
  184. return I;
  185. }
  186. // The block is all debug values.
  187. return end();
  188. }
  189. const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
  190. // A block with a landing pad successor only has one other successor.
  191. if (succ_size() > 2)
  192. return 0;
  193. for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
  194. if ((*I)->isLandingPad())
  195. return *I;
  196. return 0;
  197. }
  198. void MachineBasicBlock::dump() const {
  199. print(dbgs());
  200. }
  201. StringRef MachineBasicBlock::getName() const {
  202. if (const BasicBlock *LBB = getBasicBlock())
  203. return LBB->getName();
  204. else
  205. return "(null)";
  206. }
  207. void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
  208. const MachineFunction *MF = getParent();
  209. if (!MF) {
  210. OS << "Can't print out MachineBasicBlock because parent MachineFunction"
  211. << " is null\n";
  212. return;
  213. }
  214. if (Indexes)
  215. OS << Indexes->getMBBStartIdx(this) << '\t';
  216. OS << "BB#" << getNumber() << ": ";
  217. const char *Comma = "";
  218. if (const BasicBlock *LBB = getBasicBlock()) {
  219. OS << Comma << "derived from LLVM BB ";
  220. WriteAsOperand(OS, LBB, /*PrintType=*/false);
  221. Comma = ", ";
  222. }
  223. if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
  224. if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
  225. if (Alignment) {
  226. OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
  227. << " bytes)";
  228. Comma = ", ";
  229. }
  230. OS << '\n';
  231. const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
  232. if (!livein_empty()) {
  233. if (Indexes) OS << '\t';
  234. OS << " Live Ins:";
  235. for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
  236. OS << ' ' << PrintReg(*I, TRI);
  237. OS << '\n';
  238. }
  239. // Print the preds of this block according to the CFG.
  240. if (!pred_empty()) {
  241. if (Indexes) OS << '\t';
  242. OS << " Predecessors according to CFG:";
  243. for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
  244. OS << " BB#" << (*PI)->getNumber();
  245. OS << '\n';
  246. }
  247. for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
  248. if (Indexes) {
  249. if (Indexes->hasIndex(I))
  250. OS << Indexes->getInstructionIndex(I);
  251. OS << '\t';
  252. }
  253. OS << '\t';
  254. if (I->isInsideBundle())
  255. OS << " * ";
  256. I->print(OS, &getParent()->getTarget());
  257. }
  258. // Print the successors of this block according to the CFG.
  259. if (!succ_empty()) {
  260. if (Indexes) OS << '\t';
  261. OS << " Successors according to CFG:";
  262. for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)
  263. OS << " BB#" << (*SI)->getNumber();
  264. OS << '\n';
  265. }
  266. }
  267. void MachineBasicBlock::removeLiveIn(unsigned Reg) {
  268. std::vector<unsigned>::iterator I =
  269. std::find(LiveIns.begin(), LiveIns.end(), Reg);
  270. assert(I != LiveIns.end() && "Not a live in!");
  271. LiveIns.erase(I);
  272. }
  273. bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
  274. livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
  275. return I != livein_end();
  276. }
  277. void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
  278. getParent()->splice(NewAfter, this);
  279. }
  280. void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
  281. MachineFunction::iterator BBI = NewBefore;
  282. getParent()->splice(++BBI, this);
  283. }
  284. void MachineBasicBlock::updateTerminator() {
  285. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  286. // A block with no successors has no concerns with fall-through edges.
  287. if (this->succ_empty()) return;
  288. MachineBasicBlock *TBB = 0, *FBB = 0;
  289. SmallVector<MachineOperand, 4> Cond;
  290. DebugLoc dl; // FIXME: this is nowhere
  291. bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
  292. (void) B;
  293. assert(!B && "UpdateTerminators requires analyzable predecessors!");
  294. if (Cond.empty()) {
  295. if (TBB) {
  296. // The block has an unconditional branch. If its successor is now
  297. // its layout successor, delete the branch.
  298. if (isLayoutSuccessor(TBB))
  299. TII->RemoveBranch(*this);
  300. } else {
  301. // The block has an unconditional fallthrough. If its successor is not
  302. // its layout successor, insert a branch. First we have to locate the
  303. // only non-landing-pad successor, as that is the fallthrough block.
  304. for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
  305. if ((*SI)->isLandingPad())
  306. continue;
  307. assert(!TBB && "Found more than one non-landing-pad successor!");
  308. TBB = *SI;
  309. }
  310. // If there is no non-landing-pad successor, the block has no
  311. // fall-through edges to be concerned with.
  312. if (!TBB)
  313. return;
  314. // Finally update the unconditional successor to be reached via a branch
  315. // if it would not be reached by fallthrough.
  316. if (!isLayoutSuccessor(TBB))
  317. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  318. }
  319. } else {
  320. if (FBB) {
  321. // The block has a non-fallthrough conditional branch. If one of its
  322. // successors is its layout successor, rewrite it to a fallthrough
  323. // conditional branch.
  324. if (isLayoutSuccessor(TBB)) {
  325. if (TII->ReverseBranchCondition(Cond))
  326. return;
  327. TII->RemoveBranch(*this);
  328. TII->InsertBranch(*this, FBB, 0, Cond, dl);
  329. } else if (isLayoutSuccessor(FBB)) {
  330. TII->RemoveBranch(*this);
  331. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  332. }
  333. } else {
  334. // The block has a fallthrough conditional branch.
  335. MachineBasicBlock *MBBA = *succ_begin();
  336. MachineBasicBlock *MBBB = *llvm::next(succ_begin());
  337. if (MBBA == TBB) std::swap(MBBB, MBBA);
  338. if (isLayoutSuccessor(TBB)) {
  339. if (TII->ReverseBranchCondition(Cond)) {
  340. // We can't reverse the condition, add an unconditional branch.
  341. Cond.clear();
  342. TII->InsertBranch(*this, MBBA, 0, Cond, dl);
  343. return;
  344. }
  345. TII->RemoveBranch(*this);
  346. TII->InsertBranch(*this, MBBA, 0, Cond, dl);
  347. } else if (!isLayoutSuccessor(MBBA)) {
  348. TII->RemoveBranch(*this);
  349. TII->InsertBranch(*this, TBB, MBBA, Cond, dl);
  350. }
  351. }
  352. }
  353. }
  354. void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
  355. // If we see non-zero value for the first time it means we actually use Weight
  356. // list, so we fill all Weights with 0's.
  357. if (weight != 0 && Weights.empty())
  358. Weights.resize(Successors.size());
  359. if (weight != 0 || !Weights.empty())
  360. Weights.push_back(weight);
  361. Successors.push_back(succ);
  362. succ->addPredecessor(this);
  363. }
  364. void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
  365. succ->removePredecessor(this);
  366. succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
  367. assert(I != Successors.end() && "Not a current successor!");
  368. // If Weight list is empty it means we don't use it (disabled optimization).
  369. if (!Weights.empty()) {
  370. weight_iterator WI = getWeightIterator(I);
  371. Weights.erase(WI);
  372. }
  373. Successors.erase(I);
  374. }
  375. MachineBasicBlock::succ_iterator
  376. MachineBasicBlock::removeSuccessor(succ_iterator I) {
  377. assert(I != Successors.end() && "Not a current successor!");
  378. // If Weight list is empty it means we don't use it (disabled optimization).
  379. if (!Weights.empty()) {
  380. weight_iterator WI = getWeightIterator(I);
  381. Weights.erase(WI);
  382. }
  383. (*I)->removePredecessor(this);
  384. return Successors.erase(I);
  385. }
  386. void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
  387. MachineBasicBlock *New) {
  388. uint32_t weight = 0;
  389. succ_iterator SI = std::find(Successors.begin(), Successors.end(), Old);
  390. // If Weight list is empty it means we don't use it (disabled optimization).
  391. if (!Weights.empty()) {
  392. weight_iterator WI = getWeightIterator(SI);
  393. weight = *WI;
  394. }
  395. // Update the successor information.
  396. removeSuccessor(SI);
  397. addSuccessor(New, weight);
  398. }
  399. void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
  400. Predecessors.push_back(pred);
  401. }
  402. void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
  403. pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
  404. assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
  405. Predecessors.erase(I);
  406. }
  407. void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
  408. if (this == fromMBB)
  409. return;
  410. while (!fromMBB->succ_empty()) {
  411. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  412. uint32_t weight = 0;
  413. // If Weight list is empty it means we don't use it (disabled optimization).
  414. if (!fromMBB->Weights.empty())
  415. weight = *fromMBB->Weights.begin();
  416. addSuccessor(Succ, weight);
  417. fromMBB->removeSuccessor(Succ);
  418. }
  419. }
  420. void
  421. MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
  422. if (this == fromMBB)
  423. return;
  424. while (!fromMBB->succ_empty()) {
  425. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  426. addSuccessor(Succ);
  427. fromMBB->removeSuccessor(Succ);
  428. // Fix up any PHI nodes in the successor.
  429. for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
  430. ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
  431. for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
  432. MachineOperand &MO = MI->getOperand(i);
  433. if (MO.getMBB() == fromMBB)
  434. MO.setMBB(this);
  435. }
  436. }
  437. }
  438. bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
  439. const_succ_iterator I = std::find(Successors.begin(), Successors.end(), MBB);
  440. return I != Successors.end();
  441. }
  442. bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
  443. MachineFunction::const_iterator I(this);
  444. return llvm::next(I) == MachineFunction::const_iterator(MBB);
  445. }
  446. bool MachineBasicBlock::canFallThrough() {
  447. MachineFunction::iterator Fallthrough = this;
  448. ++Fallthrough;
  449. // If FallthroughBlock is off the end of the function, it can't fall through.
  450. if (Fallthrough == getParent()->end())
  451. return false;
  452. // If FallthroughBlock isn't a successor, no fallthrough is possible.
  453. if (!isSuccessor(Fallthrough))
  454. return false;
  455. // Analyze the branches, if any, at the end of the block.
  456. MachineBasicBlock *TBB = 0, *FBB = 0;
  457. SmallVector<MachineOperand, 4> Cond;
  458. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  459. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
  460. // If we couldn't analyze the branch, examine the last instruction.
  461. // If the block doesn't end in a known control barrier, assume fallthrough
  462. // is possible. The isPredicable check is needed because this code can be
  463. // called during IfConversion, where an instruction which is normally a
  464. // Barrier is predicated and thus no longer an actual control barrier. This
  465. // is over-conservative though, because if an instruction isn't actually
  466. // predicated we could still treat it like a barrier.
  467. return empty() || !back().isBarrier() ||
  468. back().isPredicable();
  469. }
  470. // If there is no branch, control always falls through.
  471. if (TBB == 0) return true;
  472. // If there is some explicit branch to the fallthrough block, it can obviously
  473. // reach, even though the branch should get folded to fall through implicitly.
  474. if (MachineFunction::iterator(TBB) == Fallthrough ||
  475. MachineFunction::iterator(FBB) == Fallthrough)
  476. return true;
  477. // If it's an unconditional branch to some block not the fall through, it
  478. // doesn't fall through.
  479. if (Cond.empty()) return false;
  480. // Otherwise, if it is conditional and has no explicit false block, it falls
  481. // through.
  482. return FBB == 0;
  483. }
  484. MachineBasicBlock *
  485. MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
  486. MachineFunction *MF = getParent();
  487. DebugLoc dl; // FIXME: this is nowhere
  488. // We may need to update this's terminator, but we can't do that if
  489. // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
  490. const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
  491. MachineBasicBlock *TBB = 0, *FBB = 0;
  492. SmallVector<MachineOperand, 4> Cond;
  493. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
  494. return NULL;
  495. // Avoid bugpoint weirdness: A block may end with a conditional branch but
  496. // jumps to the same MBB is either case. We have duplicate CFG edges in that
  497. // case that we can't handle. Since this never happens in properly optimized
  498. // code, just skip those edges.
  499. if (TBB && TBB == FBB) {
  500. DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
  501. << getNumber() << '\n');
  502. return NULL;
  503. }
  504. MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
  505. MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
  506. DEBUG(dbgs() << "Splitting critical edge:"
  507. " BB#" << getNumber()
  508. << " -- BB#" << NMBB->getNumber()
  509. << " -- BB#" << Succ->getNumber() << '\n');
  510. // On some targets like Mips, branches may kill virtual registers. Make sure
  511. // that LiveVariables is properly updated after updateTerminator replaces the
  512. // terminators.
  513. LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
  514. // Collect a list of virtual registers killed by the terminators.
  515. SmallVector<unsigned, 4> KilledRegs;
  516. if (LV)
  517. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  518. I != E; ++I) {
  519. MachineInstr *MI = I;
  520. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  521. OE = MI->operands_end(); OI != OE; ++OI) {
  522. if (!OI->isReg() || !OI->isUse() || !OI->isKill() || OI->isUndef())
  523. continue;
  524. unsigned Reg = OI->getReg();
  525. if (TargetRegisterInfo::isVirtualRegister(Reg) &&
  526. LV->getVarInfo(Reg).removeKill(MI)) {
  527. KilledRegs.push_back(Reg);
  528. DEBUG(dbgs() << "Removing terminator kill: " << *MI);
  529. OI->setIsKill(false);
  530. }
  531. }
  532. }
  533. ReplaceUsesOfBlockWith(Succ, NMBB);
  534. updateTerminator();
  535. // Insert unconditional "jump Succ" instruction in NMBB if necessary.
  536. NMBB->addSuccessor(Succ);
  537. if (!NMBB->isLayoutSuccessor(Succ)) {
  538. Cond.clear();
  539. MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
  540. }
  541. // Fix PHI nodes in Succ so they refer to NMBB instead of this
  542. for (MachineBasicBlock::instr_iterator
  543. i = Succ->instr_begin(),e = Succ->instr_end();
  544. i != e && i->isPHI(); ++i)
  545. for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
  546. if (i->getOperand(ni+1).getMBB() == this)
  547. i->getOperand(ni+1).setMBB(NMBB);
  548. // Inherit live-ins from the successor
  549. for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
  550. E = Succ->livein_end(); I != E; ++I)
  551. NMBB->addLiveIn(*I);
  552. // Update LiveVariables.
  553. if (LV) {
  554. // Restore kills of virtual registers that were killed by the terminators.
  555. while (!KilledRegs.empty()) {
  556. unsigned Reg = KilledRegs.pop_back_val();
  557. for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
  558. if (!(--I)->addRegisterKilled(Reg, NULL, /* addIfNotFound= */ false))
  559. continue;
  560. LV->getVarInfo(Reg).Kills.push_back(I);
  561. DEBUG(dbgs() << "Restored terminator kill: " << *I);
  562. break;
  563. }
  564. }
  565. // Update relevant live-through information.
  566. LV->addNewBlock(NMBB, this, Succ);
  567. }
  568. if (MachineDominatorTree *MDT =
  569. P->getAnalysisIfAvailable<MachineDominatorTree>()) {
  570. // Update dominator information.
  571. MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
  572. bool IsNewIDom = true;
  573. for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
  574. PI != E; ++PI) {
  575. MachineBasicBlock *PredBB = *PI;
  576. if (PredBB == NMBB)
  577. continue;
  578. if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
  579. IsNewIDom = false;
  580. break;
  581. }
  582. }
  583. // We know "this" dominates the newly created basic block.
  584. MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
  585. // If all the other predecessors of "Succ" are dominated by "Succ" itself
  586. // then the new block is the new immediate dominator of "Succ". Otherwise,
  587. // the new block doesn't dominate anything.
  588. if (IsNewIDom)
  589. MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
  590. }
  591. if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
  592. if (MachineLoop *TIL = MLI->getLoopFor(this)) {
  593. // If one or the other blocks were not in a loop, the new block is not
  594. // either, and thus LI doesn't need to be updated.
  595. if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
  596. if (TIL == DestLoop) {
  597. // Both in the same loop, the NMBB joins loop.
  598. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  599. } else if (TIL->contains(DestLoop)) {
  600. // Edge from an outer loop to an inner loop. Add to the outer loop.
  601. TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
  602. } else if (DestLoop->contains(TIL)) {
  603. // Edge from an inner loop to an outer loop. Add to the outer loop.
  604. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  605. } else {
  606. // Edge from two loops with no containment relation. Because these
  607. // are natural loops, we know that the destination block must be the
  608. // header of its loop (adding a branch into a loop elsewhere would
  609. // create an irreducible loop).
  610. assert(DestLoop->getHeader() == Succ &&
  611. "Should not create irreducible loops!");
  612. if (MachineLoop *P = DestLoop->getParentLoop())
  613. P->addBasicBlockToLoop(NMBB, MLI->getBase());
  614. }
  615. }
  616. }
  617. return NMBB;
  618. }
  619. MachineBasicBlock::iterator
  620. MachineBasicBlock::erase(MachineBasicBlock::iterator I) {
  621. if (I->isBundle()) {
  622. MachineBasicBlock::iterator E = llvm::next(I);
  623. return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
  624. }
  625. return Insts.erase(I.getInstrIterator());
  626. }
  627. MachineInstr *MachineBasicBlock::remove(MachineInstr *I) {
  628. if (I->isBundle()) {
  629. MachineBasicBlock::instr_iterator MII = I; ++MII;
  630. while (MII != end() && MII->isInsideBundle()) {
  631. MachineInstr *MI = &*MII++;
  632. Insts.remove(MI);
  633. }
  634. }
  635. return Insts.remove(I);
  636. }
  637. void MachineBasicBlock::splice(MachineBasicBlock::iterator where,
  638. MachineBasicBlock *Other,
  639. MachineBasicBlock::iterator From) {
  640. if (From->isBundle()) {
  641. MachineBasicBlock::iterator To = llvm::next(From);
  642. Insts.splice(where.getInstrIterator(), Other->Insts,
  643. From.getInstrIterator(), To.getInstrIterator());
  644. return;
  645. }
  646. Insts.splice(where.getInstrIterator(), Other->Insts, From.getInstrIterator());
  647. }
  648. /// removeFromParent - This method unlinks 'this' from the containing function,
  649. /// and returns it, but does not delete it.
  650. MachineBasicBlock *MachineBasicBlock::removeFromParent() {
  651. assert(getParent() && "Not embedded in a function!");
  652. getParent()->remove(this);
  653. return this;
  654. }
  655. /// eraseFromParent - This method unlinks 'this' from the containing function,
  656. /// and deletes it.
  657. void MachineBasicBlock::eraseFromParent() {
  658. assert(getParent() && "Not embedded in a function!");
  659. getParent()->erase(this);
  660. }
  661. /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
  662. /// 'Old', change the code and CFG so that it branches to 'New' instead.
  663. void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
  664. MachineBasicBlock *New) {
  665. assert(Old != New && "Cannot replace self with self!");
  666. MachineBasicBlock::instr_iterator I = instr_end();
  667. while (I != instr_begin()) {
  668. --I;
  669. if (!I->isTerminator()) break;
  670. // Scan the operands of this machine instruction, replacing any uses of Old
  671. // with New.
  672. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  673. if (I->getOperand(i).isMBB() &&
  674. I->getOperand(i).getMBB() == Old)
  675. I->getOperand(i).setMBB(New);
  676. }
  677. // Update the successor information.
  678. replaceSuccessor(Old, New);
  679. }
  680. /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
  681. /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
  682. /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
  683. /// null.
  684. ///
  685. /// Besides DestA and DestB, retain other edges leading to LandingPads
  686. /// (currently there can be only one; we don't check or require that here).
  687. /// Note it is possible that DestA and/or DestB are LandingPads.
  688. bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
  689. MachineBasicBlock *DestB,
  690. bool isCond) {
  691. // The values of DestA and DestB frequently come from a call to the
  692. // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
  693. // values from there.
  694. //
  695. // 1. If both DestA and DestB are null, then the block ends with no branches
  696. // (it falls through to its successor).
  697. // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
  698. // with only an unconditional branch.
  699. // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
  700. // with a conditional branch that falls through to a successor (DestB).
  701. // 4. If DestA and DestB is set and isCond is true, then the block ends with a
  702. // conditional branch followed by an unconditional branch. DestA is the
  703. // 'true' destination and DestB is the 'false' destination.
  704. bool Changed = false;
  705. MachineFunction::iterator FallThru =
  706. llvm::next(MachineFunction::iterator(this));
  707. if (DestA == 0 && DestB == 0) {
  708. // Block falls through to successor.
  709. DestA = FallThru;
  710. DestB = FallThru;
  711. } else if (DestA != 0 && DestB == 0) {
  712. if (isCond)
  713. // Block ends in conditional jump that falls through to successor.
  714. DestB = FallThru;
  715. } else {
  716. assert(DestA && DestB && isCond &&
  717. "CFG in a bad state. Cannot correct CFG edges");
  718. }
  719. // Remove superfluous edges. I.e., those which aren't destinations of this
  720. // basic block, duplicate edges, or landing pads.
  721. SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
  722. MachineBasicBlock::succ_iterator SI = succ_begin();
  723. while (SI != succ_end()) {
  724. const MachineBasicBlock *MBB = *SI;
  725. if (!SeenMBBs.insert(MBB) ||
  726. (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
  727. // This is a superfluous edge, remove it.
  728. SI = removeSuccessor(SI);
  729. Changed = true;
  730. } else {
  731. ++SI;
  732. }
  733. }
  734. return Changed;
  735. }
  736. /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
  737. /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
  738. DebugLoc
  739. MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
  740. DebugLoc DL;
  741. instr_iterator E = instr_end();
  742. if (MBBI == E)
  743. return DL;
  744. // Skip debug declarations, we don't want a DebugLoc from them.
  745. while (MBBI != E && MBBI->isDebugValue())
  746. MBBI++;
  747. if (MBBI != E)
  748. DL = MBBI->getDebugLoc();
  749. return DL;
  750. }
  751. /// getSuccWeight - Return weight of the edge from this block to MBB.
  752. ///
  753. uint32_t MachineBasicBlock::getSuccWeight(MachineBasicBlock *succ) {
  754. if (Weights.empty())
  755. return 0;
  756. succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
  757. return *getWeightIterator(I);
  758. }
  759. /// getWeightIterator - Return wight iterator corresonding to the I successor
  760. /// iterator
  761. MachineBasicBlock::weight_iterator MachineBasicBlock::
  762. getWeightIterator(MachineBasicBlock::succ_iterator I) {
  763. assert(Weights.size() == Successors.size() && "Async weight list!");
  764. size_t index = std::distance(Successors.begin(), I);
  765. assert(index < Weights.size() && "Not a current successor!");
  766. return Weights.begin() + index;
  767. }
  768. void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
  769. bool t) {
  770. OS << "BB#" << MBB->getNumber();
  771. }