MachineBasicBlock.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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. SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
  579. if (Indexes)
  580. Indexes->insertMBBInMaps(NMBB);
  581. // On some targets like Mips, branches may kill virtual registers. Make sure
  582. // that LiveVariables is properly updated after updateTerminator replaces the
  583. // terminators.
  584. LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
  585. // Collect a list of virtual registers killed by the terminators.
  586. SmallVector<unsigned, 4> KilledRegs;
  587. if (LV)
  588. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  589. I != E; ++I) {
  590. MachineInstr *MI = I;
  591. for (MachineInstr::mop_iterator OI = MI->operands_begin(),
  592. OE = MI->operands_end(); OI != OE; ++OI) {
  593. if (!OI->isReg() || OI->getReg() == 0 ||
  594. !OI->isUse() || !OI->isKill() || OI->isUndef())
  595. continue;
  596. unsigned Reg = OI->getReg();
  597. if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
  598. LV->getVarInfo(Reg).removeKill(MI)) {
  599. KilledRegs.push_back(Reg);
  600. DEBUG(dbgs() << "Removing terminator kill: " << *MI);
  601. OI->setIsKill(false);
  602. }
  603. }
  604. }
  605. ReplaceUsesOfBlockWith(Succ, NMBB);
  606. // If updateTerminator() removes instructions, we need to remove them from
  607. // SlotIndexes.
  608. SmallVector<MachineInstr*, 4> Terminators;
  609. if (Indexes) {
  610. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  611. I != E; ++I)
  612. Terminators.push_back(I);
  613. }
  614. updateTerminator();
  615. if (Indexes) {
  616. SmallVector<MachineInstr*, 4> NewTerminators;
  617. for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
  618. I != E; ++I)
  619. NewTerminators.push_back(I);
  620. for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
  621. E = Terminators.end(); I != E; ++I) {
  622. if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
  623. NewTerminators.end())
  624. Indexes->removeMachineInstrFromMaps(*I);
  625. }
  626. }
  627. // Insert unconditional "jump Succ" instruction in NMBB if necessary.
  628. NMBB->addSuccessor(Succ);
  629. if (!NMBB->isLayoutSuccessor(Succ)) {
  630. Cond.clear();
  631. MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
  632. if (Indexes) {
  633. for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
  634. I != E; ++I) {
  635. // Some instructions may have been moved to NMBB by updateTerminator(),
  636. // so we first remove any instruction that already has an index.
  637. if (Indexes->hasIndex(I))
  638. Indexes->removeMachineInstrFromMaps(I);
  639. Indexes->insertMachineInstrInMaps(I);
  640. }
  641. }
  642. }
  643. // Fix PHI nodes in Succ so they refer to NMBB instead of this
  644. for (MachineBasicBlock::instr_iterator
  645. i = Succ->instr_begin(),e = Succ->instr_end();
  646. i != e && i->isPHI(); ++i)
  647. for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
  648. if (i->getOperand(ni+1).getMBB() == this)
  649. i->getOperand(ni+1).setMBB(NMBB);
  650. // Inherit live-ins from the successor
  651. for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
  652. E = Succ->livein_end(); I != E; ++I)
  653. NMBB->addLiveIn(*I);
  654. // Update LiveVariables.
  655. const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
  656. if (LV) {
  657. // Restore kills of virtual registers that were killed by the terminators.
  658. while (!KilledRegs.empty()) {
  659. unsigned Reg = KilledRegs.pop_back_val();
  660. for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
  661. if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
  662. continue;
  663. if (TargetRegisterInfo::isVirtualRegister(Reg))
  664. LV->getVarInfo(Reg).Kills.push_back(I);
  665. DEBUG(dbgs() << "Restored terminator kill: " << *I);
  666. break;
  667. }
  668. }
  669. // Update relevant live-through information.
  670. LV->addNewBlock(NMBB, this, Succ);
  671. }
  672. if (LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>()) {
  673. // After splitting the edge and updating SlotIndexes, live intervals may be
  674. // in one of two situations, depending on whether this block was the last in
  675. // the function. If the original block was the last in the function, all live
  676. // intervals will end prior to the beginning of the new split block. If the
  677. // original block was not at the end of the function, all live intervals will
  678. // extend to the end of the new split block.
  679. bool isLastMBB =
  680. llvm::next(MachineFunction::iterator(NMBB)) == getParent()->end();
  681. SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
  682. SlotIndex PrevIndex = StartIndex.getPrevSlot();
  683. SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
  684. // Find the registers used from NMBB in PHIs in Succ.
  685. SmallSet<unsigned, 8> PHISrcRegs;
  686. for (MachineBasicBlock::instr_iterator
  687. I = Succ->instr_begin(), E = Succ->instr_end();
  688. I != E && I->isPHI(); ++I) {
  689. for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
  690. if (I->getOperand(ni+1).getMBB() == NMBB) {
  691. MachineOperand &MO = I->getOperand(ni);
  692. unsigned Reg = MO.getReg();
  693. PHISrcRegs.insert(Reg);
  694. if (MO.isUndef())
  695. continue;
  696. LiveInterval &LI = LIS->getInterval(Reg);
  697. VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
  698. assert(VNI && "PHI sources should be live out of their predecessors.");
  699. LI.addRange(LiveRange(StartIndex, EndIndex, VNI));
  700. }
  701. }
  702. }
  703. MachineRegisterInfo *MRI = &getParent()->getRegInfo();
  704. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  705. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  706. if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
  707. continue;
  708. LiveInterval &LI = LIS->getInterval(Reg);
  709. if (!LI.liveAt(PrevIndex))
  710. continue;
  711. bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
  712. if (isLiveOut && isLastMBB) {
  713. VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
  714. assert(VNI && "LiveInterval should have VNInfo where it is live.");
  715. LI.addRange(LiveRange(StartIndex, EndIndex, VNI));
  716. } else if (!isLiveOut && !isLastMBB) {
  717. LI.removeRange(StartIndex, EndIndex);
  718. }
  719. }
  720. }
  721. if (MachineDominatorTree *MDT =
  722. P->getAnalysisIfAvailable<MachineDominatorTree>()) {
  723. // Update dominator information.
  724. MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
  725. bool IsNewIDom = true;
  726. for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
  727. PI != E; ++PI) {
  728. MachineBasicBlock *PredBB = *PI;
  729. if (PredBB == NMBB)
  730. continue;
  731. if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
  732. IsNewIDom = false;
  733. break;
  734. }
  735. }
  736. // We know "this" dominates the newly created basic block.
  737. MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
  738. // If all the other predecessors of "Succ" are dominated by "Succ" itself
  739. // then the new block is the new immediate dominator of "Succ". Otherwise,
  740. // the new block doesn't dominate anything.
  741. if (IsNewIDom)
  742. MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
  743. }
  744. if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
  745. if (MachineLoop *TIL = MLI->getLoopFor(this)) {
  746. // If one or the other blocks were not in a loop, the new block is not
  747. // either, and thus LI doesn't need to be updated.
  748. if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
  749. if (TIL == DestLoop) {
  750. // Both in the same loop, the NMBB joins loop.
  751. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  752. } else if (TIL->contains(DestLoop)) {
  753. // Edge from an outer loop to an inner loop. Add to the outer loop.
  754. TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
  755. } else if (DestLoop->contains(TIL)) {
  756. // Edge from an inner loop to an outer loop. Add to the outer loop.
  757. DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
  758. } else {
  759. // Edge from two loops with no containment relation. Because these
  760. // are natural loops, we know that the destination block must be the
  761. // header of its loop (adding a branch into a loop elsewhere would
  762. // create an irreducible loop).
  763. assert(DestLoop->getHeader() == Succ &&
  764. "Should not create irreducible loops!");
  765. if (MachineLoop *P = DestLoop->getParentLoop())
  766. P->addBasicBlockToLoop(NMBB, MLI->getBase());
  767. }
  768. }
  769. }
  770. return NMBB;
  771. }
  772. /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
  773. /// neighboring instructions so the bundle won't be broken by removing MI.
  774. static void unbundleSingleMI(MachineInstr *MI) {
  775. // Removing the first instruction in a bundle.
  776. if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
  777. MI->unbundleFromSucc();
  778. // Removing the last instruction in a bundle.
  779. if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
  780. MI->unbundleFromPred();
  781. // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
  782. // are already fine.
  783. }
  784. MachineBasicBlock::instr_iterator
  785. MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
  786. unbundleSingleMI(I);
  787. return Insts.erase(I);
  788. }
  789. MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
  790. unbundleSingleMI(MI);
  791. MI->clearFlag(MachineInstr::BundledPred);
  792. MI->clearFlag(MachineInstr::BundledSucc);
  793. return Insts.remove(MI);
  794. }
  795. MachineBasicBlock::instr_iterator
  796. MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
  797. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  798. "Cannot insert instruction with bundle flags");
  799. // Set the bundle flags when inserting inside a bundle.
  800. if (I != instr_end() && I->isBundledWithPred()) {
  801. MI->setFlag(MachineInstr::BundledPred);
  802. MI->setFlag(MachineInstr::BundledSucc);
  803. }
  804. return Insts.insert(I, MI);
  805. }
  806. /// removeFromParent - This method unlinks 'this' from the containing function,
  807. /// and returns it, but does not delete it.
  808. MachineBasicBlock *MachineBasicBlock::removeFromParent() {
  809. assert(getParent() && "Not embedded in a function!");
  810. getParent()->remove(this);
  811. return this;
  812. }
  813. /// eraseFromParent - This method unlinks 'this' from the containing function,
  814. /// and deletes it.
  815. void MachineBasicBlock::eraseFromParent() {
  816. assert(getParent() && "Not embedded in a function!");
  817. getParent()->erase(this);
  818. }
  819. /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
  820. /// 'Old', change the code and CFG so that it branches to 'New' instead.
  821. void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
  822. MachineBasicBlock *New) {
  823. assert(Old != New && "Cannot replace self with self!");
  824. MachineBasicBlock::instr_iterator I = instr_end();
  825. while (I != instr_begin()) {
  826. --I;
  827. if (!I->isTerminator()) break;
  828. // Scan the operands of this machine instruction, replacing any uses of Old
  829. // with New.
  830. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  831. if (I->getOperand(i).isMBB() &&
  832. I->getOperand(i).getMBB() == Old)
  833. I->getOperand(i).setMBB(New);
  834. }
  835. // Update the successor information.
  836. replaceSuccessor(Old, New);
  837. }
  838. /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
  839. /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
  840. /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
  841. /// null.
  842. ///
  843. /// Besides DestA and DestB, retain other edges leading to LandingPads
  844. /// (currently there can be only one; we don't check or require that here).
  845. /// Note it is possible that DestA and/or DestB are LandingPads.
  846. bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
  847. MachineBasicBlock *DestB,
  848. bool isCond) {
  849. // The values of DestA and DestB frequently come from a call to the
  850. // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
  851. // values from there.
  852. //
  853. // 1. If both DestA and DestB are null, then the block ends with no branches
  854. // (it falls through to its successor).
  855. // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
  856. // with only an unconditional branch.
  857. // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
  858. // with a conditional branch that falls through to a successor (DestB).
  859. // 4. If DestA and DestB is set and isCond is true, then the block ends with a
  860. // conditional branch followed by an unconditional branch. DestA is the
  861. // 'true' destination and DestB is the 'false' destination.
  862. bool Changed = false;
  863. MachineFunction::iterator FallThru =
  864. llvm::next(MachineFunction::iterator(this));
  865. if (DestA == 0 && DestB == 0) {
  866. // Block falls through to successor.
  867. DestA = FallThru;
  868. DestB = FallThru;
  869. } else if (DestA != 0 && DestB == 0) {
  870. if (isCond)
  871. // Block ends in conditional jump that falls through to successor.
  872. DestB = FallThru;
  873. } else {
  874. assert(DestA && DestB && isCond &&
  875. "CFG in a bad state. Cannot correct CFG edges");
  876. }
  877. // Remove superfluous edges. I.e., those which aren't destinations of this
  878. // basic block, duplicate edges, or landing pads.
  879. SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
  880. MachineBasicBlock::succ_iterator SI = succ_begin();
  881. while (SI != succ_end()) {
  882. const MachineBasicBlock *MBB = *SI;
  883. if (!SeenMBBs.insert(MBB) ||
  884. (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
  885. // This is a superfluous edge, remove it.
  886. SI = removeSuccessor(SI);
  887. Changed = true;
  888. } else {
  889. ++SI;
  890. }
  891. }
  892. return Changed;
  893. }
  894. /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
  895. /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
  896. DebugLoc
  897. MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
  898. DebugLoc DL;
  899. instr_iterator E = instr_end();
  900. if (MBBI == E)
  901. return DL;
  902. // Skip debug declarations, we don't want a DebugLoc from them.
  903. while (MBBI != E && MBBI->isDebugValue())
  904. MBBI++;
  905. if (MBBI != E)
  906. DL = MBBI->getDebugLoc();
  907. return DL;
  908. }
  909. /// getSuccWeight - Return weight of the edge from this block to MBB.
  910. ///
  911. uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
  912. if (Weights.empty())
  913. return 0;
  914. return *getWeightIterator(Succ);
  915. }
  916. /// getWeightIterator - Return wight iterator corresonding to the I successor
  917. /// iterator
  918. MachineBasicBlock::weight_iterator MachineBasicBlock::
  919. getWeightIterator(MachineBasicBlock::succ_iterator I) {
  920. assert(Weights.size() == Successors.size() && "Async weight list!");
  921. size_t index = std::distance(Successors.begin(), I);
  922. assert(index < Weights.size() && "Not a current successor!");
  923. return Weights.begin() + index;
  924. }
  925. /// getWeightIterator - Return wight iterator corresonding to the I successor
  926. /// iterator
  927. MachineBasicBlock::const_weight_iterator MachineBasicBlock::
  928. getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
  929. assert(Weights.size() == Successors.size() && "Async weight list!");
  930. const size_t index = std::distance(Successors.begin(), I);
  931. assert(index < Weights.size() && "Not a current successor!");
  932. return Weights.begin() + index;
  933. }
  934. /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
  935. /// as of just before "MI".
  936. ///
  937. /// Search is localised to a neighborhood of
  938. /// Neighborhood instructions before (searching for defs or kills) and N
  939. /// instructions after (searching just for defs) MI.
  940. MachineBasicBlock::LivenessQueryResult
  941. MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
  942. unsigned Reg, MachineInstr *MI,
  943. unsigned Neighborhood) {
  944. unsigned N = Neighborhood;
  945. MachineBasicBlock *MBB = MI->getParent();
  946. // Start by searching backwards from MI, looking for kills, reads or defs.
  947. MachineBasicBlock::iterator I(MI);
  948. // If this is the first insn in the block, don't search backwards.
  949. if (I != MBB->begin()) {
  950. do {
  951. --I;
  952. MachineOperandIteratorBase::PhysRegInfo Analysis =
  953. MIOperands(I).analyzePhysReg(Reg, TRI);
  954. if (Analysis.Defines)
  955. // Outputs happen after inputs so they take precedence if both are
  956. // present.
  957. return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
  958. if (Analysis.Kills || Analysis.Clobbers)
  959. // Register killed, so isn't live.
  960. return LQR_Dead;
  961. else if (Analysis.ReadsOverlap)
  962. // Defined or read without a previous kill - live.
  963. return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
  964. } while (I != MBB->begin() && --N > 0);
  965. }
  966. // Did we get to the start of the block?
  967. if (I == MBB->begin()) {
  968. // If so, the register's state is definitely defined by the live-in state.
  969. for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
  970. RAI.isValid(); ++RAI) {
  971. if (MBB->isLiveIn(*RAI))
  972. return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
  973. }
  974. return LQR_Dead;
  975. }
  976. N = Neighborhood;
  977. // Try searching forwards from MI, looking for reads or defs.
  978. I = MachineBasicBlock::iterator(MI);
  979. // If this is the last insn in the block, don't search forwards.
  980. if (I != MBB->end()) {
  981. for (++I; I != MBB->end() && N > 0; ++I, --N) {
  982. MachineOperandIteratorBase::PhysRegInfo Analysis =
  983. MIOperands(I).analyzePhysReg(Reg, TRI);
  984. if (Analysis.ReadsOverlap)
  985. // Used, therefore must have been live.
  986. return (Analysis.Reads) ?
  987. LQR_Live : LQR_OverlappingLive;
  988. else if (Analysis.Clobbers || Analysis.Defines)
  989. // Defined (but not read) therefore cannot have been live.
  990. return LQR_Dead;
  991. }
  992. }
  993. // At this point we have no idea of the liveness of the register.
  994. return LQR_Unknown;
  995. }
  996. void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
  997. bool t) {
  998. OS << "BB#" << MBB->getNumber();
  999. }