MachineBasicBlock.cpp 31 KB

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