MachineBasicBlock.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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/ADT/SmallPtrSet.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/Assembly/Writer.h"
  17. #include "llvm/BasicBlock.h"
  18. #include "llvm/CodeGen/LiveVariables.h"
  19. #include "llvm/CodeGen/MachineDominators.h"
  20. #include "llvm/CodeGen/MachineFunction.h"
  21. #include "llvm/CodeGen/MachineLoopInfo.h"
  22. #include "llvm/CodeGen/SlotIndexes.h"
  23. #include "llvm/DataLayout.h"
  24. #include "llvm/MC/MCAsmInfo.h"
  25. #include "llvm/MC/MCContext.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/LeakDetector.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Target/TargetInstrInfo.h"
  30. #include "llvm/Target/TargetMachine.h"
  31. #include "llvm/Target/TargetRegisterInfo.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. if (MachineFunction *MF = N->getParent()->getParent())
  97. N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
  98. N->setParent(0);
  99. LeakDetector::addGarbageObject(N);
  100. }
  101. /// transferNodesFromList (MI) - When moving a range of instructions from one
  102. /// MBB list to another, we need to update the parent pointers and the use/def
  103. /// lists.
  104. void ilist_traits<MachineInstr>::
  105. transferNodesFromList(ilist_traits<MachineInstr> &fromList,
  106. ilist_iterator<MachineInstr> first,
  107. ilist_iterator<MachineInstr> last) {
  108. assert(Parent->getParent() == fromList.Parent->getParent() &&
  109. "MachineInstr parent mismatch!");
  110. // Splice within the same MBB -> no change.
  111. if (Parent == fromList.Parent) return;
  112. // If splicing between two blocks within the same function, just update the
  113. // parent pointers.
  114. for (; first != last; ++first)
  115. first->setParent(Parent);
  116. }
  117. void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
  118. assert(!MI->getParent() && "MI is still in a block!");
  119. Parent->getParent()->DeleteMachineInstr(MI);
  120. }
  121. MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
  122. instr_iterator I = instr_begin(), E = instr_end();
  123. while (I != E && I->isPHI())
  124. ++I;
  125. assert((I == E || !I->isInsideBundle()) &&
  126. "First non-phi MI cannot be inside a bundle!");
  127. return I;
  128. }
  129. MachineBasicBlock::iterator
  130. MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
  131. iterator E = end();
  132. while (I != E && (I->isPHI() || I->isLabel() || I->isDebugValue()))
  133. ++I;
  134. // FIXME: This needs to change if we wish to bundle labels / dbg_values
  135. // inside the bundle.
  136. assert((I == E || !I->isInsideBundle()) &&
  137. "First non-phi / non-label instruction is inside a bundle!");
  138. return I;
  139. }
  140. MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
  141. iterator B = begin(), E = end(), I = E;
  142. while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
  143. ; /*noop */
  144. while (I != E && !I->isTerminator())
  145. ++I;
  146. return I;
  147. }
  148. MachineBasicBlock::const_iterator
  149. MachineBasicBlock::getFirstTerminator() const {
  150. const_iterator B = begin(), E = end(), I = E;
  151. while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
  152. ; /*noop */
  153. while (I != E && !I->isTerminator())
  154. ++I;
  155. return I;
  156. }
  157. MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
  158. instr_iterator B = instr_begin(), E = instr_end(), I = E;
  159. while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
  160. ; /*noop */
  161. while (I != E && !I->isTerminator())
  162. ++I;
  163. return I;
  164. }
  165. MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
  166. // Skip over end-of-block dbg_value instructions.
  167. instr_iterator B = instr_begin(), I = instr_end();
  168. while (I != B) {
  169. --I;
  170. // Return instruction that starts a bundle.
  171. if (I->isDebugValue() || I->isInsideBundle())
  172. continue;
  173. return I;
  174. }
  175. // The block is all debug values.
  176. return end();
  177. }
  178. MachineBasicBlock::const_iterator
  179. MachineBasicBlock::getLastNonDebugInstr() const {
  180. // Skip over end-of-block dbg_value instructions.
  181. const_instr_iterator B = instr_begin(), I = instr_end();
  182. while (I != B) {
  183. --I;
  184. // Return instruction that starts a bundle.
  185. if (I->isDebugValue() || I->isInsideBundle())
  186. continue;
  187. return I;
  188. }
  189. // The block is all debug values.
  190. return end();
  191. }
  192. const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
  193. // A block with a landing pad successor only has one other successor.
  194. if (succ_size() > 2)
  195. return 0;
  196. for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
  197. if ((*I)->isLandingPad())
  198. return *I;
  199. return 0;
  200. }
  201. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  202. void MachineBasicBlock::dump() const {
  203. print(dbgs());
  204. }
  205. #endif
  206. StringRef MachineBasicBlock::getName() const {
  207. if (const BasicBlock *LBB = getBasicBlock())
  208. return LBB->getName();
  209. else
  210. return "(null)";
  211. }
  212. /// Return a hopefully unique identifier for this block.
  213. std::string MachineBasicBlock::getFullName() const {
  214. std::string Name;
  215. if (getParent())
  216. Name = (getParent()->getName() + ":").str();
  217. if (getBasicBlock())
  218. Name += getBasicBlock()->getName();
  219. else
  220. Name += (Twine("BB") + Twine(getNumber())).str();
  221. return Name;
  222. }
  223. void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
  224. const MachineFunction *MF = getParent();
  225. if (!MF) {
  226. OS << "Can't print out MachineBasicBlock because parent MachineFunction"
  227. << " is null\n";
  228. return;
  229. }
  230. if (Indexes)
  231. OS << Indexes->getMBBStartIdx(this) << '\t';
  232. OS << "BB#" << getNumber() << ": ";
  233. const char *Comma = "";
  234. if (const BasicBlock *LBB = getBasicBlock()) {
  235. OS << Comma << "derived from LLVM BB ";
  236. WriteAsOperand(OS, LBB, /*PrintType=*/false);
  237. Comma = ", ";
  238. }
  239. if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
  240. if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
  241. if (Alignment)
  242. OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
  243. << " bytes)";
  244. OS << '\n';
  245. const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
  246. if (!livein_empty()) {
  247. if (Indexes) OS << '\t';
  248. OS << " Live Ins:";
  249. for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
  250. OS << ' ' << PrintReg(*I, TRI);
  251. OS << '\n';
  252. }
  253. // Print the preds of this block according to the CFG.
  254. if (!pred_empty()) {
  255. if (Indexes) OS << '\t';
  256. OS << " Predecessors according to CFG:";
  257. for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
  258. OS << " BB#" << (*PI)->getNumber();
  259. OS << '\n';
  260. }
  261. for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
  262. if (Indexes) {
  263. if (Indexes->hasIndex(I))
  264. OS << Indexes->getInstructionIndex(I);
  265. OS << '\t';
  266. }
  267. OS << '\t';
  268. if (I->isInsideBundle())
  269. OS << " * ";
  270. I->print(OS, &getParent()->getTarget());
  271. }
  272. // Print the successors of this block according to the CFG.
  273. if (!succ_empty()) {
  274. if (Indexes) OS << '\t';
  275. OS << " Successors according to CFG:";
  276. for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
  277. OS << " BB#" << (*SI)->getNumber();
  278. if (!Weights.empty())
  279. OS << '(' << *getWeightIterator(SI) << ')';
  280. }
  281. OS << '\n';
  282. }
  283. }
  284. void MachineBasicBlock::removeLiveIn(unsigned Reg) {
  285. std::vector<unsigned>::iterator I =
  286. std::find(LiveIns.begin(), LiveIns.end(), Reg);
  287. if (I != LiveIns.end())
  288. LiveIns.erase(I);
  289. }
  290. bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
  291. livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
  292. return I != livein_end();
  293. }
  294. void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
  295. getParent()->splice(NewAfter, this);
  296. }
  297. void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
  298. MachineFunction::iterator BBI = NewBefore;
  299. getParent()->splice(++BBI, this);
  300. }
  301. void MachineBasicBlock::updateTerminator() {
  302. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  303. // A block with no successors has no concerns with fall-through edges.
  304. if (this->succ_empty()) return;
  305. MachineBasicBlock *TBB = 0, *FBB = 0;
  306. SmallVector<MachineOperand, 4> Cond;
  307. DebugLoc dl; // FIXME: this is nowhere
  308. bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
  309. (void) B;
  310. assert(!B && "UpdateTerminators requires analyzable predecessors!");
  311. if (Cond.empty()) {
  312. if (TBB) {
  313. // The block has an unconditional branch. If its successor is now
  314. // its layout successor, delete the branch.
  315. if (isLayoutSuccessor(TBB))
  316. TII->RemoveBranch(*this);
  317. } else {
  318. // The block has an unconditional fallthrough. If its successor is not
  319. // its layout successor, insert a branch. First we have to locate the
  320. // only non-landing-pad successor, as that is the fallthrough block.
  321. for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
  322. if ((*SI)->isLandingPad())
  323. continue;
  324. assert(!TBB && "Found more than one non-landing-pad successor!");
  325. TBB = *SI;
  326. }
  327. // If there is no non-landing-pad successor, the block has no
  328. // fall-through edges to be concerned with.
  329. if (!TBB)
  330. return;
  331. // Finally update the unconditional successor to be reached via a branch
  332. // if it would not be reached by fallthrough.
  333. if (!isLayoutSuccessor(TBB))
  334. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  335. }
  336. } else {
  337. if (FBB) {
  338. // The block has a non-fallthrough conditional branch. If one of its
  339. // successors is its layout successor, rewrite it to a fallthrough
  340. // conditional branch.
  341. if (isLayoutSuccessor(TBB)) {
  342. if (TII->ReverseBranchCondition(Cond))
  343. return;
  344. TII->RemoveBranch(*this);
  345. TII->InsertBranch(*this, FBB, 0, Cond, dl);
  346. } else if (isLayoutSuccessor(FBB)) {
  347. TII->RemoveBranch(*this);
  348. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  349. }
  350. } else {
  351. // Walk through the successors and find the successor which is not
  352. // a landing pad and is not the conditional branch destination (in TBB)
  353. // as the fallthrough successor.
  354. MachineBasicBlock *FallthroughBB = 0;
  355. for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
  356. if ((*SI)->isLandingPad() || *SI == TBB)
  357. continue;
  358. assert(!FallthroughBB && "Found more than one fallthrough successor.");
  359. FallthroughBB = *SI;
  360. }
  361. if (!FallthroughBB && canFallThrough()) {
  362. // We fallthrough to the same basic block as the conditional jump
  363. // targets. Remove the conditional jump, leaving unconditional
  364. // fallthrough.
  365. // FIXME: This does not seem like a reasonable pattern to support, but it
  366. // has been seen in the wild coming out of degenerate ARM test cases.
  367. TII->RemoveBranch(*this);
  368. // Finally update the unconditional successor to be reached via a branch
  369. // if it would not be reached by fallthrough.
  370. if (!isLayoutSuccessor(TBB))
  371. TII->InsertBranch(*this, TBB, 0, Cond, dl);
  372. return;
  373. }
  374. // The block has a fallthrough conditional branch.
  375. if (isLayoutSuccessor(TBB)) {
  376. if (TII->ReverseBranchCondition(Cond)) {
  377. // We can't reverse the condition, add an unconditional branch.
  378. Cond.clear();
  379. TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
  380. return;
  381. }
  382. TII->RemoveBranch(*this);
  383. TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
  384. } else if (!isLayoutSuccessor(FallthroughBB)) {
  385. TII->RemoveBranch(*this);
  386. TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
  387. }
  388. }
  389. }
  390. }
  391. void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
  392. // If we see non-zero value for the first time it means we actually use Weight
  393. // list, so we fill all Weights with 0's.
  394. if (weight != 0 && Weights.empty())
  395. Weights.resize(Successors.size());
  396. if (weight != 0 || !Weights.empty())
  397. Weights.push_back(weight);
  398. Successors.push_back(succ);
  399. succ->addPredecessor(this);
  400. }
  401. void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
  402. succ->removePredecessor(this);
  403. succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
  404. assert(I != Successors.end() && "Not a current successor!");
  405. // If Weight list is empty it means we don't use it (disabled optimization).
  406. if (!Weights.empty()) {
  407. weight_iterator WI = getWeightIterator(I);
  408. Weights.erase(WI);
  409. }
  410. Successors.erase(I);
  411. }
  412. MachineBasicBlock::succ_iterator
  413. MachineBasicBlock::removeSuccessor(succ_iterator I) {
  414. assert(I != Successors.end() && "Not a current successor!");
  415. // If Weight list is empty it means we don't use it (disabled optimization).
  416. if (!Weights.empty()) {
  417. weight_iterator WI = getWeightIterator(I);
  418. Weights.erase(WI);
  419. }
  420. (*I)->removePredecessor(this);
  421. return Successors.erase(I);
  422. }
  423. void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
  424. MachineBasicBlock *New) {
  425. if (Old == New)
  426. return;
  427. succ_iterator E = succ_end();
  428. succ_iterator NewI = E;
  429. succ_iterator OldI = E;
  430. for (succ_iterator I = succ_begin(); I != E; ++I) {
  431. if (*I == Old) {
  432. OldI = I;
  433. if (NewI != E)
  434. break;
  435. }
  436. if (*I == New) {
  437. NewI = I;
  438. if (OldI != E)
  439. break;
  440. }
  441. }
  442. assert(OldI != E && "Old is not a successor of this block");
  443. Old->removePredecessor(this);
  444. // If New isn't already a successor, let it take Old's place.
  445. if (NewI == E) {
  446. New->addPredecessor(this);
  447. *OldI = New;
  448. return;
  449. }
  450. // New is already a successor.
  451. // Update its weight instead of adding a duplicate edge.
  452. if (!Weights.empty()) {
  453. weight_iterator OldWI = getWeightIterator(OldI);
  454. *getWeightIterator(NewI) += *OldWI;
  455. Weights.erase(OldWI);
  456. }
  457. Successors.erase(OldI);
  458. }
  459. void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
  460. Predecessors.push_back(pred);
  461. }
  462. void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
  463. pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
  464. assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
  465. Predecessors.erase(I);
  466. }
  467. void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
  468. if (this == fromMBB)
  469. return;
  470. while (!fromMBB->succ_empty()) {
  471. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  472. uint32_t Weight = 0;
  473. // If Weight list is empty it means we don't use it (disabled optimization).
  474. if (!fromMBB->Weights.empty())
  475. Weight = *fromMBB->Weights.begin();
  476. addSuccessor(Succ, Weight);
  477. fromMBB->removeSuccessor(Succ);
  478. }
  479. }
  480. void
  481. MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
  482. if (this == fromMBB)
  483. return;
  484. while (!fromMBB->succ_empty()) {
  485. MachineBasicBlock *Succ = *fromMBB->succ_begin();
  486. uint32_t Weight = 0;
  487. if (!fromMBB->Weights.empty())
  488. Weight = *fromMBB->Weights.begin();
  489. addSuccessor(Succ, Weight);
  490. fromMBB->removeSuccessor(Succ);
  491. // Fix up any PHI nodes in the successor.
  492. for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
  493. ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
  494. for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
  495. MachineOperand &MO = MI->getOperand(i);
  496. if (MO.getMBB() == fromMBB)
  497. MO.setMBB(this);
  498. }
  499. }
  500. }
  501. bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
  502. return std::find(pred_begin(), pred_end(), MBB) != pred_end();
  503. }
  504. bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
  505. return std::find(succ_begin(), succ_end(), MBB) != succ_end();
  506. }
  507. bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
  508. MachineFunction::const_iterator I(this);
  509. return llvm::next(I) == MachineFunction::const_iterator(MBB);
  510. }
  511. bool MachineBasicBlock::canFallThrough() {
  512. MachineFunction::iterator Fallthrough = this;
  513. ++Fallthrough;
  514. // If FallthroughBlock is off the end of the function, it can't fall through.
  515. if (Fallthrough == getParent()->end())
  516. return false;
  517. // If FallthroughBlock isn't a successor, no fallthrough is possible.
  518. if (!isSuccessor(Fallthrough))
  519. return false;
  520. // Analyze the branches, if any, at the end of the block.
  521. MachineBasicBlock *TBB = 0, *FBB = 0;
  522. SmallVector<MachineOperand, 4> Cond;
  523. const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
  524. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
  525. // If we couldn't analyze the branch, examine the last instruction.
  526. // If the block doesn't end in a known control barrier, assume fallthrough
  527. // is possible. The isPredicated check is needed because this code can be
  528. // called during IfConversion, where an instruction which is normally a
  529. // Barrier is predicated and thus no longer an actual control barrier.
  530. return empty() || !back().isBarrier() || TII->isPredicated(&back());
  531. }
  532. // If there is no branch, control always falls through.
  533. if (TBB == 0) return true;
  534. // If there is some explicit branch to the fallthrough block, it can obviously
  535. // reach, even though the branch should get folded to fall through implicitly.
  536. if (MachineFunction::iterator(TBB) == Fallthrough ||
  537. MachineFunction::iterator(FBB) == Fallthrough)
  538. return true;
  539. // If it's an unconditional branch to some block not the fall through, it
  540. // doesn't fall through.
  541. if (Cond.empty()) return false;
  542. // Otherwise, if it is conditional and has no explicit false block, it falls
  543. // through.
  544. return FBB == 0;
  545. }
  546. MachineBasicBlock *
  547. MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
  548. // Splitting the critical edge to a landing pad block is non-trivial. Don't do
  549. // it in this generic function.
  550. if (Succ->isLandingPad())
  551. return NULL;
  552. MachineFunction *MF = getParent();
  553. DebugLoc dl; // FIXME: this is nowhere
  554. // We may need to update this's terminator, but we can't do that if
  555. // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
  556. const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
  557. MachineBasicBlock *TBB = 0, *FBB = 0;
  558. SmallVector<MachineOperand, 4> Cond;
  559. if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
  560. return NULL;
  561. // Avoid bugpoint weirdness: A block may end with a conditional branch but
  562. // jumps to the same MBB is either case. We have duplicate CFG edges in that
  563. // case that we can't handle. Since this never happens in properly optimized
  564. // code, just skip those edges.
  565. if (TBB && TBB == FBB) {
  566. DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
  567. << getNumber() << '\n');
  568. return NULL;
  569. }
  570. MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
  571. MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
  572. DEBUG(dbgs() << "Splitting critical edge:"
  573. " BB#" << getNumber()
  574. << " -- BB#" << NMBB->getNumber()
  575. << " -- BB#" << Succ->getNumber() << '\n');
  576. // On some targets like Mips, branches may kill virtual registers. Make sure
  577. // that LiveVariables is properly updated after updateTerminator replaces the
  578. // terminators.
  579. LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
  580. // Collect a list of virtual registers killed by the terminators.
  581. SmallVector<unsigned, 4> KilledRegs;
  582. if (LV)
  583. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  584. I != E; ++I) {
  585. MachineInstr *MI = I;
  586. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  587. OE = MI->operands_end(); OI != OE; ++OI) {
  588. if (!OI->isReg() || OI->getReg() == 0 ||
  589. !OI->isUse() || !OI->isKill() || OI->isUndef())
  590. continue;
  591. unsigned Reg = OI->getReg();
  592. if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
  593. LV->getVarInfo(Reg).removeKill(MI)) {
  594. KilledRegs.push_back(Reg);
  595. DEBUG(dbgs() << "Removing terminator kill: " << *MI);
  596. OI->setIsKill(false);
  597. }
  598. }
  599. }
  600. ReplaceUsesOfBlockWith(Succ, NMBB);
  601. updateTerminator();
  602. // Insert unconditional "jump Succ" instruction in NMBB if necessary.
  603. NMBB->addSuccessor(Succ);
  604. if (!NMBB->isLayoutSuccessor(Succ)) {
  605. Cond.clear();
  606. MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
  607. }
  608. // Fix PHI nodes in Succ so they refer to NMBB instead of this
  609. for (MachineBasicBlock::instr_iterator
  610. i = Succ->instr_begin(),e = Succ->instr_end();
  611. i != e && i->isPHI(); ++i)
  612. for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
  613. if (i->getOperand(ni+1).getMBB() == this)
  614. i->getOperand(ni+1).setMBB(NMBB);
  615. // Inherit live-ins from the successor
  616. for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
  617. E = Succ->livein_end(); I != E; ++I)
  618. NMBB->addLiveIn(*I);
  619. // Update LiveVariables.
  620. const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
  621. if (LV) {
  622. // Restore kills of virtual registers that were killed by the terminators.
  623. while (!KilledRegs.empty()) {
  624. unsigned Reg = KilledRegs.pop_back_val();
  625. for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
  626. if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
  627. continue;
  628. if (TargetRegisterInfo::isVirtualRegister(Reg))
  629. LV->getVarInfo(Reg).Kills.push_back(I);
  630. DEBUG(dbgs() << "Restored terminator kill: " << *I);
  631. break;
  632. }
  633. }
  634. // Update relevant live-through information.
  635. LV->addNewBlock(NMBB, this, Succ);
  636. }
  637. if (MachineDominatorTree *MDT =
  638. P->getAnalysisIfAvailable<MachineDominatorTree>()) {
  639. // Update dominator information.
  640. MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
  641. bool IsNewIDom = true;
  642. for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
  643. PI != E; ++PI) {
  644. MachineBasicBlock *PredBB = *PI;
  645. if (PredBB == NMBB)
  646. continue;
  647. if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
  648. IsNewIDom = false;
  649. break;
  650. }
  651. }
  652. // We know "this" dominates the newly created basic block.
  653. MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
  654. // If all the other predecessors of "Succ" are dominated by "Succ" itself
  655. // then the new block is the new immediate dominator of "Succ". Otherwise,
  656. // the new block doesn't dominate anything.
  657. if (IsNewIDom)
  658. MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
  659. }
  660. if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
  661. if (MachineLoop *TIL = MLI->getLoopFor(this)) {
  662. // If one or the other blocks were not in a loop, the new block is not
  663. // either, and thus LI doesn't need to be updated.
  664. if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
  665. if (TIL == DestLoop) {
  666. // Both in the same loop, the NMBB joins loop.
  667. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  668. } else if (TIL->contains(DestLoop)) {
  669. // Edge from an outer loop to an inner loop. Add to the outer loop.
  670. TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
  671. } else if (DestLoop->contains(TIL)) {
  672. // Edge from an inner loop to an outer loop. Add to the outer loop.
  673. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  674. } else {
  675. // Edge from two loops with no containment relation. Because these
  676. // are natural loops, we know that the destination block must be the
  677. // header of its loop (adding a branch into a loop elsewhere would
  678. // create an irreducible loop).
  679. assert(DestLoop->getHeader() == Succ &&
  680. "Should not create irreducible loops!");
  681. if (MachineLoop *P = DestLoop->getParentLoop())
  682. P->addBasicBlockToLoop(NMBB, MLI->getBase());
  683. }
  684. }
  685. }
  686. return NMBB;
  687. }
  688. /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
  689. /// neighboring instructions so the bundle won't be broken by removing MI.
  690. static void unbundleSingleMI(MachineInstr *MI) {
  691. // Removing the first instruction in a bundle.
  692. if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
  693. MI->unbundleFromSucc();
  694. // Removing the last instruction in a bundle.
  695. if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
  696. MI->unbundleFromPred();
  697. // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
  698. // are already fine.
  699. }
  700. MachineBasicBlock::instr_iterator
  701. MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
  702. unbundleSingleMI(I);
  703. return Insts.erase(I);
  704. }
  705. MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
  706. unbundleSingleMI(MI);
  707. MI->clearFlag(MachineInstr::BundledPred);
  708. MI->clearFlag(MachineInstr::BundledSucc);
  709. return Insts.remove(MI);
  710. }
  711. MachineBasicBlock::instr_iterator
  712. MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
  713. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  714. "Cannot insert instruction with bundle flags");
  715. // Set the bundle flags when inserting inside a bundle.
  716. if (I != instr_end() && I->isBundledWithPred()) {
  717. MI->setFlag(MachineInstr::BundledPred);
  718. MI->setFlag(MachineInstr::BundledSucc);
  719. }
  720. return Insts.insert(I, MI);
  721. }
  722. void MachineBasicBlock::splice(MachineBasicBlock::iterator where,
  723. MachineBasicBlock *Other,
  724. MachineBasicBlock::iterator From) {
  725. if (From->isBundle()) {
  726. MachineBasicBlock::iterator To = llvm::next(From);
  727. Insts.splice(where.getInstrIterator(), Other->Insts,
  728. From.getInstrIterator(), To.getInstrIterator());
  729. return;
  730. }
  731. Insts.splice(where.getInstrIterator(), Other->Insts, From.getInstrIterator());
  732. }
  733. /// removeFromParent - This method unlinks 'this' from the containing function,
  734. /// and returns it, but does not delete it.
  735. MachineBasicBlock *MachineBasicBlock::removeFromParent() {
  736. assert(getParent() && "Not embedded in a function!");
  737. getParent()->remove(this);
  738. return this;
  739. }
  740. /// eraseFromParent - This method unlinks 'this' from the containing function,
  741. /// and deletes it.
  742. void MachineBasicBlock::eraseFromParent() {
  743. assert(getParent() && "Not embedded in a function!");
  744. getParent()->erase(this);
  745. }
  746. /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
  747. /// 'Old', change the code and CFG so that it branches to 'New' instead.
  748. void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
  749. MachineBasicBlock *New) {
  750. assert(Old != New && "Cannot replace self with self!");
  751. MachineBasicBlock::instr_iterator I = instr_end();
  752. while (I != instr_begin()) {
  753. --I;
  754. if (!I->isTerminator()) break;
  755. // Scan the operands of this machine instruction, replacing any uses of Old
  756. // with New.
  757. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  758. if (I->getOperand(i).isMBB() &&
  759. I->getOperand(i).getMBB() == Old)
  760. I->getOperand(i).setMBB(New);
  761. }
  762. // Update the successor information.
  763. replaceSuccessor(Old, New);
  764. }
  765. /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
  766. /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
  767. /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
  768. /// null.
  769. ///
  770. /// Besides DestA and DestB, retain other edges leading to LandingPads
  771. /// (currently there can be only one; we don't check or require that here).
  772. /// Note it is possible that DestA and/or DestB are LandingPads.
  773. bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
  774. MachineBasicBlock *DestB,
  775. bool isCond) {
  776. // The values of DestA and DestB frequently come from a call to the
  777. // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
  778. // values from there.
  779. //
  780. // 1. If both DestA and DestB are null, then the block ends with no branches
  781. // (it falls through to its successor).
  782. // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
  783. // with only an unconditional branch.
  784. // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
  785. // with a conditional branch that falls through to a successor (DestB).
  786. // 4. If DestA and DestB is set and isCond is true, then the block ends with a
  787. // conditional branch followed by an unconditional branch. DestA is the
  788. // 'true' destination and DestB is the 'false' destination.
  789. bool Changed = false;
  790. MachineFunction::iterator FallThru =
  791. llvm::next(MachineFunction::iterator(this));
  792. if (DestA == 0 && DestB == 0) {
  793. // Block falls through to successor.
  794. DestA = FallThru;
  795. DestB = FallThru;
  796. } else if (DestA != 0 && DestB == 0) {
  797. if (isCond)
  798. // Block ends in conditional jump that falls through to successor.
  799. DestB = FallThru;
  800. } else {
  801. assert(DestA && DestB && isCond &&
  802. "CFG in a bad state. Cannot correct CFG edges");
  803. }
  804. // Remove superfluous edges. I.e., those which aren't destinations of this
  805. // basic block, duplicate edges, or landing pads.
  806. SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
  807. MachineBasicBlock::succ_iterator SI = succ_begin();
  808. while (SI != succ_end()) {
  809. const MachineBasicBlock *MBB = *SI;
  810. if (!SeenMBBs.insert(MBB) ||
  811. (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
  812. // This is a superfluous edge, remove it.
  813. SI = removeSuccessor(SI);
  814. Changed = true;
  815. } else {
  816. ++SI;
  817. }
  818. }
  819. return Changed;
  820. }
  821. /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
  822. /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
  823. DebugLoc
  824. MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
  825. DebugLoc DL;
  826. instr_iterator E = instr_end();
  827. if (MBBI == E)
  828. return DL;
  829. // Skip debug declarations, we don't want a DebugLoc from them.
  830. while (MBBI != E && MBBI->isDebugValue())
  831. MBBI++;
  832. if (MBBI != E)
  833. DL = MBBI->getDebugLoc();
  834. return DL;
  835. }
  836. /// getSuccWeight - Return weight of the edge from this block to MBB.
  837. ///
  838. uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
  839. if (Weights.empty())
  840. return 0;
  841. return *getWeightIterator(Succ);
  842. }
  843. /// getWeightIterator - Return wight iterator corresonding to the I successor
  844. /// iterator
  845. MachineBasicBlock::weight_iterator MachineBasicBlock::
  846. getWeightIterator(MachineBasicBlock::succ_iterator I) {
  847. assert(Weights.size() == Successors.size() && "Async weight list!");
  848. size_t index = std::distance(Successors.begin(), I);
  849. assert(index < Weights.size() && "Not a current successor!");
  850. return Weights.begin() + index;
  851. }
  852. /// getWeightIterator - Return wight iterator corresonding to the I successor
  853. /// iterator
  854. MachineBasicBlock::const_weight_iterator MachineBasicBlock::
  855. getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
  856. assert(Weights.size() == Successors.size() && "Async weight list!");
  857. const size_t index = std::distance(Successors.begin(), I);
  858. assert(index < Weights.size() && "Not a current successor!");
  859. return Weights.begin() + index;
  860. }
  861. /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
  862. /// as of just before "MI".
  863. ///
  864. /// Search is localised to a neighborhood of
  865. /// Neighborhood instructions before (searching for defs or kills) and N
  866. /// instructions after (searching just for defs) MI.
  867. MachineBasicBlock::LivenessQueryResult
  868. MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
  869. unsigned Reg, MachineInstr *MI,
  870. unsigned Neighborhood) {
  871. unsigned N = Neighborhood;
  872. MachineBasicBlock *MBB = MI->getParent();
  873. // Start by searching backwards from MI, looking for kills, reads or defs.
  874. MachineBasicBlock::iterator I(MI);
  875. // If this is the first insn in the block, don't search backwards.
  876. if (I != MBB->begin()) {
  877. do {
  878. --I;
  879. MachineOperandIteratorBase::PhysRegInfo Analysis =
  880. MIOperands(I).analyzePhysReg(Reg, TRI);
  881. if (Analysis.Defines)
  882. // Outputs happen after inputs so they take precedence if both are
  883. // present.
  884. return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
  885. if (Analysis.Kills || Analysis.Clobbers)
  886. // Register killed, so isn't live.
  887. return LQR_Dead;
  888. else if (Analysis.ReadsOverlap)
  889. // Defined or read without a previous kill - live.
  890. return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
  891. } while (I != MBB->begin() && --N > 0);
  892. }
  893. // Did we get to the start of the block?
  894. if (I == MBB->begin()) {
  895. // If so, the register's state is definitely defined by the live-in state.
  896. for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
  897. RAI.isValid(); ++RAI) {
  898. if (MBB->isLiveIn(*RAI))
  899. return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
  900. }
  901. return LQR_Dead;
  902. }
  903. N = Neighborhood;
  904. // Try searching forwards from MI, looking for reads or defs.
  905. I = MachineBasicBlock::iterator(MI);
  906. // If this is the last insn in the block, don't search forwards.
  907. if (I != MBB->end()) {
  908. for (++I; I != MBB->end() && N > 0; ++I, --N) {
  909. MachineOperandIteratorBase::PhysRegInfo Analysis =
  910. MIOperands(I).analyzePhysReg(Reg, TRI);
  911. if (Analysis.ReadsOverlap)
  912. // Used, therefore must have been live.
  913. return (Analysis.Reads) ?
  914. LQR_Live : LQR_OverlappingLive;
  915. else if (Analysis.Clobbers || Analysis.Defines)
  916. // Defined (but not read) therefore cannot have been live.
  917. return LQR_Dead;
  918. }
  919. }
  920. // At this point we have no idea of the liveness of the register.
  921. return LQR_Unknown;
  922. }
  923. void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
  924. bool t) {
  925. OS << "BB#" << MBB->getNumber();
  926. }