MachineBasicBlock.cpp 41 KB

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