IfConversion.cpp 61 KB

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