IfConversion.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  1. //===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
  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. // This file implements the machine instruction level if-conversion pass.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #define DEBUG_TYPE "ifcvt"
  14. #include "BranchFolding.h"
  15. #include "llvm/Function.h"
  16. #include "llvm/CodeGen/Passes.h"
  17. #include "llvm/CodeGen/MachineModuleInfo.h"
  18. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  19. #include "llvm/CodeGen/MachineFunctionPass.h"
  20. #include "llvm/MC/MCInstrItineraries.h"
  21. #include "llvm/Target/TargetInstrInfo.h"
  22. #include "llvm/Target/TargetLowering.h"
  23. #include "llvm/Target/TargetMachine.h"
  24. #include "llvm/Target/TargetRegisterInfo.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/ADT/SmallSet.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include "llvm/ADT/STLExtras.h"
  32. using namespace llvm;
  33. // Hidden options for help debugging.
  34. static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
  35. static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
  36. static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
  37. static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
  38. cl::init(false), cl::Hidden);
  39. static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
  40. cl::init(false), cl::Hidden);
  41. static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
  42. cl::init(false), cl::Hidden);
  43. static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
  44. cl::init(false), cl::Hidden);
  45. static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
  46. cl::init(false), cl::Hidden);
  47. static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
  48. cl::init(false), cl::Hidden);
  49. static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
  50. cl::init(false), cl::Hidden);
  51. static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
  52. cl::init(true), cl::Hidden);
  53. STATISTIC(NumSimple, "Number of simple if-conversions performed");
  54. STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
  55. STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
  56. STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
  57. STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
  58. STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
  59. STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
  60. STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
  61. STATISTIC(NumDupBBs, "Number of duplicated blocks");
  62. STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
  63. namespace {
  64. class IfConverter : public MachineFunctionPass {
  65. enum IfcvtKind {
  66. ICNotClassfied, // BB data valid, but not classified.
  67. ICSimpleFalse, // Same as ICSimple, but on the false path.
  68. ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
  69. ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
  70. ICTriangleRev, // Same as ICTriangle, but true path rev condition.
  71. ICTriangleFalse, // Same as ICTriangle, but on the false path.
  72. ICTriangle, // BB is entry of a triangle sub-CFG.
  73. ICDiamond // BB is entry of a diamond sub-CFG.
  74. };
  75. /// BBInfo - One per MachineBasicBlock, this is used to cache the result
  76. /// if-conversion feasibility analysis. This includes results from
  77. /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
  78. /// classification, and common tail block of its successors (if it's a
  79. /// diamond shape), its size, whether it's predicable, and whether any
  80. /// instruction can clobber the 'would-be' predicate.
  81. ///
  82. /// IsDone - True if BB is not to be considered for ifcvt.
  83. /// IsBeingAnalyzed - True if BB is currently being analyzed.
  84. /// IsAnalyzed - True if BB has been analyzed (info is still valid).
  85. /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
  86. /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
  87. /// HasFallThrough - True if BB may fallthrough to the following BB.
  88. /// IsUnpredicable - True if BB is known to be unpredicable.
  89. /// ClobbersPred - True if BB could modify predicates (e.g. has
  90. /// cmp, call, etc.)
  91. /// NonPredSize - Number of non-predicated instructions.
  92. /// ExtraCost - Extra cost for multi-cycle instructions.
  93. /// ExtraCost2 - Some instructions are slower when predicated
  94. /// BB - Corresponding MachineBasicBlock.
  95. /// TrueBB / FalseBB- See AnalyzeBranch().
  96. /// BrCond - Conditions for end of block conditional branches.
  97. /// Predicate - Predicate used in the BB.
  98. struct BBInfo {
  99. bool IsDone : 1;
  100. bool IsBeingAnalyzed : 1;
  101. bool IsAnalyzed : 1;
  102. bool IsEnqueued : 1;
  103. bool IsBrAnalyzable : 1;
  104. bool HasFallThrough : 1;
  105. bool IsUnpredicable : 1;
  106. bool CannotBeCopied : 1;
  107. bool ClobbersPred : 1;
  108. unsigned NonPredSize;
  109. unsigned ExtraCost;
  110. unsigned ExtraCost2;
  111. MachineBasicBlock *BB;
  112. MachineBasicBlock *TrueBB;
  113. MachineBasicBlock *FalseBB;
  114. SmallVector<MachineOperand, 4> BrCond;
  115. SmallVector<MachineOperand, 4> Predicate;
  116. BBInfo() : IsDone(false), IsBeingAnalyzed(false),
  117. IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
  118. HasFallThrough(false), IsUnpredicable(false),
  119. CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
  120. ExtraCost(0), ExtraCost2(0), BB(0), TrueBB(0), FalseBB(0) {}
  121. };
  122. /// IfcvtToken - Record information about pending if-conversions to attempt:
  123. /// BBI - Corresponding BBInfo.
  124. /// Kind - Type of block. See IfcvtKind.
  125. /// NeedSubsumption - True if the to-be-predicated BB has already been
  126. /// predicated.
  127. /// NumDups - Number of instructions that would be duplicated due
  128. /// to this if-conversion. (For diamonds, the number of
  129. /// identical instructions at the beginnings of both
  130. /// paths).
  131. /// NumDups2 - For diamonds, the number of identical instructions
  132. /// at the ends of both paths.
  133. struct IfcvtToken {
  134. BBInfo &BBI;
  135. IfcvtKind Kind;
  136. bool NeedSubsumption;
  137. unsigned NumDups;
  138. unsigned NumDups2;
  139. IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
  140. : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
  141. };
  142. /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
  143. /// basic block number.
  144. std::vector<BBInfo> BBAnalysis;
  145. const TargetLowering *TLI;
  146. const TargetInstrInfo *TII;
  147. const TargetRegisterInfo *TRI;
  148. const InstrItineraryData *InstrItins;
  149. const MachineBranchProbabilityInfo *MBPI;
  150. bool MadeChange;
  151. int FnNum;
  152. public:
  153. static char ID;
  154. IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
  155. initializeIfConverterPass(*PassRegistry::getPassRegistry());
  156. }
  157. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  158. AU.addRequired<MachineBranchProbabilityInfo>();
  159. MachineFunctionPass::getAnalysisUsage(AU);
  160. }
  161. virtual bool runOnMachineFunction(MachineFunction &MF);
  162. private:
  163. bool ReverseBranchCondition(BBInfo &BBI);
  164. bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
  165. const BranchProbability &Prediction) const;
  166. bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
  167. bool FalseBranch, unsigned &Dups,
  168. const BranchProbability &Prediction) const;
  169. bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
  170. unsigned &Dups1, unsigned &Dups2) const;
  171. void ScanInstructions(BBInfo &BBI);
  172. BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
  173. std::vector<IfcvtToken*> &Tokens);
  174. bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
  175. bool isTriangle = false, bool RevBranch = false);
  176. void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
  177. void InvalidatePreds(MachineBasicBlock *BB);
  178. void RemoveExtraEdges(BBInfo &BBI);
  179. bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
  180. bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
  181. bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
  182. unsigned NumDups1, unsigned NumDups2);
  183. void PredicateBlock(BBInfo &BBI,
  184. MachineBasicBlock::iterator E,
  185. SmallVectorImpl<MachineOperand> &Cond,
  186. SmallSet<unsigned, 4> &Redefs,
  187. SmallSet<unsigned, 4> *LaterRedefs = 0);
  188. void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
  189. SmallVectorImpl<MachineOperand> &Cond,
  190. SmallSet<unsigned, 4> &Redefs,
  191. bool IgnoreBr = false);
  192. void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
  193. bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
  194. unsigned Cycle, unsigned Extra,
  195. const BranchProbability &Prediction) const {
  196. return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
  197. Prediction);
  198. }
  199. bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
  200. unsigned TCycle, unsigned TExtra,
  201. MachineBasicBlock &FBB,
  202. unsigned FCycle, unsigned FExtra,
  203. const BranchProbability &Prediction) const {
  204. return TCycle > 0 && FCycle > 0 &&
  205. TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
  206. Prediction);
  207. }
  208. // blockAlwaysFallThrough - Block ends without a terminator.
  209. bool blockAlwaysFallThrough(BBInfo &BBI) const {
  210. return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
  211. }
  212. // IfcvtTokenCmp - Used to sort if-conversion candidates.
  213. static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
  214. int Incr1 = (C1->Kind == ICDiamond)
  215. ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
  216. int Incr2 = (C2->Kind == ICDiamond)
  217. ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
  218. if (Incr1 > Incr2)
  219. return true;
  220. else if (Incr1 == Incr2) {
  221. // Favors subsumption.
  222. if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
  223. return true;
  224. else if (C1->NeedSubsumption == C2->NeedSubsumption) {
  225. // Favors diamond over triangle, etc.
  226. if ((unsigned)C1->Kind < (unsigned)C2->Kind)
  227. return true;
  228. else if (C1->Kind == C2->Kind)
  229. return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
  230. }
  231. }
  232. return false;
  233. }
  234. };
  235. char IfConverter::ID = 0;
  236. }
  237. char &llvm::IfConverterID = IfConverter::ID;
  238. INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
  239. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  240. INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
  241. bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
  242. TLI = MF.getTarget().getTargetLowering();
  243. TII = MF.getTarget().getInstrInfo();
  244. TRI = MF.getTarget().getRegisterInfo();
  245. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  246. InstrItins = MF.getTarget().getInstrItineraryData();
  247. if (!TII) return false;
  248. // Tail merge tend to expose more if-conversion opportunities.
  249. BranchFolder BF(true, false);
  250. bool BFChange = BF.OptimizeFunction(MF, TII,
  251. MF.getTarget().getRegisterInfo(),
  252. getAnalysisIfAvailable<MachineModuleInfo>());
  253. DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
  254. << MF.getFunction()->getName() << "\'");
  255. if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
  256. DEBUG(dbgs() << " skipped\n");
  257. return false;
  258. }
  259. DEBUG(dbgs() << "\n");
  260. MF.RenumberBlocks();
  261. BBAnalysis.resize(MF.getNumBlockIDs());
  262. std::vector<IfcvtToken*> Tokens;
  263. MadeChange = false;
  264. unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
  265. NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
  266. while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
  267. // Do an initial analysis for each basic block and find all the potential
  268. // candidates to perform if-conversion.
  269. bool Change = false;
  270. AnalyzeBlocks(MF, Tokens);
  271. while (!Tokens.empty()) {
  272. IfcvtToken *Token = Tokens.back();
  273. Tokens.pop_back();
  274. BBInfo &BBI = Token->BBI;
  275. IfcvtKind Kind = Token->Kind;
  276. unsigned NumDups = Token->NumDups;
  277. unsigned NumDups2 = Token->NumDups2;
  278. delete Token;
  279. // If the block has been evicted out of the queue or it has already been
  280. // marked dead (due to it being predicated), then skip it.
  281. if (BBI.IsDone)
  282. BBI.IsEnqueued = false;
  283. if (!BBI.IsEnqueued)
  284. continue;
  285. BBI.IsEnqueued = false;
  286. bool RetVal = false;
  287. switch (Kind) {
  288. default: llvm_unreachable("Unexpected!");
  289. case ICSimple:
  290. case ICSimpleFalse: {
  291. bool isFalse = Kind == ICSimpleFalse;
  292. if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
  293. DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
  294. " false" : "")
  295. << "): BB#" << BBI.BB->getNumber() << " ("
  296. << ((Kind == ICSimpleFalse)
  297. ? BBI.FalseBB->getNumber()
  298. : BBI.TrueBB->getNumber()) << ") ");
  299. RetVal = IfConvertSimple(BBI, Kind);
  300. DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  301. if (RetVal) {
  302. if (isFalse) ++NumSimpleFalse;
  303. else ++NumSimple;
  304. }
  305. break;
  306. }
  307. case ICTriangle:
  308. case ICTriangleRev:
  309. case ICTriangleFalse:
  310. case ICTriangleFRev: {
  311. bool isFalse = Kind == ICTriangleFalse;
  312. bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
  313. if (DisableTriangle && !isFalse && !isRev) break;
  314. if (DisableTriangleR && !isFalse && isRev) break;
  315. if (DisableTriangleF && isFalse && !isRev) break;
  316. if (DisableTriangleFR && isFalse && isRev) break;
  317. DEBUG(dbgs() << "Ifcvt (Triangle");
  318. if (isFalse)
  319. DEBUG(dbgs() << " false");
  320. if (isRev)
  321. DEBUG(dbgs() << " rev");
  322. DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
  323. << BBI.TrueBB->getNumber() << ",F:"
  324. << BBI.FalseBB->getNumber() << ") ");
  325. RetVal = IfConvertTriangle(BBI, Kind);
  326. DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  327. if (RetVal) {
  328. if (isFalse) {
  329. if (isRev) ++NumTriangleFRev;
  330. else ++NumTriangleFalse;
  331. } else {
  332. if (isRev) ++NumTriangleRev;
  333. else ++NumTriangle;
  334. }
  335. }
  336. break;
  337. }
  338. case ICDiamond: {
  339. if (DisableDiamond) break;
  340. DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
  341. << BBI.TrueBB->getNumber() << ",F:"
  342. << BBI.FalseBB->getNumber() << ") ");
  343. RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
  344. DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  345. if (RetVal) ++NumDiamonds;
  346. break;
  347. }
  348. }
  349. Change |= RetVal;
  350. NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
  351. NumTriangleFalse + NumTriangleFRev + NumDiamonds;
  352. if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
  353. break;
  354. }
  355. if (!Change)
  356. break;
  357. MadeChange |= Change;
  358. }
  359. // Delete tokens in case of early exit.
  360. while (!Tokens.empty()) {
  361. IfcvtToken *Token = Tokens.back();
  362. Tokens.pop_back();
  363. delete Token;
  364. }
  365. Tokens.clear();
  366. BBAnalysis.clear();
  367. if (MadeChange && IfCvtBranchFold) {
  368. BranchFolder BF(false, false);
  369. BF.OptimizeFunction(MF, TII,
  370. MF.getTarget().getRegisterInfo(),
  371. getAnalysisIfAvailable<MachineModuleInfo>());
  372. }
  373. MadeChange |= BFChange;
  374. return MadeChange;
  375. }
  376. /// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
  377. /// its 'true' successor.
  378. static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
  379. MachineBasicBlock *TrueBB) {
  380. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  381. E = BB->succ_end(); SI != E; ++SI) {
  382. MachineBasicBlock *SuccBB = *SI;
  383. if (SuccBB != TrueBB)
  384. return SuccBB;
  385. }
  386. return NULL;
  387. }
  388. /// ReverseBranchCondition - Reverse the condition of the end of the block
  389. /// branch. Swap block's 'true' and 'false' successors.
  390. bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
  391. DebugLoc dl; // FIXME: this is nowhere
  392. if (!TII->ReverseBranchCondition(BBI.BrCond)) {
  393. TII->RemoveBranch(*BBI.BB);
  394. TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
  395. std::swap(BBI.TrueBB, BBI.FalseBB);
  396. return true;
  397. }
  398. return false;
  399. }
  400. /// getNextBlock - Returns the next block in the function blocks ordering. If
  401. /// it is the end, returns NULL.
  402. static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
  403. MachineFunction::iterator I = BB;
  404. MachineFunction::iterator E = BB->getParent()->end();
  405. if (++I == E)
  406. return NULL;
  407. return I;
  408. }
  409. /// ValidSimple - Returns true if the 'true' block (along with its
  410. /// predecessor) forms a valid simple shape for ifcvt. It also returns the
  411. /// number of instructions that the ifcvt would need to duplicate if performed
  412. /// in Dups.
  413. bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
  414. const BranchProbability &Prediction) const {
  415. Dups = 0;
  416. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
  417. return false;
  418. if (TrueBBI.IsBrAnalyzable)
  419. return false;
  420. if (TrueBBI.BB->pred_size() > 1) {
  421. if (TrueBBI.CannotBeCopied ||
  422. !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
  423. Prediction))
  424. return false;
  425. Dups = TrueBBI.NonPredSize;
  426. }
  427. return true;
  428. }
  429. /// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
  430. /// with their common predecessor) forms a valid triangle shape for ifcvt.
  431. /// If 'FalseBranch' is true, it checks if 'true' block's false branch
  432. /// branches to the 'false' block rather than the other way around. It also
  433. /// returns the number of instructions that the ifcvt would need to duplicate
  434. /// if performed in 'Dups'.
  435. bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
  436. bool FalseBranch, unsigned &Dups,
  437. const BranchProbability &Prediction) const {
  438. Dups = 0;
  439. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
  440. return false;
  441. if (TrueBBI.BB->pred_size() > 1) {
  442. if (TrueBBI.CannotBeCopied)
  443. return false;
  444. unsigned Size = TrueBBI.NonPredSize;
  445. if (TrueBBI.IsBrAnalyzable) {
  446. if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
  447. // Ends with an unconditional branch. It will be removed.
  448. --Size;
  449. else {
  450. MachineBasicBlock *FExit = FalseBranch
  451. ? TrueBBI.TrueBB : TrueBBI.FalseBB;
  452. if (FExit)
  453. // Require a conditional branch
  454. ++Size;
  455. }
  456. }
  457. if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
  458. return false;
  459. Dups = Size;
  460. }
  461. MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
  462. if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
  463. MachineFunction::iterator I = TrueBBI.BB;
  464. if (++I == TrueBBI.BB->getParent()->end())
  465. return false;
  466. TExit = I;
  467. }
  468. return TExit && TExit == FalseBBI.BB;
  469. }
  470. /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
  471. /// with their common predecessor) forms a valid diamond shape for ifcvt.
  472. bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
  473. unsigned &Dups1, unsigned &Dups2) const {
  474. Dups1 = Dups2 = 0;
  475. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
  476. FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
  477. return false;
  478. MachineBasicBlock *TT = TrueBBI.TrueBB;
  479. MachineBasicBlock *FT = FalseBBI.TrueBB;
  480. if (!TT && blockAlwaysFallThrough(TrueBBI))
  481. TT = getNextBlock(TrueBBI.BB);
  482. if (!FT && blockAlwaysFallThrough(FalseBBI))
  483. FT = getNextBlock(FalseBBI.BB);
  484. if (TT != FT)
  485. return false;
  486. if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
  487. return false;
  488. if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
  489. return false;
  490. // FIXME: Allow true block to have an early exit?
  491. if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
  492. (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
  493. return false;
  494. // Count duplicate instructions at the beginning of the true and false blocks.
  495. MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
  496. MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
  497. MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
  498. MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
  499. while (TIB != TIE && FIB != FIE) {
  500. // Skip dbg_value instructions. These do not count.
  501. if (TIB->isDebugValue()) {
  502. while (TIB != TIE && TIB->isDebugValue())
  503. ++TIB;
  504. if (TIB == TIE)
  505. break;
  506. }
  507. if (FIB->isDebugValue()) {
  508. while (FIB != FIE && FIB->isDebugValue())
  509. ++FIB;
  510. if (FIB == FIE)
  511. break;
  512. }
  513. if (!TIB->isIdenticalTo(FIB))
  514. break;
  515. ++Dups1;
  516. ++TIB;
  517. ++FIB;
  518. }
  519. // Now, in preparation for counting duplicate instructions at the ends of the
  520. // blocks, move the end iterators up past any branch instructions.
  521. while (TIE != TIB) {
  522. --TIE;
  523. if (!TIE->isBranch())
  524. break;
  525. }
  526. while (FIE != FIB) {
  527. --FIE;
  528. if (!FIE->isBranch())
  529. break;
  530. }
  531. // If Dups1 includes all of a block, then don't count duplicate
  532. // instructions at the end of the blocks.
  533. if (TIB == TIE || FIB == FIE)
  534. return true;
  535. // Count duplicate instructions at the ends of the blocks.
  536. while (TIE != TIB && FIE != FIB) {
  537. // Skip dbg_value instructions. These do not count.
  538. if (TIE->isDebugValue()) {
  539. while (TIE != TIB && TIE->isDebugValue())
  540. --TIE;
  541. if (TIE == TIB)
  542. break;
  543. }
  544. if (FIE->isDebugValue()) {
  545. while (FIE != FIB && FIE->isDebugValue())
  546. --FIE;
  547. if (FIE == FIB)
  548. break;
  549. }
  550. if (!TIE->isIdenticalTo(FIE))
  551. break;
  552. ++Dups2;
  553. --TIE;
  554. --FIE;
  555. }
  556. return true;
  557. }
  558. /// ScanInstructions - Scan all the instructions in the block to determine if
  559. /// the block is predicable. In most cases, that means all the instructions
  560. /// in the block are isPredicable(). Also checks if the block contains any
  561. /// instruction which can clobber a predicate (e.g. condition code register).
  562. /// If so, the block is not predicable unless it's the last instruction.
  563. void IfConverter::ScanInstructions(BBInfo &BBI) {
  564. if (BBI.IsDone)
  565. return;
  566. bool AlreadyPredicated = BBI.Predicate.size() > 0;
  567. // First analyze the end of BB branches.
  568. BBI.TrueBB = BBI.FalseBB = NULL;
  569. BBI.BrCond.clear();
  570. BBI.IsBrAnalyzable =
  571. !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
  572. BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
  573. if (BBI.BrCond.size()) {
  574. // No false branch. This BB must end with a conditional branch and a
  575. // fallthrough.
  576. if (!BBI.FalseBB)
  577. BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
  578. if (!BBI.FalseBB) {
  579. // Malformed bcc? True and false blocks are the same?
  580. BBI.IsUnpredicable = true;
  581. return;
  582. }
  583. }
  584. // Then scan all the instructions.
  585. BBI.NonPredSize = 0;
  586. BBI.ExtraCost = 0;
  587. BBI.ExtraCost2 = 0;
  588. BBI.ClobbersPred = false;
  589. for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
  590. I != E; ++I) {
  591. if (I->isDebugValue())
  592. continue;
  593. if (I->isNotDuplicable())
  594. BBI.CannotBeCopied = true;
  595. bool isPredicated = TII->isPredicated(I);
  596. bool isCondBr = BBI.IsBrAnalyzable && I->isConditionalBranch();
  597. if (!isCondBr) {
  598. if (!isPredicated) {
  599. BBI.NonPredSize++;
  600. unsigned ExtraPredCost = 0;
  601. unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I,
  602. &ExtraPredCost);
  603. if (NumCycles > 1)
  604. BBI.ExtraCost += NumCycles-1;
  605. BBI.ExtraCost2 += ExtraPredCost;
  606. } else if (!AlreadyPredicated) {
  607. // FIXME: This instruction is already predicated before the
  608. // if-conversion pass. It's probably something like a conditional move.
  609. // Mark this block unpredicable for now.
  610. BBI.IsUnpredicable = true;
  611. return;
  612. }
  613. }
  614. if (BBI.ClobbersPred && !isPredicated) {
  615. // Predicate modification instruction should end the block (except for
  616. // already predicated instructions and end of block branches).
  617. if (isCondBr) {
  618. // A conditional branch is not predicable, but it may be eliminated.
  619. continue;
  620. }
  621. // Predicate may have been modified, the subsequent (currently)
  622. // unpredicated instructions cannot be correctly predicated.
  623. BBI.IsUnpredicable = true;
  624. return;
  625. }
  626. // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
  627. // still potentially predicable.
  628. std::vector<MachineOperand> PredDefs;
  629. if (TII->DefinesPredicate(I, PredDefs))
  630. BBI.ClobbersPred = true;
  631. if (!TII->isPredicable(I)) {
  632. BBI.IsUnpredicable = true;
  633. return;
  634. }
  635. }
  636. }
  637. /// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
  638. /// predicated by the specified predicate.
  639. bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
  640. SmallVectorImpl<MachineOperand> &Pred,
  641. bool isTriangle, bool RevBranch) {
  642. // If the block is dead or unpredicable, then it cannot be predicated.
  643. if (BBI.IsDone || BBI.IsUnpredicable)
  644. return false;
  645. // If it is already predicated, check if its predicate subsumes the new
  646. // predicate.
  647. if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
  648. return false;
  649. if (BBI.BrCond.size()) {
  650. if (!isTriangle)
  651. return false;
  652. // Test predicate subsumption.
  653. SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
  654. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  655. if (RevBranch) {
  656. if (TII->ReverseBranchCondition(Cond))
  657. return false;
  658. }
  659. if (TII->ReverseBranchCondition(RevPred) ||
  660. !TII->SubsumesPredicate(Cond, RevPred))
  661. return false;
  662. }
  663. return true;
  664. }
  665. /// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
  666. /// the specified block. Record its successors and whether it looks like an
  667. /// if-conversion candidate.
  668. IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
  669. std::vector<IfcvtToken*> &Tokens) {
  670. BBInfo &BBI = BBAnalysis[BB->getNumber()];
  671. if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
  672. return BBI;
  673. BBI.BB = BB;
  674. BBI.IsBeingAnalyzed = true;
  675. ScanInstructions(BBI);
  676. // Unanalyzable or ends with fallthrough or unconditional branch, or if is not
  677. // considered for ifcvt anymore.
  678. if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
  679. BBI.IsBeingAnalyzed = false;
  680. BBI.IsAnalyzed = true;
  681. return BBI;
  682. }
  683. // Do not ifcvt if either path is a back edge to the entry block.
  684. if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
  685. BBI.IsBeingAnalyzed = false;
  686. BBI.IsAnalyzed = true;
  687. return BBI;
  688. }
  689. // Do not ifcvt if true and false fallthrough blocks are the same.
  690. if (!BBI.FalseBB) {
  691. BBI.IsBeingAnalyzed = false;
  692. BBI.IsAnalyzed = true;
  693. return BBI;
  694. }
  695. BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
  696. BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
  697. if (TrueBBI.IsDone && FalseBBI.IsDone) {
  698. BBI.IsBeingAnalyzed = false;
  699. BBI.IsAnalyzed = true;
  700. return BBI;
  701. }
  702. SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  703. bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
  704. unsigned Dups = 0;
  705. unsigned Dups2 = 0;
  706. bool TNeedSub = TrueBBI.Predicate.size() > 0;
  707. bool FNeedSub = FalseBBI.Predicate.size() > 0;
  708. bool Enqueued = false;
  709. BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
  710. if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
  711. MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
  712. TrueBBI.ExtraCost), TrueBBI.ExtraCost2,
  713. *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
  714. FalseBBI.ExtraCost),FalseBBI.ExtraCost2,
  715. Prediction) &&
  716. FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
  717. FeasibilityAnalysis(FalseBBI, RevCond)) {
  718. // Diamond:
  719. // EBB
  720. // / \_
  721. // | |
  722. // TBB FBB
  723. // \ /
  724. // TailBB
  725. // Note TailBB can be empty.
  726. Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
  727. Dups2));
  728. Enqueued = true;
  729. }
  730. if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
  731. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  732. TrueBBI.ExtraCost2, Prediction) &&
  733. FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
  734. // Triangle:
  735. // EBB
  736. // | \_
  737. // | |
  738. // | TBB
  739. // | /
  740. // FBB
  741. Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
  742. Enqueued = true;
  743. }
  744. if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
  745. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  746. TrueBBI.ExtraCost2, Prediction) &&
  747. FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
  748. Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
  749. Enqueued = true;
  750. }
  751. if (ValidSimple(TrueBBI, Dups, Prediction) &&
  752. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  753. TrueBBI.ExtraCost2, Prediction) &&
  754. FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
  755. // Simple (split, no rejoin):
  756. // EBB
  757. // | \_
  758. // | |
  759. // | TBB---> exit
  760. // |
  761. // FBB
  762. Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
  763. Enqueued = true;
  764. }
  765. if (CanRevCond) {
  766. // Try the other path...
  767. if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
  768. Prediction.getCompl()) &&
  769. MeetIfcvtSizeLimit(*FalseBBI.BB,
  770. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  771. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  772. FeasibilityAnalysis(FalseBBI, RevCond, true)) {
  773. Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
  774. Enqueued = true;
  775. }
  776. if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
  777. Prediction.getCompl()) &&
  778. MeetIfcvtSizeLimit(*FalseBBI.BB,
  779. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  780. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  781. FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
  782. Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
  783. Enqueued = true;
  784. }
  785. if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
  786. MeetIfcvtSizeLimit(*FalseBBI.BB,
  787. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  788. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  789. FeasibilityAnalysis(FalseBBI, RevCond)) {
  790. Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
  791. Enqueued = true;
  792. }
  793. }
  794. BBI.IsEnqueued = Enqueued;
  795. BBI.IsBeingAnalyzed = false;
  796. BBI.IsAnalyzed = true;
  797. return BBI;
  798. }
  799. /// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
  800. /// candidates.
  801. void IfConverter::AnalyzeBlocks(MachineFunction &MF,
  802. std::vector<IfcvtToken*> &Tokens) {
  803. for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
  804. MachineBasicBlock *BB = I;
  805. AnalyzeBlock(BB, Tokens);
  806. }
  807. // Sort to favor more complex ifcvt scheme.
  808. std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
  809. }
  810. /// canFallThroughTo - Returns true either if ToBB is the next block after BB or
  811. /// that all the intervening blocks are empty (given BB can fall through to its
  812. /// next block).
  813. static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
  814. MachineFunction::iterator PI = BB;
  815. MachineFunction::iterator I = llvm::next(PI);
  816. MachineFunction::iterator TI = ToBB;
  817. MachineFunction::iterator E = BB->getParent()->end();
  818. while (I != TI) {
  819. // Check isSuccessor to avoid case where the next block is empty, but
  820. // it's not a successor.
  821. if (I == E || !I->empty() || !PI->isSuccessor(I))
  822. return false;
  823. PI = I++;
  824. }
  825. return true;
  826. }
  827. /// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
  828. /// to determine if it can be if-converted. If predecessor is already enqueued,
  829. /// dequeue it!
  830. void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
  831. for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
  832. E = BB->pred_end(); PI != E; ++PI) {
  833. BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
  834. if (PBBI.IsDone || PBBI.BB == BB)
  835. continue;
  836. PBBI.IsAnalyzed = false;
  837. PBBI.IsEnqueued = false;
  838. }
  839. }
  840. /// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
  841. ///
  842. static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
  843. const TargetInstrInfo *TII) {
  844. DebugLoc dl; // FIXME: this is nowhere
  845. SmallVector<MachineOperand, 0> NoCond;
  846. TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
  847. }
  848. /// RemoveExtraEdges - Remove true / false edges if either / both are no longer
  849. /// successors.
  850. void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
  851. MachineBasicBlock *TBB = NULL, *FBB = NULL;
  852. SmallVector<MachineOperand, 4> Cond;
  853. if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
  854. BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
  855. }
  856. /// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
  857. /// modeled as read + write (sort like two-address instructions). These
  858. /// routines track register liveness and add implicit uses to if-converted
  859. /// instructions to conform to the model.
  860. static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
  861. const TargetRegisterInfo *TRI) {
  862. for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
  863. E = BB->livein_end(); I != E; ++I) {
  864. unsigned Reg = *I;
  865. Redefs.insert(Reg);
  866. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  867. Redefs.insert(*SubRegs);
  868. }
  869. }
  870. static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
  871. const TargetRegisterInfo *TRI,
  872. bool AddImpUse = false) {
  873. SmallVector<unsigned, 4> Defs;
  874. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  875. const MachineOperand &MO = MI->getOperand(i);
  876. if (!MO.isReg())
  877. continue;
  878. unsigned Reg = MO.getReg();
  879. if (!Reg)
  880. continue;
  881. if (MO.isDef())
  882. Defs.push_back(Reg);
  883. else if (MO.isKill()) {
  884. Redefs.erase(Reg);
  885. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  886. Redefs.erase(*SubRegs);
  887. }
  888. }
  889. for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
  890. unsigned Reg = Defs[i];
  891. if (Redefs.count(Reg)) {
  892. if (AddImpUse)
  893. // Treat predicated update as read + write.
  894. MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
  895. true/*IsImp*/,false/*IsKill*/,
  896. false/*IsDead*/,true/*IsUndef*/));
  897. } else {
  898. Redefs.insert(Reg);
  899. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  900. Redefs.insert(*SubRegs);
  901. }
  902. }
  903. }
  904. static void UpdatePredRedefs(MachineBasicBlock::iterator I,
  905. MachineBasicBlock::iterator E,
  906. SmallSet<unsigned,4> &Redefs,
  907. const TargetRegisterInfo *TRI) {
  908. while (I != E) {
  909. UpdatePredRedefs(I, Redefs, TRI);
  910. ++I;
  911. }
  912. }
  913. /// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
  914. ///
  915. bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
  916. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  917. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  918. BBInfo *CvtBBI = &TrueBBI;
  919. BBInfo *NextBBI = &FalseBBI;
  920. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  921. if (Kind == ICSimpleFalse)
  922. std::swap(CvtBBI, NextBBI);
  923. if (CvtBBI->IsDone ||
  924. (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
  925. // Something has changed. It's no longer safe to predicate this block.
  926. BBI.IsAnalyzed = false;
  927. CvtBBI->IsAnalyzed = false;
  928. return false;
  929. }
  930. if (Kind == ICSimpleFalse)
  931. if (TII->ReverseBranchCondition(Cond))
  932. llvm_unreachable("Unable to reverse branch condition!");
  933. // Initialize liveins to the first BB. These are potentiall redefined by
  934. // predicated instructions.
  935. SmallSet<unsigned, 4> Redefs;
  936. InitPredRedefs(CvtBBI->BB, Redefs, TRI);
  937. InitPredRedefs(NextBBI->BB, Redefs, TRI);
  938. if (CvtBBI->BB->pred_size() > 1) {
  939. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  940. // Copy instructions in the true block, predicate them, and add them to
  941. // the entry block.
  942. CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
  943. } else {
  944. PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
  945. // Merge converted block into entry block.
  946. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  947. MergeBlocks(BBI, *CvtBBI);
  948. }
  949. bool IterIfcvt = true;
  950. if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
  951. InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
  952. BBI.HasFallThrough = false;
  953. // Now ifcvt'd block will look like this:
  954. // BB:
  955. // ...
  956. // t, f = cmp
  957. // if t op
  958. // b BBf
  959. //
  960. // We cannot further ifcvt this block because the unconditional branch
  961. // will have to be predicated on the new condition, that will not be
  962. // available if cmp executes.
  963. IterIfcvt = false;
  964. }
  965. RemoveExtraEdges(BBI);
  966. // Update block info. BB can be iteratively if-converted.
  967. if (!IterIfcvt)
  968. BBI.IsDone = true;
  969. InvalidatePreds(BBI.BB);
  970. CvtBBI->IsDone = true;
  971. // FIXME: Must maintain LiveIns.
  972. return true;
  973. }
  974. /// IfConvertTriangle - If convert a triangle sub-CFG.
  975. ///
  976. bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
  977. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  978. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  979. BBInfo *CvtBBI = &TrueBBI;
  980. BBInfo *NextBBI = &FalseBBI;
  981. DebugLoc dl; // FIXME: this is nowhere
  982. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  983. if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
  984. std::swap(CvtBBI, NextBBI);
  985. if (CvtBBI->IsDone ||
  986. (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
  987. // Something has changed. It's no longer safe to predicate this block.
  988. BBI.IsAnalyzed = false;
  989. CvtBBI->IsAnalyzed = false;
  990. return false;
  991. }
  992. if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
  993. if (TII->ReverseBranchCondition(Cond))
  994. llvm_unreachable("Unable to reverse branch condition!");
  995. if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
  996. if (ReverseBranchCondition(*CvtBBI)) {
  997. // BB has been changed, modify its predecessors (except for this
  998. // one) so they don't get ifcvt'ed based on bad intel.
  999. for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
  1000. E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
  1001. MachineBasicBlock *PBB = *PI;
  1002. if (PBB == BBI.BB)
  1003. continue;
  1004. BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
  1005. if (PBBI.IsEnqueued) {
  1006. PBBI.IsAnalyzed = false;
  1007. PBBI.IsEnqueued = false;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. // Initialize liveins to the first BB. These are potentially redefined by
  1013. // predicated instructions.
  1014. SmallSet<unsigned, 4> Redefs;
  1015. InitPredRedefs(CvtBBI->BB, Redefs, TRI);
  1016. InitPredRedefs(NextBBI->BB, Redefs, TRI);
  1017. bool HasEarlyExit = CvtBBI->FalseBB != NULL;
  1018. if (CvtBBI->BB->pred_size() > 1) {
  1019. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  1020. // Copy instructions in the true block, predicate them, and add them to
  1021. // the entry block.
  1022. CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
  1023. } else {
  1024. // Predicate the 'true' block after removing its branch.
  1025. CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
  1026. PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
  1027. // Now merge the entry of the triangle with the true block.
  1028. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  1029. MergeBlocks(BBI, *CvtBBI, false);
  1030. }
  1031. // If 'true' block has a 'false' successor, add an exit branch to it.
  1032. if (HasEarlyExit) {
  1033. SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
  1034. CvtBBI->BrCond.end());
  1035. if (TII->ReverseBranchCondition(RevCond))
  1036. llvm_unreachable("Unable to reverse branch condition!");
  1037. TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
  1038. BBI.BB->addSuccessor(CvtBBI->FalseBB);
  1039. }
  1040. // Merge in the 'false' block if the 'false' block has no other
  1041. // predecessors. Otherwise, add an unconditional branch to 'false'.
  1042. bool FalseBBDead = false;
  1043. bool IterIfcvt = true;
  1044. bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
  1045. if (!isFallThrough) {
  1046. // Only merge them if the true block does not fallthrough to the false
  1047. // block. By not merging them, we make it possible to iteratively
  1048. // ifcvt the blocks.
  1049. if (!HasEarlyExit &&
  1050. NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
  1051. MergeBlocks(BBI, *NextBBI);
  1052. FalseBBDead = true;
  1053. } else {
  1054. InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
  1055. BBI.HasFallThrough = false;
  1056. }
  1057. // Mixed predicated and unpredicated code. This cannot be iteratively
  1058. // predicated.
  1059. IterIfcvt = false;
  1060. }
  1061. RemoveExtraEdges(BBI);
  1062. // Update block info. BB can be iteratively if-converted.
  1063. if (!IterIfcvt)
  1064. BBI.IsDone = true;
  1065. InvalidatePreds(BBI.BB);
  1066. CvtBBI->IsDone = true;
  1067. if (FalseBBDead)
  1068. NextBBI->IsDone = true;
  1069. // FIXME: Must maintain LiveIns.
  1070. return true;
  1071. }
  1072. /// IfConvertDiamond - If convert a diamond sub-CFG.
  1073. ///
  1074. bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
  1075. unsigned NumDups1, unsigned NumDups2) {
  1076. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1077. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1078. MachineBasicBlock *TailBB = TrueBBI.TrueBB;
  1079. // True block must fall through or end with an unanalyzable terminator.
  1080. if (!TailBB) {
  1081. if (blockAlwaysFallThrough(TrueBBI))
  1082. TailBB = FalseBBI.TrueBB;
  1083. assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
  1084. }
  1085. if (TrueBBI.IsDone || FalseBBI.IsDone ||
  1086. TrueBBI.BB->pred_size() > 1 ||
  1087. FalseBBI.BB->pred_size() > 1) {
  1088. // Something has changed. It's no longer safe to predicate these blocks.
  1089. BBI.IsAnalyzed = false;
  1090. TrueBBI.IsAnalyzed = false;
  1091. FalseBBI.IsAnalyzed = false;
  1092. return false;
  1093. }
  1094. // Put the predicated instructions from the 'true' block before the
  1095. // instructions from the 'false' block, unless the true block would clobber
  1096. // the predicate, in which case, do the opposite.
  1097. BBInfo *BBI1 = &TrueBBI;
  1098. BBInfo *BBI2 = &FalseBBI;
  1099. SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  1100. if (TII->ReverseBranchCondition(RevCond))
  1101. llvm_unreachable("Unable to reverse branch condition!");
  1102. SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
  1103. SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
  1104. // Figure out the more profitable ordering.
  1105. bool DoSwap = false;
  1106. if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
  1107. DoSwap = true;
  1108. else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
  1109. if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
  1110. DoSwap = true;
  1111. }
  1112. if (DoSwap) {
  1113. std::swap(BBI1, BBI2);
  1114. std::swap(Cond1, Cond2);
  1115. }
  1116. // Remove the conditional branch from entry to the blocks.
  1117. BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
  1118. // Initialize liveins to the first BB. These are potentially redefined by
  1119. // predicated instructions.
  1120. SmallSet<unsigned, 4> Redefs;
  1121. InitPredRedefs(BBI1->BB, Redefs, TRI);
  1122. // Remove the duplicated instructions at the beginnings of both paths.
  1123. MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
  1124. MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
  1125. MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
  1126. MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
  1127. // Skip dbg_value instructions
  1128. while (DI1 != DIE1 && DI1->isDebugValue())
  1129. ++DI1;
  1130. while (DI2 != DIE2 && DI2->isDebugValue())
  1131. ++DI2;
  1132. BBI1->NonPredSize -= NumDups1;
  1133. BBI2->NonPredSize -= NumDups1;
  1134. // Skip past the dups on each side separately since there may be
  1135. // differing dbg_value entries.
  1136. for (unsigned i = 0; i < NumDups1; ++DI1) {
  1137. if (!DI1->isDebugValue())
  1138. ++i;
  1139. }
  1140. while (NumDups1 != 0) {
  1141. ++DI2;
  1142. if (!DI2->isDebugValue())
  1143. --NumDups1;
  1144. }
  1145. UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
  1146. BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
  1147. BBI2->BB->erase(BBI2->BB->begin(), DI2);
  1148. // Remove branch from 'true' block and remove duplicated instructions.
  1149. BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
  1150. DI1 = BBI1->BB->end();
  1151. for (unsigned i = 0; i != NumDups2; ) {
  1152. // NumDups2 only counted non-dbg_value instructions, so this won't
  1153. // run off the head of the list.
  1154. assert (DI1 != BBI1->BB->begin());
  1155. --DI1;
  1156. // skip dbg_value instructions
  1157. if (!DI1->isDebugValue())
  1158. ++i;
  1159. }
  1160. BBI1->BB->erase(DI1, BBI1->BB->end());
  1161. // Remove 'false' block branch and find the last instruction to predicate.
  1162. BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
  1163. DI2 = BBI2->BB->end();
  1164. while (NumDups2 != 0) {
  1165. // NumDups2 only counted non-dbg_value instructions, so this won't
  1166. // run off the head of the list.
  1167. assert (DI2 != BBI2->BB->begin());
  1168. --DI2;
  1169. // skip dbg_value instructions
  1170. if (!DI2->isDebugValue())
  1171. --NumDups2;
  1172. }
  1173. // Remember which registers would later be defined by the false block.
  1174. // This allows us not to predicate instructions in the true block that would
  1175. // later be re-defined. That is, rather than
  1176. // subeq r0, r1, #1
  1177. // addne r0, r1, #1
  1178. // generate:
  1179. // sub r0, r1, #1
  1180. // addne r0, r1, #1
  1181. SmallSet<unsigned, 4> RedefsByFalse;
  1182. SmallSet<unsigned, 4> ExtUses;
  1183. if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
  1184. for (MachineBasicBlock::iterator FI = BBI2->BB->begin(); FI != DI2; ++FI) {
  1185. if (FI->isDebugValue())
  1186. continue;
  1187. SmallVector<unsigned, 4> Defs;
  1188. for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
  1189. const MachineOperand &MO = FI->getOperand(i);
  1190. if (!MO.isReg())
  1191. continue;
  1192. unsigned Reg = MO.getReg();
  1193. if (!Reg)
  1194. continue;
  1195. if (MO.isDef()) {
  1196. Defs.push_back(Reg);
  1197. } else if (!RedefsByFalse.count(Reg)) {
  1198. // These are defined before ctrl flow reach the 'false' instructions.
  1199. // They cannot be modified by the 'true' instructions.
  1200. ExtUses.insert(Reg);
  1201. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  1202. ExtUses.insert(*SubRegs);
  1203. }
  1204. }
  1205. for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
  1206. unsigned Reg = Defs[i];
  1207. if (!ExtUses.count(Reg)) {
  1208. RedefsByFalse.insert(Reg);
  1209. for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
  1210. RedefsByFalse.insert(*SubRegs);
  1211. }
  1212. }
  1213. }
  1214. }
  1215. // Predicate the 'true' block.
  1216. PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs, &RedefsByFalse);
  1217. // Predicate the 'false' block.
  1218. PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
  1219. // Merge the true block into the entry of the diamond.
  1220. MergeBlocks(BBI, *BBI1, TailBB == 0);
  1221. MergeBlocks(BBI, *BBI2, TailBB == 0);
  1222. // If the if-converted block falls through or unconditionally branches into
  1223. // the tail block, and the tail block does not have other predecessors, then
  1224. // fold the tail block in as well. Otherwise, unless it falls through to the
  1225. // tail, add a unconditional branch to it.
  1226. if (TailBB) {
  1227. BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
  1228. bool CanMergeTail = !TailBBI.HasFallThrough;
  1229. // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
  1230. // check if there are any other predecessors besides those.
  1231. unsigned NumPreds = TailBB->pred_size();
  1232. if (NumPreds > 1)
  1233. CanMergeTail = false;
  1234. else if (NumPreds == 1 && CanMergeTail) {
  1235. MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
  1236. if (*PI != BBI1->BB && *PI != BBI2->BB)
  1237. CanMergeTail = false;
  1238. }
  1239. if (CanMergeTail) {
  1240. MergeBlocks(BBI, TailBBI);
  1241. TailBBI.IsDone = true;
  1242. } else {
  1243. BBI.BB->addSuccessor(TailBB);
  1244. InsertUncondBranch(BBI.BB, TailBB, TII);
  1245. BBI.HasFallThrough = false;
  1246. }
  1247. }
  1248. // RemoveExtraEdges won't work if the block has an unanalyzable branch,
  1249. // which can happen here if TailBB is unanalyzable and is merged, so
  1250. // explicitly remove BBI1 and BBI2 as successors.
  1251. BBI.BB->removeSuccessor(BBI1->BB);
  1252. BBI.BB->removeSuccessor(BBI2->BB);
  1253. RemoveExtraEdges(BBI);
  1254. // Update block info.
  1255. BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
  1256. InvalidatePreds(BBI.BB);
  1257. // FIXME: Must maintain LiveIns.
  1258. return true;
  1259. }
  1260. static bool MaySpeculate(const MachineInstr *MI,
  1261. SmallSet<unsigned, 4> &LaterRedefs,
  1262. const TargetInstrInfo *TII) {
  1263. bool SawStore = true;
  1264. if (!MI->isSafeToMove(TII, 0, SawStore))
  1265. return false;
  1266. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1267. const MachineOperand &MO = MI->getOperand(i);
  1268. if (!MO.isReg())
  1269. continue;
  1270. unsigned Reg = MO.getReg();
  1271. if (!Reg)
  1272. continue;
  1273. if (MO.isDef() && !LaterRedefs.count(Reg))
  1274. return false;
  1275. }
  1276. return true;
  1277. }
  1278. /// PredicateBlock - Predicate instructions from the start of the block to the
  1279. /// specified end with the specified condition.
  1280. void IfConverter::PredicateBlock(BBInfo &BBI,
  1281. MachineBasicBlock::iterator E,
  1282. SmallVectorImpl<MachineOperand> &Cond,
  1283. SmallSet<unsigned, 4> &Redefs,
  1284. SmallSet<unsigned, 4> *LaterRedefs) {
  1285. bool AnyUnpred = false;
  1286. bool MaySpec = LaterRedefs != 0;
  1287. for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
  1288. if (I->isDebugValue() || TII->isPredicated(I))
  1289. continue;
  1290. // It may be possible not to predicate an instruction if it's the 'true'
  1291. // side of a diamond and the 'false' side may re-define the instruction's
  1292. // defs.
  1293. if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
  1294. AnyUnpred = true;
  1295. continue;
  1296. }
  1297. // If any instruction is predicated, then every instruction after it must
  1298. // be predicated.
  1299. MaySpec = false;
  1300. if (!TII->PredicateInstruction(I, Cond)) {
  1301. #ifndef NDEBUG
  1302. dbgs() << "Unable to predicate " << *I << "!\n";
  1303. #endif
  1304. llvm_unreachable(0);
  1305. }
  1306. // If the predicated instruction now redefines a register as the result of
  1307. // if-conversion, add an implicit kill.
  1308. UpdatePredRedefs(I, Redefs, TRI, true);
  1309. }
  1310. std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
  1311. BBI.IsAnalyzed = false;
  1312. BBI.NonPredSize = 0;
  1313. ++NumIfConvBBs;
  1314. if (AnyUnpred)
  1315. ++NumUnpred;
  1316. }
  1317. /// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
  1318. /// the destination block. Skip end of block branches if IgnoreBr is true.
  1319. void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
  1320. SmallVectorImpl<MachineOperand> &Cond,
  1321. SmallSet<unsigned, 4> &Redefs,
  1322. bool IgnoreBr) {
  1323. MachineFunction &MF = *ToBBI.BB->getParent();
  1324. for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
  1325. E = FromBBI.BB->end(); I != E; ++I) {
  1326. // Do not copy the end of the block branches.
  1327. if (IgnoreBr && I->isBranch())
  1328. break;
  1329. MachineInstr *MI = MF.CloneMachineInstr(I);
  1330. ToBBI.BB->insert(ToBBI.BB->end(), MI);
  1331. ToBBI.NonPredSize++;
  1332. unsigned ExtraPredCost = 0;
  1333. unsigned NumCycles = TII->getInstrLatency(InstrItins, &*I, &ExtraPredCost);
  1334. if (NumCycles > 1)
  1335. ToBBI.ExtraCost += NumCycles-1;
  1336. ToBBI.ExtraCost2 += ExtraPredCost;
  1337. if (!TII->isPredicated(I) && !MI->isDebugValue()) {
  1338. if (!TII->PredicateInstruction(MI, Cond)) {
  1339. #ifndef NDEBUG
  1340. dbgs() << "Unable to predicate " << *I << "!\n";
  1341. #endif
  1342. llvm_unreachable(0);
  1343. }
  1344. }
  1345. // If the predicated instruction now redefines a register as the result of
  1346. // if-conversion, add an implicit kill.
  1347. UpdatePredRedefs(MI, Redefs, TRI, true);
  1348. }
  1349. if (!IgnoreBr) {
  1350. std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
  1351. FromBBI.BB->succ_end());
  1352. MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
  1353. MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
  1354. for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
  1355. MachineBasicBlock *Succ = Succs[i];
  1356. // Fallthrough edge can't be transferred.
  1357. if (Succ == FallThrough)
  1358. continue;
  1359. ToBBI.BB->addSuccessor(Succ);
  1360. }
  1361. }
  1362. std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
  1363. std::back_inserter(ToBBI.Predicate));
  1364. std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
  1365. ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
  1366. ToBBI.IsAnalyzed = false;
  1367. ++NumDupBBs;
  1368. }
  1369. /// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
  1370. /// This will leave FromBB as an empty block, so remove all of its
  1371. /// successor edges except for the fall-through edge. If AddEdges is true,
  1372. /// i.e., when FromBBI's branch is being moved, add those successor edges to
  1373. /// ToBBI.
  1374. void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
  1375. ToBBI.BB->splice(ToBBI.BB->end(),
  1376. FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
  1377. std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
  1378. FromBBI.BB->succ_end());
  1379. MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
  1380. MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
  1381. for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
  1382. MachineBasicBlock *Succ = Succs[i];
  1383. // Fallthrough edge can't be transferred.
  1384. if (Succ == FallThrough)
  1385. continue;
  1386. FromBBI.BB->removeSuccessor(Succ);
  1387. if (AddEdges)
  1388. ToBBI.BB->addSuccessor(Succ);
  1389. }
  1390. // Now FromBBI always falls through to the next block!
  1391. if (NBB && !FromBBI.BB->isSuccessor(NBB))
  1392. FromBBI.BB->addSuccessor(NBB);
  1393. std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
  1394. std::back_inserter(ToBBI.Predicate));
  1395. FromBBI.Predicate.clear();
  1396. ToBBI.NonPredSize += FromBBI.NonPredSize;
  1397. ToBBI.ExtraCost += FromBBI.ExtraCost;
  1398. ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
  1399. FromBBI.NonPredSize = 0;
  1400. FromBBI.ExtraCost = 0;
  1401. FromBBI.ExtraCost2 = 0;
  1402. ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
  1403. ToBBI.HasFallThrough = FromBBI.HasFallThrough;
  1404. ToBBI.IsAnalyzed = false;
  1405. FromBBI.IsAnalyzed = false;
  1406. }