MachineBasicBlock.cpp 42 KB

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