IfConversion.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  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, which
  11. // tries to convert conditional branches into predicated instructions.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "BranchFolding.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/ScopeExit.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/SparseSet.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/ADT/iterator_range.h"
  22. #include "llvm/CodeGen/LivePhysRegs.h"
  23. #include "llvm/CodeGen/MachineBasicBlock.h"
  24. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  25. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineFunctionPass.h"
  28. #include "llvm/CodeGen/MachineInstr.h"
  29. #include "llvm/CodeGen/MachineInstrBuilder.h"
  30. #include "llvm/CodeGen/MachineModuleInfo.h"
  31. #include "llvm/CodeGen/MachineOperand.h"
  32. #include "llvm/CodeGen/MachineRegisterInfo.h"
  33. #include "llvm/CodeGen/TargetInstrInfo.h"
  34. #include "llvm/CodeGen/TargetLowering.h"
  35. #include "llvm/CodeGen/TargetRegisterInfo.h"
  36. #include "llvm/CodeGen/TargetSchedule.h"
  37. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  38. #include "llvm/IR/DebugLoc.h"
  39. #include "llvm/MC/MCRegisterInfo.h"
  40. #include "llvm/Pass.h"
  41. #include "llvm/Support/BranchProbability.h"
  42. #include "llvm/Support/CommandLine.h"
  43. #include "llvm/Support/Debug.h"
  44. #include "llvm/Support/ErrorHandling.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include <algorithm>
  47. #include <cassert>
  48. #include <functional>
  49. #include <iterator>
  50. #include <memory>
  51. #include <utility>
  52. #include <vector>
  53. using namespace llvm;
  54. #define DEBUG_TYPE "if-converter"
  55. // Hidden options for help debugging.
  56. static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
  57. static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
  58. static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
  59. static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
  60. cl::init(false), cl::Hidden);
  61. static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
  62. cl::init(false), cl::Hidden);
  63. static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
  64. cl::init(false), cl::Hidden);
  65. static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
  66. cl::init(false), cl::Hidden);
  67. static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
  68. cl::init(false), cl::Hidden);
  69. static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
  70. cl::init(false), cl::Hidden);
  71. static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
  72. cl::init(false), cl::Hidden);
  73. static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
  74. cl::init(false), cl::Hidden);
  75. static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
  76. cl::init(true), cl::Hidden);
  77. STATISTIC(NumSimple, "Number of simple if-conversions performed");
  78. STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
  79. STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
  80. STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
  81. STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
  82. STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
  83. STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
  84. STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
  85. STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
  86. STATISTIC(NumDupBBs, "Number of duplicated blocks");
  87. STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
  88. namespace {
  89. class IfConverter : public MachineFunctionPass {
  90. enum IfcvtKind {
  91. ICNotClassfied, // BB data valid, but not classified.
  92. ICSimpleFalse, // Same as ICSimple, but on the false path.
  93. ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
  94. ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
  95. ICTriangleRev, // Same as ICTriangle, but true path rev condition.
  96. ICTriangleFalse, // Same as ICTriangle, but on the false path.
  97. ICTriangle, // BB is entry of a triangle sub-CFG.
  98. ICDiamond, // BB is entry of a diamond sub-CFG.
  99. ICForkedDiamond // BB is entry of an almost diamond sub-CFG, with a
  100. // common tail that can be shared.
  101. };
  102. /// One per MachineBasicBlock, this is used to cache the result
  103. /// if-conversion feasibility analysis. This includes results from
  104. /// TargetInstrInfo::analyzeBranch() (i.e. TBB, FBB, and Cond), and its
  105. /// classification, and common tail block of its successors (if it's a
  106. /// diamond shape), its size, whether it's predicable, and whether any
  107. /// instruction can clobber the 'would-be' predicate.
  108. ///
  109. /// IsDone - True if BB is not to be considered for ifcvt.
  110. /// IsBeingAnalyzed - True if BB is currently being analyzed.
  111. /// IsAnalyzed - True if BB has been analyzed (info is still valid).
  112. /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
  113. /// IsBrAnalyzable - True if analyzeBranch() returns false.
  114. /// HasFallThrough - True if BB may fallthrough to the following BB.
  115. /// IsUnpredicable - True if BB is known to be unpredicable.
  116. /// ClobbersPred - True if BB could modify predicates (e.g. has
  117. /// cmp, call, etc.)
  118. /// NonPredSize - Number of non-predicated instructions.
  119. /// ExtraCost - Extra cost for multi-cycle instructions.
  120. /// ExtraCost2 - Some instructions are slower when predicated
  121. /// BB - Corresponding MachineBasicBlock.
  122. /// TrueBB / FalseBB- See analyzeBranch().
  123. /// BrCond - Conditions for end of block conditional branches.
  124. /// Predicate - Predicate used in the BB.
  125. struct BBInfo {
  126. bool IsDone : 1;
  127. bool IsBeingAnalyzed : 1;
  128. bool IsAnalyzed : 1;
  129. bool IsEnqueued : 1;
  130. bool IsBrAnalyzable : 1;
  131. bool IsBrReversible : 1;
  132. bool HasFallThrough : 1;
  133. bool IsUnpredicable : 1;
  134. bool CannotBeCopied : 1;
  135. bool ClobbersPred : 1;
  136. unsigned NonPredSize = 0;
  137. unsigned ExtraCost = 0;
  138. unsigned ExtraCost2 = 0;
  139. MachineBasicBlock *BB = nullptr;
  140. MachineBasicBlock *TrueBB = nullptr;
  141. MachineBasicBlock *FalseBB = nullptr;
  142. SmallVector<MachineOperand, 4> BrCond;
  143. SmallVector<MachineOperand, 4> Predicate;
  144. BBInfo() : IsDone(false), IsBeingAnalyzed(false),
  145. IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
  146. IsBrReversible(false), HasFallThrough(false),
  147. IsUnpredicable(false), CannotBeCopied(false),
  148. ClobbersPred(false) {}
  149. };
  150. /// Record information about pending if-conversions to attempt:
  151. /// BBI - Corresponding BBInfo.
  152. /// Kind - Type of block. See IfcvtKind.
  153. /// NeedSubsumption - True if the to-be-predicated BB has already been
  154. /// predicated.
  155. /// NumDups - Number of instructions that would be duplicated due
  156. /// to this if-conversion. (For diamonds, the number of
  157. /// identical instructions at the beginnings of both
  158. /// paths).
  159. /// NumDups2 - For diamonds, the number of identical instructions
  160. /// at the ends of both paths.
  161. struct IfcvtToken {
  162. BBInfo &BBI;
  163. IfcvtKind Kind;
  164. unsigned NumDups;
  165. unsigned NumDups2;
  166. bool NeedSubsumption : 1;
  167. bool TClobbersPred : 1;
  168. bool FClobbersPred : 1;
  169. IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
  170. bool tc = false, bool fc = false)
  171. : BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
  172. TClobbersPred(tc), FClobbersPred(fc) {}
  173. };
  174. /// Results of if-conversion feasibility analysis indexed by basic block
  175. /// number.
  176. std::vector<BBInfo> BBAnalysis;
  177. TargetSchedModel SchedModel;
  178. const TargetLoweringBase *TLI;
  179. const TargetInstrInfo *TII;
  180. const TargetRegisterInfo *TRI;
  181. const MachineBranchProbabilityInfo *MBPI;
  182. MachineRegisterInfo *MRI;
  183. LivePhysRegs Redefs;
  184. bool PreRegAlloc;
  185. bool MadeChange;
  186. int FnNum = -1;
  187. std::function<bool(const MachineFunction &)> PredicateFtor;
  188. public:
  189. static char ID;
  190. IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
  191. : MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
  192. initializeIfConverterPass(*PassRegistry::getPassRegistry());
  193. }
  194. void getAnalysisUsage(AnalysisUsage &AU) const override {
  195. AU.addRequired<MachineBlockFrequencyInfo>();
  196. AU.addRequired<MachineBranchProbabilityInfo>();
  197. MachineFunctionPass::getAnalysisUsage(AU);
  198. }
  199. bool runOnMachineFunction(MachineFunction &MF) override;
  200. MachineFunctionProperties getRequiredProperties() const override {
  201. return MachineFunctionProperties().set(
  202. MachineFunctionProperties::Property::NoVRegs);
  203. }
  204. private:
  205. bool reverseBranchCondition(BBInfo &BBI) const;
  206. bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
  207. BranchProbability Prediction) const;
  208. bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
  209. bool FalseBranch, unsigned &Dups,
  210. BranchProbability Prediction) const;
  211. bool CountDuplicatedInstructions(
  212. MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
  213. MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
  214. unsigned &Dups1, unsigned &Dups2,
  215. MachineBasicBlock &TBB, MachineBasicBlock &FBB,
  216. bool SkipUnconditionalBranches) const;
  217. bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
  218. unsigned &Dups1, unsigned &Dups2,
  219. BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
  220. bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
  221. unsigned &Dups1, unsigned &Dups2,
  222. BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
  223. void AnalyzeBranches(BBInfo &BBI);
  224. void ScanInstructions(BBInfo &BBI,
  225. MachineBasicBlock::iterator &Begin,
  226. MachineBasicBlock::iterator &End,
  227. bool BranchUnpredicable = false) const;
  228. bool RescanInstructions(
  229. MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
  230. MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
  231. BBInfo &TrueBBI, BBInfo &FalseBBI) const;
  232. void AnalyzeBlock(MachineBasicBlock &MBB,
  233. std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
  234. bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Pred,
  235. bool isTriangle = false, bool RevBranch = false,
  236. bool hasCommonTail = false);
  237. void AnalyzeBlocks(MachineFunction &MF,
  238. std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
  239. void InvalidatePreds(MachineBasicBlock &MBB);
  240. bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
  241. bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
  242. bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
  243. unsigned NumDups1, unsigned NumDups2,
  244. bool TClobbersPred, bool FClobbersPred,
  245. bool RemoveBranch, bool MergeAddEdges);
  246. bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
  247. unsigned NumDups1, unsigned NumDups2,
  248. bool TClobbers, bool FClobbers);
  249. bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
  250. unsigned NumDups1, unsigned NumDups2,
  251. bool TClobbers, bool FClobbers);
  252. void PredicateBlock(BBInfo &BBI,
  253. MachineBasicBlock::iterator E,
  254. SmallVectorImpl<MachineOperand> &Cond,
  255. SmallSet<unsigned, 4> *LaterRedefs = nullptr);
  256. void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
  257. SmallVectorImpl<MachineOperand> &Cond,
  258. bool IgnoreBr = false);
  259. void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
  260. bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
  261. unsigned Cycle, unsigned Extra,
  262. BranchProbability Prediction) const {
  263. return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
  264. Prediction);
  265. }
  266. bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB,
  267. unsigned TCycle, unsigned TExtra,
  268. MachineBasicBlock &FBB,
  269. unsigned FCycle, unsigned FExtra,
  270. BranchProbability Prediction) const {
  271. return TCycle > 0 && FCycle > 0 &&
  272. TII->isProfitableToIfCvt(TBB, TCycle, TExtra, FBB, FCycle, FExtra,
  273. Prediction);
  274. }
  275. /// Returns true if Block ends without a terminator.
  276. bool blockAlwaysFallThrough(BBInfo &BBI) const {
  277. return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
  278. }
  279. /// Used to sort if-conversion candidates.
  280. static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
  281. const std::unique_ptr<IfcvtToken> &C2) {
  282. int Incr1 = (C1->Kind == ICDiamond)
  283. ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
  284. int Incr2 = (C2->Kind == ICDiamond)
  285. ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
  286. if (Incr1 > Incr2)
  287. return true;
  288. else if (Incr1 == Incr2) {
  289. // Favors subsumption.
  290. if (!C1->NeedSubsumption && C2->NeedSubsumption)
  291. return true;
  292. else if (C1->NeedSubsumption == C2->NeedSubsumption) {
  293. // Favors diamond over triangle, etc.
  294. if ((unsigned)C1->Kind < (unsigned)C2->Kind)
  295. return true;
  296. else if (C1->Kind == C2->Kind)
  297. return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
  298. }
  299. }
  300. return false;
  301. }
  302. };
  303. } // end anonymous namespace
  304. char IfConverter::ID = 0;
  305. char &llvm::IfConverterID = IfConverter::ID;
  306. INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
  307. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  308. INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
  309. bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
  310. if (skipFunction(MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
  311. return false;
  312. const TargetSubtargetInfo &ST = MF.getSubtarget();
  313. TLI = ST.getTargetLowering();
  314. TII = ST.getInstrInfo();
  315. TRI = ST.getRegisterInfo();
  316. BranchFolder::MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
  317. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  318. MRI = &MF.getRegInfo();
  319. SchedModel.init(&ST);
  320. if (!TII) return false;
  321. PreRegAlloc = MRI->isSSA();
  322. bool BFChange = false;
  323. if (!PreRegAlloc) {
  324. // Tail merge tend to expose more if-conversion opportunities.
  325. BranchFolder BF(true, false, MBFI, *MBPI);
  326. BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo(),
  327. getAnalysisIfAvailable<MachineModuleInfo>());
  328. }
  329. LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
  330. << MF.getName() << "\'");
  331. if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
  332. LLVM_DEBUG(dbgs() << " skipped\n");
  333. return false;
  334. }
  335. LLVM_DEBUG(dbgs() << "\n");
  336. MF.RenumberBlocks();
  337. BBAnalysis.resize(MF.getNumBlockIDs());
  338. std::vector<std::unique_ptr<IfcvtToken>> Tokens;
  339. MadeChange = false;
  340. unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
  341. NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
  342. while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
  343. // Do an initial analysis for each basic block and find all the potential
  344. // candidates to perform if-conversion.
  345. bool Change = false;
  346. AnalyzeBlocks(MF, Tokens);
  347. while (!Tokens.empty()) {
  348. std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
  349. Tokens.pop_back();
  350. BBInfo &BBI = Token->BBI;
  351. IfcvtKind Kind = Token->Kind;
  352. unsigned NumDups = Token->NumDups;
  353. unsigned NumDups2 = Token->NumDups2;
  354. // If the block has been evicted out of the queue or it has already been
  355. // marked dead (due to it being predicated), then skip it.
  356. if (BBI.IsDone)
  357. BBI.IsEnqueued = false;
  358. if (!BBI.IsEnqueued)
  359. continue;
  360. BBI.IsEnqueued = false;
  361. bool RetVal = false;
  362. switch (Kind) {
  363. default: llvm_unreachable("Unexpected!");
  364. case ICSimple:
  365. case ICSimpleFalse: {
  366. bool isFalse = Kind == ICSimpleFalse;
  367. if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
  368. LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
  369. << (Kind == ICSimpleFalse ? " false" : "")
  370. << "): " << printMBBReference(*BBI.BB) << " ("
  371. << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
  372. : BBI.TrueBB->getNumber())
  373. << ") ");
  374. RetVal = IfConvertSimple(BBI, Kind);
  375. LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  376. if (RetVal) {
  377. if (isFalse) ++NumSimpleFalse;
  378. else ++NumSimple;
  379. }
  380. break;
  381. }
  382. case ICTriangle:
  383. case ICTriangleRev:
  384. case ICTriangleFalse:
  385. case ICTriangleFRev: {
  386. bool isFalse = Kind == ICTriangleFalse;
  387. bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
  388. if (DisableTriangle && !isFalse && !isRev) break;
  389. if (DisableTriangleR && !isFalse && isRev) break;
  390. if (DisableTriangleF && isFalse && !isRev) break;
  391. if (DisableTriangleFR && isFalse && isRev) break;
  392. LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
  393. if (isFalse)
  394. LLVM_DEBUG(dbgs() << " false");
  395. if (isRev)
  396. LLVM_DEBUG(dbgs() << " rev");
  397. LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
  398. << " (T:" << BBI.TrueBB->getNumber()
  399. << ",F:" << BBI.FalseBB->getNumber() << ") ");
  400. RetVal = IfConvertTriangle(BBI, Kind);
  401. LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  402. if (RetVal) {
  403. if (isFalse) {
  404. if (isRev) ++NumTriangleFRev;
  405. else ++NumTriangleFalse;
  406. } else {
  407. if (isRev) ++NumTriangleRev;
  408. else ++NumTriangle;
  409. }
  410. }
  411. break;
  412. }
  413. case ICDiamond:
  414. if (DisableDiamond) break;
  415. LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
  416. << " (T:" << BBI.TrueBB->getNumber()
  417. << ",F:" << BBI.FalseBB->getNumber() << ") ");
  418. RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
  419. Token->TClobbersPred,
  420. Token->FClobbersPred);
  421. LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  422. if (RetVal) ++NumDiamonds;
  423. break;
  424. case ICForkedDiamond:
  425. if (DisableForkedDiamond) break;
  426. LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
  427. << printMBBReference(*BBI.BB)
  428. << " (T:" << BBI.TrueBB->getNumber()
  429. << ",F:" << BBI.FalseBB->getNumber() << ") ");
  430. RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
  431. Token->TClobbersPred,
  432. Token->FClobbersPred);
  433. LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
  434. if (RetVal) ++NumForkedDiamonds;
  435. break;
  436. }
  437. if (RetVal && MRI->tracksLiveness())
  438. recomputeLivenessFlags(*BBI.BB);
  439. Change |= RetVal;
  440. NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
  441. NumTriangleFalse + NumTriangleFRev + NumDiamonds;
  442. if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
  443. break;
  444. }
  445. if (!Change)
  446. break;
  447. MadeChange |= Change;
  448. }
  449. Tokens.clear();
  450. BBAnalysis.clear();
  451. if (MadeChange && IfCvtBranchFold) {
  452. BranchFolder BF(false, false, MBFI, *MBPI);
  453. BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
  454. getAnalysisIfAvailable<MachineModuleInfo>());
  455. }
  456. MadeChange |= BFChange;
  457. return MadeChange;
  458. }
  459. /// BB has a fallthrough. Find its 'false' successor given its 'true' successor.
  460. static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
  461. MachineBasicBlock *TrueBB) {
  462. for (MachineBasicBlock *SuccBB : BB->successors()) {
  463. if (SuccBB != TrueBB)
  464. return SuccBB;
  465. }
  466. return nullptr;
  467. }
  468. /// Reverse the condition of the end of the block branch. Swap block's 'true'
  469. /// and 'false' successors.
  470. bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
  471. DebugLoc dl; // FIXME: this is nowhere
  472. if (!TII->reverseBranchCondition(BBI.BrCond)) {
  473. TII->removeBranch(*BBI.BB);
  474. TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
  475. std::swap(BBI.TrueBB, BBI.FalseBB);
  476. return true;
  477. }
  478. return false;
  479. }
  480. /// Returns the next block in the function blocks ordering. If it is the end,
  481. /// returns NULL.
  482. static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
  483. MachineFunction::iterator I = MBB.getIterator();
  484. MachineFunction::iterator E = MBB.getParent()->end();
  485. if (++I == E)
  486. return nullptr;
  487. return &*I;
  488. }
  489. /// Returns true if the 'true' block (along with its predecessor) forms a valid
  490. /// simple shape for ifcvt. It also returns the number of instructions that the
  491. /// ifcvt would need to duplicate if performed in Dups.
  492. bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
  493. BranchProbability Prediction) const {
  494. Dups = 0;
  495. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
  496. return false;
  497. if (TrueBBI.IsBrAnalyzable)
  498. return false;
  499. if (TrueBBI.BB->pred_size() > 1) {
  500. if (TrueBBI.CannotBeCopied ||
  501. !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
  502. Prediction))
  503. return false;
  504. Dups = TrueBBI.NonPredSize;
  505. }
  506. return true;
  507. }
  508. /// Returns true if the 'true' and 'false' blocks (along with their common
  509. /// predecessor) forms a valid triangle shape for ifcvt. If 'FalseBranch' is
  510. /// true, it checks if 'true' block's false branch branches to the 'false' block
  511. /// rather than the other way around. It also returns the number of instructions
  512. /// that the ifcvt would need to duplicate if performed in 'Dups'.
  513. bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
  514. bool FalseBranch, unsigned &Dups,
  515. BranchProbability Prediction) const {
  516. Dups = 0;
  517. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
  518. return false;
  519. if (TrueBBI.BB->pred_size() > 1) {
  520. if (TrueBBI.CannotBeCopied)
  521. return false;
  522. unsigned Size = TrueBBI.NonPredSize;
  523. if (TrueBBI.IsBrAnalyzable) {
  524. if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
  525. // Ends with an unconditional branch. It will be removed.
  526. --Size;
  527. else {
  528. MachineBasicBlock *FExit = FalseBranch
  529. ? TrueBBI.TrueBB : TrueBBI.FalseBB;
  530. if (FExit)
  531. // Require a conditional branch
  532. ++Size;
  533. }
  534. }
  535. if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
  536. return false;
  537. Dups = Size;
  538. }
  539. MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
  540. if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
  541. MachineFunction::iterator I = TrueBBI.BB->getIterator();
  542. if (++I == TrueBBI.BB->getParent()->end())
  543. return false;
  544. TExit = &*I;
  545. }
  546. return TExit && TExit == FalseBBI.BB;
  547. }
  548. /// Count duplicated instructions and move the iterators to show where they
  549. /// are.
  550. /// @param TIB True Iterator Begin
  551. /// @param FIB False Iterator Begin
  552. /// These two iterators initially point to the first instruction of the two
  553. /// blocks, and finally point to the first non-shared instruction.
  554. /// @param TIE True Iterator End
  555. /// @param FIE False Iterator End
  556. /// These two iterators initially point to End() for the two blocks() and
  557. /// finally point to the first shared instruction in the tail.
  558. /// Upon return [TIB, TIE), and [FIB, FIE) mark the un-duplicated portions of
  559. /// two blocks.
  560. /// @param Dups1 count of duplicated instructions at the beginning of the 2
  561. /// blocks.
  562. /// @param Dups2 count of duplicated instructions at the end of the 2 blocks.
  563. /// @param SkipUnconditionalBranches if true, Don't make sure that
  564. /// unconditional branches at the end of the blocks are the same. True is
  565. /// passed when the blocks are analyzable to allow for fallthrough to be
  566. /// handled.
  567. /// @return false if the shared portion prevents if conversion.
  568. bool IfConverter::CountDuplicatedInstructions(
  569. MachineBasicBlock::iterator &TIB,
  570. MachineBasicBlock::iterator &FIB,
  571. MachineBasicBlock::iterator &TIE,
  572. MachineBasicBlock::iterator &FIE,
  573. unsigned &Dups1, unsigned &Dups2,
  574. MachineBasicBlock &TBB, MachineBasicBlock &FBB,
  575. bool SkipUnconditionalBranches) const {
  576. while (TIB != TIE && FIB != FIE) {
  577. // Skip dbg_value instructions. These do not count.
  578. TIB = skipDebugInstructionsForward(TIB, TIE);
  579. FIB = skipDebugInstructionsForward(FIB, FIE);
  580. if (TIB == TIE || FIB == FIE)
  581. break;
  582. if (!TIB->isIdenticalTo(*FIB))
  583. break;
  584. // A pred-clobbering instruction in the shared portion prevents
  585. // if-conversion.
  586. std::vector<MachineOperand> PredDefs;
  587. if (TII->DefinesPredicate(*TIB, PredDefs))
  588. return false;
  589. // If we get all the way to the branch instructions, don't count them.
  590. if (!TIB->isBranch())
  591. ++Dups1;
  592. ++TIB;
  593. ++FIB;
  594. }
  595. // Check for already containing all of the block.
  596. if (TIB == TIE || FIB == FIE)
  597. return true;
  598. // Now, in preparation for counting duplicate instructions at the ends of the
  599. // blocks, switch to reverse_iterators. Note that getReverse() returns an
  600. // iterator that points to the same instruction, unlike std::reverse_iterator.
  601. // We have to do our own shifting so that we get the same range.
  602. MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
  603. MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
  604. const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
  605. const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
  606. if (!TBB.succ_empty() || !FBB.succ_empty()) {
  607. if (SkipUnconditionalBranches) {
  608. while (RTIE != RTIB && RTIE->isUnconditionalBranch())
  609. ++RTIE;
  610. while (RFIE != RFIB && RFIE->isUnconditionalBranch())
  611. ++RFIE;
  612. }
  613. }
  614. // Count duplicate instructions at the ends of the blocks.
  615. while (RTIE != RTIB && RFIE != RFIB) {
  616. // Skip dbg_value instructions. These do not count.
  617. // Note that these are reverse iterators going forward.
  618. RTIE = skipDebugInstructionsForward(RTIE, RTIB);
  619. RFIE = skipDebugInstructionsForward(RFIE, RFIB);
  620. if (RTIE == RTIB || RFIE == RFIB)
  621. break;
  622. if (!RTIE->isIdenticalTo(*RFIE))
  623. break;
  624. // We have to verify that any branch instructions are the same, and then we
  625. // don't count them toward the # of duplicate instructions.
  626. if (!RTIE->isBranch())
  627. ++Dups2;
  628. ++RTIE;
  629. ++RFIE;
  630. }
  631. TIE = std::next(RTIE.getReverse());
  632. FIE = std::next(RFIE.getReverse());
  633. return true;
  634. }
  635. /// RescanInstructions - Run ScanInstructions on a pair of blocks.
  636. /// @param TIB - True Iterator Begin, points to first non-shared instruction
  637. /// @param FIB - False Iterator Begin, points to first non-shared instruction
  638. /// @param TIE - True Iterator End, points past last non-shared instruction
  639. /// @param FIE - False Iterator End, points past last non-shared instruction
  640. /// @param TrueBBI - BBInfo to update for the true block.
  641. /// @param FalseBBI - BBInfo to update for the false block.
  642. /// @returns - false if either block cannot be predicated or if both blocks end
  643. /// with a predicate-clobbering instruction.
  644. bool IfConverter::RescanInstructions(
  645. MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
  646. MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
  647. BBInfo &TrueBBI, BBInfo &FalseBBI) const {
  648. bool BranchUnpredicable = true;
  649. TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
  650. ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
  651. if (TrueBBI.IsUnpredicable)
  652. return false;
  653. ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
  654. if (FalseBBI.IsUnpredicable)
  655. return false;
  656. if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
  657. return false;
  658. return true;
  659. }
  660. #ifndef NDEBUG
  661. static void verifySameBranchInstructions(
  662. MachineBasicBlock *MBB1,
  663. MachineBasicBlock *MBB2) {
  664. const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
  665. const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
  666. MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
  667. MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
  668. while (E1 != B1 && E2 != B2) {
  669. skipDebugInstructionsForward(E1, B1);
  670. skipDebugInstructionsForward(E2, B2);
  671. if (E1 == B1 && E2 == B2)
  672. break;
  673. if (E1 == B1) {
  674. assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
  675. break;
  676. }
  677. if (E2 == B2) {
  678. assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
  679. break;
  680. }
  681. if (E1->isBranch() || E2->isBranch())
  682. assert(E1->isIdenticalTo(*E2) &&
  683. "Branch mis-match, branch instructions don't match.");
  684. else
  685. break;
  686. ++E1;
  687. ++E2;
  688. }
  689. }
  690. #endif
  691. /// ValidForkedDiamond - Returns true if the 'true' and 'false' blocks (along
  692. /// with their common predecessor) form a diamond if a common tail block is
  693. /// extracted.
  694. /// While not strictly a diamond, this pattern would form a diamond if
  695. /// tail-merging had merged the shared tails.
  696. /// EBB
  697. /// _/ \_
  698. /// | |
  699. /// TBB FBB
  700. /// / \ / \
  701. /// FalseBB TrueBB FalseBB
  702. /// Currently only handles analyzable branches.
  703. /// Specifically excludes actual diamonds to avoid overlap.
  704. bool IfConverter::ValidForkedDiamond(
  705. BBInfo &TrueBBI, BBInfo &FalseBBI,
  706. unsigned &Dups1, unsigned &Dups2,
  707. BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
  708. Dups1 = Dups2 = 0;
  709. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
  710. FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
  711. return false;
  712. if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
  713. return false;
  714. // Don't IfConvert blocks that can't be folded into their predecessor.
  715. if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
  716. return false;
  717. // This function is specifically looking for conditional tails, as
  718. // unconditional tails are already handled by the standard diamond case.
  719. if (TrueBBI.BrCond.size() == 0 ||
  720. FalseBBI.BrCond.size() == 0)
  721. return false;
  722. MachineBasicBlock *TT = TrueBBI.TrueBB;
  723. MachineBasicBlock *TF = TrueBBI.FalseBB;
  724. MachineBasicBlock *FT = FalseBBI.TrueBB;
  725. MachineBasicBlock *FF = FalseBBI.FalseBB;
  726. if (!TT)
  727. TT = getNextBlock(*TrueBBI.BB);
  728. if (!TF)
  729. TF = getNextBlock(*TrueBBI.BB);
  730. if (!FT)
  731. FT = getNextBlock(*FalseBBI.BB);
  732. if (!FF)
  733. FF = getNextBlock(*FalseBBI.BB);
  734. if (!TT || !TF)
  735. return false;
  736. // Check successors. If they don't match, bail.
  737. if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
  738. return false;
  739. bool FalseReversed = false;
  740. if (TF == FT && TT == FF) {
  741. // If the branches are opposing, but we can't reverse, don't do it.
  742. if (!FalseBBI.IsBrReversible)
  743. return false;
  744. FalseReversed = true;
  745. reverseBranchCondition(FalseBBI);
  746. }
  747. auto UnReverseOnExit = make_scope_exit([&]() {
  748. if (FalseReversed)
  749. reverseBranchCondition(FalseBBI);
  750. });
  751. // Count duplicate instructions at the beginning of the true and false blocks.
  752. MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
  753. MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
  754. MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
  755. MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
  756. if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
  757. *TrueBBI.BB, *FalseBBI.BB,
  758. /* SkipUnconditionalBranches */ true))
  759. return false;
  760. TrueBBICalc.BB = TrueBBI.BB;
  761. FalseBBICalc.BB = FalseBBI.BB;
  762. if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
  763. return false;
  764. // The size is used to decide whether to if-convert, and the shared portions
  765. // are subtracted off. Because of the subtraction, we just use the size that
  766. // was calculated by the original ScanInstructions, as it is correct.
  767. TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
  768. FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
  769. return true;
  770. }
  771. /// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
  772. /// with their common predecessor) forms a valid diamond shape for ifcvt.
  773. bool IfConverter::ValidDiamond(
  774. BBInfo &TrueBBI, BBInfo &FalseBBI,
  775. unsigned &Dups1, unsigned &Dups2,
  776. BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
  777. Dups1 = Dups2 = 0;
  778. if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
  779. FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
  780. return false;
  781. MachineBasicBlock *TT = TrueBBI.TrueBB;
  782. MachineBasicBlock *FT = FalseBBI.TrueBB;
  783. if (!TT && blockAlwaysFallThrough(TrueBBI))
  784. TT = getNextBlock(*TrueBBI.BB);
  785. if (!FT && blockAlwaysFallThrough(FalseBBI))
  786. FT = getNextBlock(*FalseBBI.BB);
  787. if (TT != FT)
  788. return false;
  789. if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
  790. return false;
  791. if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
  792. return false;
  793. // FIXME: Allow true block to have an early exit?
  794. if (TrueBBI.FalseBB || FalseBBI.FalseBB)
  795. return false;
  796. // Count duplicate instructions at the beginning and end of the true and
  797. // false blocks.
  798. // Skip unconditional branches only if we are considering an analyzable
  799. // diamond. Otherwise the branches must be the same.
  800. bool SkipUnconditionalBranches =
  801. TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
  802. MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
  803. MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
  804. MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
  805. MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
  806. if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
  807. *TrueBBI.BB, *FalseBBI.BB,
  808. SkipUnconditionalBranches))
  809. return false;
  810. TrueBBICalc.BB = TrueBBI.BB;
  811. FalseBBICalc.BB = FalseBBI.BB;
  812. if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
  813. return false;
  814. // The size is used to decide whether to if-convert, and the shared portions
  815. // are subtracted off. Because of the subtraction, we just use the size that
  816. // was calculated by the original ScanInstructions, as it is correct.
  817. TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
  818. FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
  819. return true;
  820. }
  821. /// AnalyzeBranches - Look at the branches at the end of a block to determine if
  822. /// the block is predicable.
  823. void IfConverter::AnalyzeBranches(BBInfo &BBI) {
  824. if (BBI.IsDone)
  825. return;
  826. BBI.TrueBB = BBI.FalseBB = nullptr;
  827. BBI.BrCond.clear();
  828. BBI.IsBrAnalyzable =
  829. !TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
  830. SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  831. BBI.IsBrReversible = (RevCond.size() == 0) ||
  832. !TII->reverseBranchCondition(RevCond);
  833. BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
  834. if (BBI.BrCond.size()) {
  835. // No false branch. This BB must end with a conditional branch and a
  836. // fallthrough.
  837. if (!BBI.FalseBB)
  838. BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
  839. if (!BBI.FalseBB) {
  840. // Malformed bcc? True and false blocks are the same?
  841. BBI.IsUnpredicable = true;
  842. }
  843. }
  844. }
  845. /// ScanInstructions - Scan all the instructions in the block to determine if
  846. /// the block is predicable. In most cases, that means all the instructions
  847. /// in the block are isPredicable(). Also checks if the block contains any
  848. /// instruction which can clobber a predicate (e.g. condition code register).
  849. /// If so, the block is not predicable unless it's the last instruction.
  850. void IfConverter::ScanInstructions(BBInfo &BBI,
  851. MachineBasicBlock::iterator &Begin,
  852. MachineBasicBlock::iterator &End,
  853. bool BranchUnpredicable) const {
  854. if (BBI.IsDone || BBI.IsUnpredicable)
  855. return;
  856. bool AlreadyPredicated = !BBI.Predicate.empty();
  857. BBI.NonPredSize = 0;
  858. BBI.ExtraCost = 0;
  859. BBI.ExtraCost2 = 0;
  860. BBI.ClobbersPred = false;
  861. for (MachineInstr &MI : make_range(Begin, End)) {
  862. if (MI.isDebugInstr())
  863. continue;
  864. // It's unsafe to duplicate convergent instructions in this context, so set
  865. // BBI.CannotBeCopied to true if MI is convergent. To see why, consider the
  866. // following CFG, which is subject to our "simple" transformation.
  867. //
  868. // BB0 // if (c1) goto BB1; else goto BB2;
  869. // / \
  870. // BB1 |
  871. // | BB2 // if (c2) goto TBB; else goto FBB;
  872. // | / |
  873. // | / |
  874. // TBB |
  875. // | |
  876. // | FBB
  877. // |
  878. // exit
  879. //
  880. // Suppose we want to move TBB's contents up into BB1 and BB2 (in BB1 they'd
  881. // be unconditional, and in BB2, they'd be predicated upon c2), and suppose
  882. // TBB contains a convergent instruction. This is safe iff doing so does
  883. // not add a control-flow dependency to the convergent instruction -- i.e.,
  884. // it's safe iff the set of control flows that leads us to the convergent
  885. // instruction does not get smaller after the transformation.
  886. //
  887. // Originally we executed TBB if c1 || c2. After the transformation, there
  888. // are two copies of TBB's instructions. We get to the first if c1, and we
  889. // get to the second if !c1 && c2.
  890. //
  891. // There are clearly fewer ways to satisfy the condition "c1" than
  892. // "c1 || c2". Since we've shrunk the set of control flows which lead to
  893. // our convergent instruction, the transformation is unsafe.
  894. if (MI.isNotDuplicable() || MI.isConvergent())
  895. BBI.CannotBeCopied = true;
  896. bool isPredicated = TII->isPredicated(MI);
  897. bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
  898. if (BranchUnpredicable && MI.isBranch()) {
  899. BBI.IsUnpredicable = true;
  900. return;
  901. }
  902. // A conditional branch is not predicable, but it may be eliminated.
  903. if (isCondBr)
  904. continue;
  905. if (!isPredicated) {
  906. BBI.NonPredSize++;
  907. unsigned ExtraPredCost = TII->getPredicationCost(MI);
  908. unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
  909. if (NumCycles > 1)
  910. BBI.ExtraCost += NumCycles-1;
  911. BBI.ExtraCost2 += ExtraPredCost;
  912. } else if (!AlreadyPredicated) {
  913. // FIXME: This instruction is already predicated before the
  914. // if-conversion pass. It's probably something like a conditional move.
  915. // Mark this block unpredicable for now.
  916. BBI.IsUnpredicable = true;
  917. return;
  918. }
  919. if (BBI.ClobbersPred && !isPredicated) {
  920. // Predicate modification instruction should end the block (except for
  921. // already predicated instructions and end of block branches).
  922. // Predicate may have been modified, the subsequent (currently)
  923. // unpredicated instructions cannot be correctly predicated.
  924. BBI.IsUnpredicable = true;
  925. return;
  926. }
  927. // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
  928. // still potentially predicable.
  929. std::vector<MachineOperand> PredDefs;
  930. if (TII->DefinesPredicate(MI, PredDefs))
  931. BBI.ClobbersPred = true;
  932. if (!TII->isPredicable(MI)) {
  933. BBI.IsUnpredicable = true;
  934. return;
  935. }
  936. }
  937. }
  938. /// Determine if the block is a suitable candidate to be predicated by the
  939. /// specified predicate.
  940. /// @param BBI BBInfo for the block to check
  941. /// @param Pred Predicate array for the branch that leads to BBI
  942. /// @param isTriangle true if the Analysis is for a triangle
  943. /// @param RevBranch true if Reverse(Pred) leads to BBI (e.g. BBI is the false
  944. /// case
  945. /// @param hasCommonTail true if BBI shares a tail with a sibling block that
  946. /// contains any instruction that would make the block unpredicable.
  947. bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
  948. SmallVectorImpl<MachineOperand> &Pred,
  949. bool isTriangle, bool RevBranch,
  950. bool hasCommonTail) {
  951. // If the block is dead or unpredicable, then it cannot be predicated.
  952. // Two blocks may share a common unpredicable tail, but this doesn't prevent
  953. // them from being if-converted. The non-shared portion is assumed to have
  954. // been checked
  955. if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
  956. return false;
  957. // If it is already predicated but we couldn't analyze its terminator, the
  958. // latter might fallthrough, but we can't determine where to.
  959. // Conservatively avoid if-converting again.
  960. if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
  961. return false;
  962. // If it is already predicated, check if the new predicate subsumes
  963. // its predicate.
  964. if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
  965. return false;
  966. if (!hasCommonTail && BBI.BrCond.size()) {
  967. if (!isTriangle)
  968. return false;
  969. // Test predicate subsumption.
  970. SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
  971. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  972. if (RevBranch) {
  973. if (TII->reverseBranchCondition(Cond))
  974. return false;
  975. }
  976. if (TII->reverseBranchCondition(RevPred) ||
  977. !TII->SubsumesPredicate(Cond, RevPred))
  978. return false;
  979. }
  980. return true;
  981. }
  982. /// Analyze the structure of the sub-CFG starting from the specified block.
  983. /// Record its successors and whether it looks like an if-conversion candidate.
  984. void IfConverter::AnalyzeBlock(
  985. MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
  986. struct BBState {
  987. BBState(MachineBasicBlock &MBB) : MBB(&MBB), SuccsAnalyzed(false) {}
  988. MachineBasicBlock *MBB;
  989. /// This flag is true if MBB's successors have been analyzed.
  990. bool SuccsAnalyzed;
  991. };
  992. // Push MBB to the stack.
  993. SmallVector<BBState, 16> BBStack(1, MBB);
  994. while (!BBStack.empty()) {
  995. BBState &State = BBStack.back();
  996. MachineBasicBlock *BB = State.MBB;
  997. BBInfo &BBI = BBAnalysis[BB->getNumber()];
  998. if (!State.SuccsAnalyzed) {
  999. if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
  1000. BBStack.pop_back();
  1001. continue;
  1002. }
  1003. BBI.BB = BB;
  1004. BBI.IsBeingAnalyzed = true;
  1005. AnalyzeBranches(BBI);
  1006. MachineBasicBlock::iterator Begin = BBI.BB->begin();
  1007. MachineBasicBlock::iterator End = BBI.BB->end();
  1008. ScanInstructions(BBI, Begin, End);
  1009. // Unanalyzable or ends with fallthrough or unconditional branch, or if is
  1010. // not considered for ifcvt anymore.
  1011. if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
  1012. BBI.IsBeingAnalyzed = false;
  1013. BBI.IsAnalyzed = true;
  1014. BBStack.pop_back();
  1015. continue;
  1016. }
  1017. // Do not ifcvt if either path is a back edge to the entry block.
  1018. if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
  1019. BBI.IsBeingAnalyzed = false;
  1020. BBI.IsAnalyzed = true;
  1021. BBStack.pop_back();
  1022. continue;
  1023. }
  1024. // Do not ifcvt if true and false fallthrough blocks are the same.
  1025. if (!BBI.FalseBB) {
  1026. BBI.IsBeingAnalyzed = false;
  1027. BBI.IsAnalyzed = true;
  1028. BBStack.pop_back();
  1029. continue;
  1030. }
  1031. // Push the False and True blocks to the stack.
  1032. State.SuccsAnalyzed = true;
  1033. BBStack.push_back(*BBI.FalseBB);
  1034. BBStack.push_back(*BBI.TrueBB);
  1035. continue;
  1036. }
  1037. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1038. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1039. if (TrueBBI.IsDone && FalseBBI.IsDone) {
  1040. BBI.IsBeingAnalyzed = false;
  1041. BBI.IsAnalyzed = true;
  1042. BBStack.pop_back();
  1043. continue;
  1044. }
  1045. SmallVector<MachineOperand, 4>
  1046. RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  1047. bool CanRevCond = !TII->reverseBranchCondition(RevCond);
  1048. unsigned Dups = 0;
  1049. unsigned Dups2 = 0;
  1050. bool TNeedSub = !TrueBBI.Predicate.empty();
  1051. bool FNeedSub = !FalseBBI.Predicate.empty();
  1052. bool Enqueued = false;
  1053. BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
  1054. if (CanRevCond) {
  1055. BBInfo TrueBBICalc, FalseBBICalc;
  1056. auto feasibleDiamond = [&]() {
  1057. bool MeetsSize = MeetIfcvtSizeLimit(
  1058. *TrueBBI.BB, (TrueBBICalc.NonPredSize - (Dups + Dups2) +
  1059. TrueBBICalc.ExtraCost), TrueBBICalc.ExtraCost2,
  1060. *FalseBBI.BB, (FalseBBICalc.NonPredSize - (Dups + Dups2) +
  1061. FalseBBICalc.ExtraCost), FalseBBICalc.ExtraCost2,
  1062. Prediction);
  1063. bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
  1064. /* IsTriangle */ false, /* RevCond */ false,
  1065. /* hasCommonTail */ true);
  1066. bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
  1067. /* IsTriangle */ false, /* RevCond */ false,
  1068. /* hasCommonTail */ true);
  1069. return MeetsSize && TrueFeasible && FalseFeasible;
  1070. };
  1071. if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
  1072. TrueBBICalc, FalseBBICalc)) {
  1073. if (feasibleDiamond()) {
  1074. // Diamond:
  1075. // EBB
  1076. // / \_
  1077. // | |
  1078. // TBB FBB
  1079. // \ /
  1080. // TailBB
  1081. // Note TailBB can be empty.
  1082. Tokens.push_back(llvm::make_unique<IfcvtToken>(
  1083. BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
  1084. (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
  1085. Enqueued = true;
  1086. }
  1087. } else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
  1088. TrueBBICalc, FalseBBICalc)) {
  1089. if (feasibleDiamond()) {
  1090. // ForkedDiamond:
  1091. // if TBB and FBB have a common tail that includes their conditional
  1092. // branch instructions, then we can If Convert this pattern.
  1093. // EBB
  1094. // _/ \_
  1095. // | |
  1096. // TBB FBB
  1097. // / \ / \
  1098. // FalseBB TrueBB FalseBB
  1099. //
  1100. Tokens.push_back(llvm::make_unique<IfcvtToken>(
  1101. BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
  1102. (bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
  1103. Enqueued = true;
  1104. }
  1105. }
  1106. }
  1107. if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
  1108. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  1109. TrueBBI.ExtraCost2, Prediction) &&
  1110. FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
  1111. // Triangle:
  1112. // EBB
  1113. // | \_
  1114. // | |
  1115. // | TBB
  1116. // | /
  1117. // FBB
  1118. Tokens.push_back(
  1119. llvm::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
  1120. Enqueued = true;
  1121. }
  1122. if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
  1123. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  1124. TrueBBI.ExtraCost2, Prediction) &&
  1125. FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
  1126. Tokens.push_back(
  1127. llvm::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
  1128. Enqueued = true;
  1129. }
  1130. if (ValidSimple(TrueBBI, Dups, Prediction) &&
  1131. MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
  1132. TrueBBI.ExtraCost2, Prediction) &&
  1133. FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
  1134. // Simple (split, no rejoin):
  1135. // EBB
  1136. // | \_
  1137. // | |
  1138. // | TBB---> exit
  1139. // |
  1140. // FBB
  1141. Tokens.push_back(
  1142. llvm::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
  1143. Enqueued = true;
  1144. }
  1145. if (CanRevCond) {
  1146. // Try the other path...
  1147. if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
  1148. Prediction.getCompl()) &&
  1149. MeetIfcvtSizeLimit(*FalseBBI.BB,
  1150. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  1151. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  1152. FeasibilityAnalysis(FalseBBI, RevCond, true)) {
  1153. Tokens.push_back(llvm::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
  1154. FNeedSub, Dups));
  1155. Enqueued = true;
  1156. }
  1157. if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
  1158. Prediction.getCompl()) &&
  1159. MeetIfcvtSizeLimit(*FalseBBI.BB,
  1160. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  1161. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  1162. FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
  1163. Tokens.push_back(
  1164. llvm::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
  1165. Enqueued = true;
  1166. }
  1167. if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
  1168. MeetIfcvtSizeLimit(*FalseBBI.BB,
  1169. FalseBBI.NonPredSize + FalseBBI.ExtraCost,
  1170. FalseBBI.ExtraCost2, Prediction.getCompl()) &&
  1171. FeasibilityAnalysis(FalseBBI, RevCond)) {
  1172. Tokens.push_back(
  1173. llvm::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
  1174. Enqueued = true;
  1175. }
  1176. }
  1177. BBI.IsEnqueued = Enqueued;
  1178. BBI.IsBeingAnalyzed = false;
  1179. BBI.IsAnalyzed = true;
  1180. BBStack.pop_back();
  1181. }
  1182. }
  1183. /// Analyze all blocks and find entries for all if-conversion candidates.
  1184. void IfConverter::AnalyzeBlocks(
  1185. MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
  1186. for (MachineBasicBlock &MBB : MF)
  1187. AnalyzeBlock(MBB, Tokens);
  1188. // Sort to favor more complex ifcvt scheme.
  1189. std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
  1190. }
  1191. /// Returns true either if ToMBB is the next block after MBB or that all the
  1192. /// intervening blocks are empty (given MBB can fall through to its next block).
  1193. static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
  1194. MachineFunction::iterator PI = MBB.getIterator();
  1195. MachineFunction::iterator I = std::next(PI);
  1196. MachineFunction::iterator TI = ToMBB.getIterator();
  1197. MachineFunction::iterator E = MBB.getParent()->end();
  1198. while (I != TI) {
  1199. // Check isSuccessor to avoid case where the next block is empty, but
  1200. // it's not a successor.
  1201. if (I == E || !I->empty() || !PI->isSuccessor(&*I))
  1202. return false;
  1203. PI = I++;
  1204. }
  1205. // Finally see if the last I is indeed a successor to PI.
  1206. return PI->isSuccessor(&*I);
  1207. }
  1208. /// Invalidate predecessor BB info so it would be re-analyzed to determine if it
  1209. /// can be if-converted. If predecessor is already enqueued, dequeue it!
  1210. void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
  1211. for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
  1212. BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
  1213. if (PBBI.IsDone || PBBI.BB == &MBB)
  1214. continue;
  1215. PBBI.IsAnalyzed = false;
  1216. PBBI.IsEnqueued = false;
  1217. }
  1218. }
  1219. /// Inserts an unconditional branch from \p MBB to \p ToMBB.
  1220. static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
  1221. const TargetInstrInfo *TII) {
  1222. DebugLoc dl; // FIXME: this is nowhere
  1223. SmallVector<MachineOperand, 0> NoCond;
  1224. TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
  1225. }
  1226. /// Behaves like LiveRegUnits::StepForward() but also adds implicit uses to all
  1227. /// values defined in MI which are also live/used by MI.
  1228. static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
  1229. const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
  1230. // Before stepping forward past MI, remember which regs were live
  1231. // before MI. This is needed to set the Undef flag only when reg is
  1232. // dead.
  1233. SparseSet<unsigned> LiveBeforeMI;
  1234. LiveBeforeMI.setUniverse(TRI->getNumRegs());
  1235. for (unsigned Reg : Redefs)
  1236. LiveBeforeMI.insert(Reg);
  1237. SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Clobbers;
  1238. Redefs.stepForward(MI, Clobbers);
  1239. // Now add the implicit uses for each of the clobbered values.
  1240. for (auto Clobber : Clobbers) {
  1241. // FIXME: Const cast here is nasty, but better than making StepForward
  1242. // take a mutable instruction instead of const.
  1243. unsigned Reg = Clobber.first;
  1244. MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
  1245. MachineInstr *OpMI = Op.getParent();
  1246. MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
  1247. if (Op.isRegMask()) {
  1248. // First handle regmasks. They clobber any entries in the mask which
  1249. // means that we need a def for those registers.
  1250. if (LiveBeforeMI.count(Reg))
  1251. MIB.addReg(Reg, RegState::Implicit);
  1252. // We also need to add an implicit def of this register for the later
  1253. // use to read from.
  1254. // For the register allocator to have allocated a register clobbered
  1255. // by the call which is used later, it must be the case that
  1256. // the call doesn't return.
  1257. MIB.addReg(Reg, RegState::Implicit | RegState::Define);
  1258. continue;
  1259. }
  1260. if (LiveBeforeMI.count(Reg))
  1261. MIB.addReg(Reg, RegState::Implicit);
  1262. else {
  1263. bool HasLiveSubReg = false;
  1264. for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
  1265. if (!LiveBeforeMI.count(*S))
  1266. continue;
  1267. HasLiveSubReg = true;
  1268. break;
  1269. }
  1270. if (HasLiveSubReg)
  1271. MIB.addReg(Reg, RegState::Implicit);
  1272. }
  1273. }
  1274. }
  1275. /// If convert a simple (split, no rejoin) sub-CFG.
  1276. bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
  1277. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1278. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1279. BBInfo *CvtBBI = &TrueBBI;
  1280. BBInfo *NextBBI = &FalseBBI;
  1281. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  1282. if (Kind == ICSimpleFalse)
  1283. std::swap(CvtBBI, NextBBI);
  1284. MachineBasicBlock &CvtMBB = *CvtBBI->BB;
  1285. MachineBasicBlock &NextMBB = *NextBBI->BB;
  1286. if (CvtBBI->IsDone ||
  1287. (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
  1288. // Something has changed. It's no longer safe to predicate this block.
  1289. BBI.IsAnalyzed = false;
  1290. CvtBBI->IsAnalyzed = false;
  1291. return false;
  1292. }
  1293. if (CvtMBB.hasAddressTaken())
  1294. // Conservatively abort if-conversion if BB's address is taken.
  1295. return false;
  1296. if (Kind == ICSimpleFalse)
  1297. if (TII->reverseBranchCondition(Cond))
  1298. llvm_unreachable("Unable to reverse branch condition!");
  1299. Redefs.init(*TRI);
  1300. if (MRI->tracksLiveness()) {
  1301. // Initialize liveins to the first BB. These are potentiall redefined by
  1302. // predicated instructions.
  1303. Redefs.addLiveIns(CvtMBB);
  1304. Redefs.addLiveIns(NextMBB);
  1305. }
  1306. // Remove the branches from the entry so we can add the contents of the true
  1307. // block to it.
  1308. BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
  1309. if (CvtMBB.pred_size() > 1) {
  1310. // Copy instructions in the true block, predicate them, and add them to
  1311. // the entry block.
  1312. CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
  1313. // Keep the CFG updated.
  1314. BBI.BB->removeSuccessor(&CvtMBB, true);
  1315. } else {
  1316. // Predicate the instructions in the true block.
  1317. PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
  1318. // Merge converted block into entry block. The BB to Cvt edge is removed
  1319. // by MergeBlocks.
  1320. MergeBlocks(BBI, *CvtBBI);
  1321. }
  1322. bool IterIfcvt = true;
  1323. if (!canFallThroughTo(*BBI.BB, NextMBB)) {
  1324. InsertUncondBranch(*BBI.BB, NextMBB, TII);
  1325. BBI.HasFallThrough = false;
  1326. // Now ifcvt'd block will look like this:
  1327. // BB:
  1328. // ...
  1329. // t, f = cmp
  1330. // if t op
  1331. // b BBf
  1332. //
  1333. // We cannot further ifcvt this block because the unconditional branch
  1334. // will have to be predicated on the new condition, that will not be
  1335. // available if cmp executes.
  1336. IterIfcvt = false;
  1337. }
  1338. // Update block info. BB can be iteratively if-converted.
  1339. if (!IterIfcvt)
  1340. BBI.IsDone = true;
  1341. InvalidatePreds(*BBI.BB);
  1342. CvtBBI->IsDone = true;
  1343. // FIXME: Must maintain LiveIns.
  1344. return true;
  1345. }
  1346. /// If convert a triangle sub-CFG.
  1347. bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
  1348. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1349. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1350. BBInfo *CvtBBI = &TrueBBI;
  1351. BBInfo *NextBBI = &FalseBBI;
  1352. DebugLoc dl; // FIXME: this is nowhere
  1353. SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
  1354. if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
  1355. std::swap(CvtBBI, NextBBI);
  1356. MachineBasicBlock &CvtMBB = *CvtBBI->BB;
  1357. MachineBasicBlock &NextMBB = *NextBBI->BB;
  1358. if (CvtBBI->IsDone ||
  1359. (CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
  1360. // Something has changed. It's no longer safe to predicate this block.
  1361. BBI.IsAnalyzed = false;
  1362. CvtBBI->IsAnalyzed = false;
  1363. return false;
  1364. }
  1365. if (CvtMBB.hasAddressTaken())
  1366. // Conservatively abort if-conversion if BB's address is taken.
  1367. return false;
  1368. if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
  1369. if (TII->reverseBranchCondition(Cond))
  1370. llvm_unreachable("Unable to reverse branch condition!");
  1371. if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
  1372. if (reverseBranchCondition(*CvtBBI)) {
  1373. // BB has been changed, modify its predecessors (except for this
  1374. // one) so they don't get ifcvt'ed based on bad intel.
  1375. for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
  1376. if (PBB == BBI.BB)
  1377. continue;
  1378. BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
  1379. if (PBBI.IsEnqueued) {
  1380. PBBI.IsAnalyzed = false;
  1381. PBBI.IsEnqueued = false;
  1382. }
  1383. }
  1384. }
  1385. }
  1386. // Initialize liveins to the first BB. These are potentially redefined by
  1387. // predicated instructions.
  1388. Redefs.init(*TRI);
  1389. if (MRI->tracksLiveness()) {
  1390. Redefs.addLiveIns(CvtMBB);
  1391. Redefs.addLiveIns(NextMBB);
  1392. }
  1393. bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
  1394. BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
  1395. if (HasEarlyExit) {
  1396. // Get probabilities before modifying CvtMBB and BBI.BB.
  1397. CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
  1398. CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
  1399. BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
  1400. BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
  1401. }
  1402. // Remove the branches from the entry so we can add the contents of the true
  1403. // block to it.
  1404. BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
  1405. if (CvtMBB.pred_size() > 1) {
  1406. // Copy instructions in the true block, predicate them, and add them to
  1407. // the entry block.
  1408. CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
  1409. } else {
  1410. // Predicate the 'true' block after removing its branch.
  1411. CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
  1412. PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
  1413. // Now merge the entry of the triangle with the true block.
  1414. MergeBlocks(BBI, *CvtBBI, false);
  1415. }
  1416. // Keep the CFG updated.
  1417. BBI.BB->removeSuccessor(&CvtMBB, true);
  1418. // If 'true' block has a 'false' successor, add an exit branch to it.
  1419. if (HasEarlyExit) {
  1420. SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
  1421. CvtBBI->BrCond.end());
  1422. if (TII->reverseBranchCondition(RevCond))
  1423. llvm_unreachable("Unable to reverse branch condition!");
  1424. // Update the edge probability for both CvtBBI->FalseBB and NextBBI.
  1425. // NewNext = New_Prob(BBI.BB, NextMBB) =
  1426. // Prob(BBI.BB, NextMBB) +
  1427. // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, NextMBB)
  1428. // NewFalse = New_Prob(BBI.BB, CvtBBI->FalseBB) =
  1429. // Prob(BBI.BB, CvtMBB) * Prob(CvtMBB, CvtBBI->FalseBB)
  1430. auto NewTrueBB = getNextBlock(*BBI.BB);
  1431. auto NewNext = BBNext + BBCvt * CvtNext;
  1432. auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
  1433. if (NewTrueBBIter != BBI.BB->succ_end())
  1434. BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
  1435. auto NewFalse = BBCvt * CvtFalse;
  1436. TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
  1437. BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
  1438. }
  1439. // Merge in the 'false' block if the 'false' block has no other
  1440. // predecessors. Otherwise, add an unconditional branch to 'false'.
  1441. bool FalseBBDead = false;
  1442. bool IterIfcvt = true;
  1443. bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
  1444. if (!isFallThrough) {
  1445. // Only merge them if the true block does not fallthrough to the false
  1446. // block. By not merging them, we make it possible to iteratively
  1447. // ifcvt the blocks.
  1448. if (!HasEarlyExit &&
  1449. NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
  1450. !NextMBB.hasAddressTaken()) {
  1451. MergeBlocks(BBI, *NextBBI);
  1452. FalseBBDead = true;
  1453. } else {
  1454. InsertUncondBranch(*BBI.BB, NextMBB, TII);
  1455. BBI.HasFallThrough = false;
  1456. }
  1457. // Mixed predicated and unpredicated code. This cannot be iteratively
  1458. // predicated.
  1459. IterIfcvt = false;
  1460. }
  1461. // Update block info. BB can be iteratively if-converted.
  1462. if (!IterIfcvt)
  1463. BBI.IsDone = true;
  1464. InvalidatePreds(*BBI.BB);
  1465. CvtBBI->IsDone = true;
  1466. if (FalseBBDead)
  1467. NextBBI->IsDone = true;
  1468. // FIXME: Must maintain LiveIns.
  1469. return true;
  1470. }
  1471. /// Common code shared between diamond conversions.
  1472. /// \p BBI, \p TrueBBI, and \p FalseBBI form the diamond shape.
  1473. /// \p NumDups1 - number of shared instructions at the beginning of \p TrueBBI
  1474. /// and FalseBBI
  1475. /// \p NumDups2 - number of shared instructions at the end of \p TrueBBI
  1476. /// and \p FalseBBI
  1477. /// \p RemoveBranch - Remove the common branch of the two blocks before
  1478. /// predicating. Only false for unanalyzable fallthrough
  1479. /// cases. The caller will replace the branch if necessary.
  1480. /// \p MergeAddEdges - Add successor edges when merging blocks. Only false for
  1481. /// unanalyzable fallthrough
  1482. bool IfConverter::IfConvertDiamondCommon(
  1483. BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
  1484. unsigned NumDups1, unsigned NumDups2,
  1485. bool TClobbersPred, bool FClobbersPred,
  1486. bool RemoveBranch, bool MergeAddEdges) {
  1487. if (TrueBBI.IsDone || FalseBBI.IsDone ||
  1488. TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
  1489. // Something has changed. It's no longer safe to predicate these blocks.
  1490. BBI.IsAnalyzed = false;
  1491. TrueBBI.IsAnalyzed = false;
  1492. FalseBBI.IsAnalyzed = false;
  1493. return false;
  1494. }
  1495. if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
  1496. // Conservatively abort if-conversion if either BB has its address taken.
  1497. return false;
  1498. // Put the predicated instructions from the 'true' block before the
  1499. // instructions from the 'false' block, unless the true block would clobber
  1500. // the predicate, in which case, do the opposite.
  1501. BBInfo *BBI1 = &TrueBBI;
  1502. BBInfo *BBI2 = &FalseBBI;
  1503. SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
  1504. if (TII->reverseBranchCondition(RevCond))
  1505. llvm_unreachable("Unable to reverse branch condition!");
  1506. SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
  1507. SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
  1508. // Figure out the more profitable ordering.
  1509. bool DoSwap = false;
  1510. if (TClobbersPred && !FClobbersPred)
  1511. DoSwap = true;
  1512. else if (!TClobbersPred && !FClobbersPred) {
  1513. if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
  1514. DoSwap = true;
  1515. } else if (TClobbersPred && FClobbersPred)
  1516. llvm_unreachable("Predicate info cannot be clobbered by both sides.");
  1517. if (DoSwap) {
  1518. std::swap(BBI1, BBI2);
  1519. std::swap(Cond1, Cond2);
  1520. }
  1521. // Remove the conditional branch from entry to the blocks.
  1522. BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
  1523. MachineBasicBlock &MBB1 = *BBI1->BB;
  1524. MachineBasicBlock &MBB2 = *BBI2->BB;
  1525. // Initialize the Redefs:
  1526. // - BB2 live-in regs need implicit uses before being redefined by BB1
  1527. // instructions.
  1528. // - BB1 live-out regs need implicit uses before being redefined by BB2
  1529. // instructions. We start with BB1 live-ins so we have the live-out regs
  1530. // after tracking the BB1 instructions.
  1531. Redefs.init(*TRI);
  1532. if (MRI->tracksLiveness()) {
  1533. Redefs.addLiveIns(MBB1);
  1534. Redefs.addLiveIns(MBB2);
  1535. }
  1536. // Remove the duplicated instructions at the beginnings of both paths.
  1537. // Skip dbg_value instructions.
  1538. MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr();
  1539. MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr();
  1540. BBI1->NonPredSize -= NumDups1;
  1541. BBI2->NonPredSize -= NumDups1;
  1542. // Skip past the dups on each side separately since there may be
  1543. // differing dbg_value entries. NumDups1 can include a "return"
  1544. // instruction, if it's not marked as "branch".
  1545. for (unsigned i = 0; i < NumDups1; ++DI1) {
  1546. if (DI1 == MBB1.end())
  1547. break;
  1548. if (!DI1->isDebugInstr())
  1549. ++i;
  1550. }
  1551. while (NumDups1 != 0) {
  1552. ++DI2;
  1553. if (DI2 == MBB2.end())
  1554. break;
  1555. if (!DI2->isDebugInstr())
  1556. --NumDups1;
  1557. }
  1558. if (MRI->tracksLiveness()) {
  1559. for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
  1560. SmallVector<std::pair<unsigned, const MachineOperand*>, 4> Dummy;
  1561. Redefs.stepForward(MI, Dummy);
  1562. }
  1563. }
  1564. BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
  1565. MBB2.erase(MBB2.begin(), DI2);
  1566. // The branches have been checked to match, so it is safe to remove the
  1567. // branch in BB1 and rely on the copy in BB2. The complication is that
  1568. // the blocks may end with a return instruction, which may or may not
  1569. // be marked as "branch". If it's not, then it could be included in
  1570. // "dups1", leaving the blocks potentially empty after moving the common
  1571. // duplicates.
  1572. #ifndef NDEBUG
  1573. // Unanalyzable branches must match exactly. Check that now.
  1574. if (!BBI1->IsBrAnalyzable)
  1575. verifySameBranchInstructions(&MBB1, &MBB2);
  1576. #endif
  1577. BBI1->NonPredSize -= TII->removeBranch(*BBI1->BB);
  1578. // Remove duplicated instructions.
  1579. DI1 = MBB1.end();
  1580. for (unsigned i = 0; i != NumDups2; ) {
  1581. // NumDups2 only counted non-dbg_value instructions, so this won't
  1582. // run off the head of the list.
  1583. assert(DI1 != MBB1.begin());
  1584. --DI1;
  1585. // skip dbg_value instructions
  1586. if (!DI1->isDebugInstr())
  1587. ++i;
  1588. }
  1589. MBB1.erase(DI1, MBB1.end());
  1590. DI2 = BBI2->BB->end();
  1591. // The branches have been checked to match. Skip over the branch in the false
  1592. // block so that we don't try to predicate it.
  1593. if (RemoveBranch)
  1594. BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
  1595. else {
  1596. // Make DI2 point to the end of the range where the common "tail"
  1597. // instructions could be found.
  1598. while (DI2 != MBB2.begin()) {
  1599. MachineBasicBlock::iterator Prev = std::prev(DI2);
  1600. if (!Prev->isBranch() && !Prev->isDebugInstr())
  1601. break;
  1602. DI2 = Prev;
  1603. }
  1604. }
  1605. while (NumDups2 != 0) {
  1606. // NumDups2 only counted non-dbg_value instructions, so this won't
  1607. // run off the head of the list.
  1608. assert(DI2 != MBB2.begin());
  1609. --DI2;
  1610. // skip dbg_value instructions
  1611. if (!DI2->isDebugInstr())
  1612. --NumDups2;
  1613. }
  1614. // Remember which registers would later be defined by the false block.
  1615. // This allows us not to predicate instructions in the true block that would
  1616. // later be re-defined. That is, rather than
  1617. // subeq r0, r1, #1
  1618. // addne r0, r1, #1
  1619. // generate:
  1620. // sub r0, r1, #1
  1621. // addne r0, r1, #1
  1622. SmallSet<unsigned, 4> RedefsByFalse;
  1623. SmallSet<unsigned, 4> ExtUses;
  1624. if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
  1625. for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
  1626. if (FI.isDebugInstr())
  1627. continue;
  1628. SmallVector<unsigned, 4> Defs;
  1629. for (const MachineOperand &MO : FI.operands()) {
  1630. if (!MO.isReg())
  1631. continue;
  1632. unsigned Reg = MO.getReg();
  1633. if (!Reg)
  1634. continue;
  1635. if (MO.isDef()) {
  1636. Defs.push_back(Reg);
  1637. } else if (!RedefsByFalse.count(Reg)) {
  1638. // These are defined before ctrl flow reach the 'false' instructions.
  1639. // They cannot be modified by the 'true' instructions.
  1640. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  1641. SubRegs.isValid(); ++SubRegs)
  1642. ExtUses.insert(*SubRegs);
  1643. }
  1644. }
  1645. for (unsigned Reg : Defs) {
  1646. if (!ExtUses.count(Reg)) {
  1647. for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
  1648. SubRegs.isValid(); ++SubRegs)
  1649. RedefsByFalse.insert(*SubRegs);
  1650. }
  1651. }
  1652. }
  1653. }
  1654. // Predicate the 'true' block.
  1655. PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
  1656. // After predicating BBI1, if there is a predicated terminator in BBI1 and
  1657. // a non-predicated in BBI2, then we don't want to predicate the one from
  1658. // BBI2. The reason is that if we merged these blocks, we would end up with
  1659. // two predicated terminators in the same block.
  1660. // Also, if the branches in MBB1 and MBB2 were non-analyzable, then don't
  1661. // predicate them either. They were checked to be identical, and so the
  1662. // same branch would happen regardless of which path was taken.
  1663. if (!MBB2.empty() && (DI2 == MBB2.end())) {
  1664. MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
  1665. MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
  1666. bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
  1667. bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
  1668. if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
  1669. --DI2;
  1670. }
  1671. // Predicate the 'false' block.
  1672. PredicateBlock(*BBI2, DI2, *Cond2);
  1673. // Merge the true block into the entry of the diamond.
  1674. MergeBlocks(BBI, *BBI1, MergeAddEdges);
  1675. MergeBlocks(BBI, *BBI2, MergeAddEdges);
  1676. return true;
  1677. }
  1678. /// If convert an almost-diamond sub-CFG where the true
  1679. /// and false blocks share a common tail.
  1680. bool IfConverter::IfConvertForkedDiamond(
  1681. BBInfo &BBI, IfcvtKind Kind,
  1682. unsigned NumDups1, unsigned NumDups2,
  1683. bool TClobbersPred, bool FClobbersPred) {
  1684. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1685. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1686. // Save the debug location for later.
  1687. DebugLoc dl;
  1688. MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
  1689. if (TIE != TrueBBI.BB->end())
  1690. dl = TIE->getDebugLoc();
  1691. // Removing branches from both blocks is safe, because we have already
  1692. // determined that both blocks have the same branch instructions. The branch
  1693. // will be added back at the end, unpredicated.
  1694. if (!IfConvertDiamondCommon(
  1695. BBI, TrueBBI, FalseBBI,
  1696. NumDups1, NumDups2,
  1697. TClobbersPred, FClobbersPred,
  1698. /* RemoveBranch */ true, /* MergeAddEdges */ true))
  1699. return false;
  1700. // Add back the branch.
  1701. // Debug location saved above when removing the branch from BBI2
  1702. TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
  1703. TrueBBI.BrCond, dl);
  1704. // Update block info.
  1705. BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
  1706. InvalidatePreds(*BBI.BB);
  1707. // FIXME: Must maintain LiveIns.
  1708. return true;
  1709. }
  1710. /// If convert a diamond sub-CFG.
  1711. bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
  1712. unsigned NumDups1, unsigned NumDups2,
  1713. bool TClobbersPred, bool FClobbersPred) {
  1714. BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
  1715. BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
  1716. MachineBasicBlock *TailBB = TrueBBI.TrueBB;
  1717. // True block must fall through or end with an unanalyzable terminator.
  1718. if (!TailBB) {
  1719. if (blockAlwaysFallThrough(TrueBBI))
  1720. TailBB = FalseBBI.TrueBB;
  1721. assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
  1722. }
  1723. if (!IfConvertDiamondCommon(
  1724. BBI, TrueBBI, FalseBBI,
  1725. NumDups1, NumDups2,
  1726. TClobbersPred, FClobbersPred,
  1727. /* RemoveBranch */ TrueBBI.IsBrAnalyzable,
  1728. /* MergeAddEdges */ TailBB == nullptr))
  1729. return false;
  1730. // If the if-converted block falls through or unconditionally branches into
  1731. // the tail block, and the tail block does not have other predecessors, then
  1732. // fold the tail block in as well. Otherwise, unless it falls through to the
  1733. // tail, add a unconditional branch to it.
  1734. if (TailBB) {
  1735. // We need to remove the edges to the true and false blocks manually since
  1736. // we didn't let IfConvertDiamondCommon update the CFG.
  1737. BBI.BB->removeSuccessor(TrueBBI.BB);
  1738. BBI.BB->removeSuccessor(FalseBBI.BB, true);
  1739. BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
  1740. bool CanMergeTail = !TailBBI.HasFallThrough &&
  1741. !TailBBI.BB->hasAddressTaken();
  1742. // The if-converted block can still have a predicated terminator
  1743. // (e.g. a predicated return). If that is the case, we cannot merge
  1744. // it with the tail block.
  1745. MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
  1746. if (TI != BBI.BB->end() && TII->isPredicated(*TI))
  1747. CanMergeTail = false;
  1748. // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
  1749. // check if there are any other predecessors besides those.
  1750. unsigned NumPreds = TailBB->pred_size();
  1751. if (NumPreds > 1)
  1752. CanMergeTail = false;
  1753. else if (NumPreds == 1 && CanMergeTail) {
  1754. MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
  1755. if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
  1756. CanMergeTail = false;
  1757. }
  1758. if (CanMergeTail) {
  1759. MergeBlocks(BBI, TailBBI);
  1760. TailBBI.IsDone = true;
  1761. } else {
  1762. BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
  1763. InsertUncondBranch(*BBI.BB, *TailBB, TII);
  1764. BBI.HasFallThrough = false;
  1765. }
  1766. }
  1767. // Update block info.
  1768. BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
  1769. InvalidatePreds(*BBI.BB);
  1770. // FIXME: Must maintain LiveIns.
  1771. return true;
  1772. }
  1773. static bool MaySpeculate(const MachineInstr &MI,
  1774. SmallSet<unsigned, 4> &LaterRedefs) {
  1775. bool SawStore = true;
  1776. if (!MI.isSafeToMove(nullptr, SawStore))
  1777. return false;
  1778. for (const MachineOperand &MO : MI.operands()) {
  1779. if (!MO.isReg())
  1780. continue;
  1781. unsigned Reg = MO.getReg();
  1782. if (!Reg)
  1783. continue;
  1784. if (MO.isDef() && !LaterRedefs.count(Reg))
  1785. return false;
  1786. }
  1787. return true;
  1788. }
  1789. /// Predicate instructions from the start of the block to the specified end with
  1790. /// the specified condition.
  1791. void IfConverter::PredicateBlock(BBInfo &BBI,
  1792. MachineBasicBlock::iterator E,
  1793. SmallVectorImpl<MachineOperand> &Cond,
  1794. SmallSet<unsigned, 4> *LaterRedefs) {
  1795. bool AnyUnpred = false;
  1796. bool MaySpec = LaterRedefs != nullptr;
  1797. for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
  1798. if (I.isDebugInstr() || TII->isPredicated(I))
  1799. continue;
  1800. // It may be possible not to predicate an instruction if it's the 'true'
  1801. // side of a diamond and the 'false' side may re-define the instruction's
  1802. // defs.
  1803. if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
  1804. AnyUnpred = true;
  1805. continue;
  1806. }
  1807. // If any instruction is predicated, then every instruction after it must
  1808. // be predicated.
  1809. MaySpec = false;
  1810. if (!TII->PredicateInstruction(I, Cond)) {
  1811. #ifndef NDEBUG
  1812. dbgs() << "Unable to predicate " << I << "!\n";
  1813. #endif
  1814. llvm_unreachable(nullptr);
  1815. }
  1816. // If the predicated instruction now redefines a register as the result of
  1817. // if-conversion, add an implicit kill.
  1818. UpdatePredRedefs(I, Redefs);
  1819. }
  1820. BBI.Predicate.append(Cond.begin(), Cond.end());
  1821. BBI.IsAnalyzed = false;
  1822. BBI.NonPredSize = 0;
  1823. ++NumIfConvBBs;
  1824. if (AnyUnpred)
  1825. ++NumUnpred;
  1826. }
  1827. /// Copy and predicate instructions from source BB to the destination block.
  1828. /// Skip end of block branches if IgnoreBr is true.
  1829. void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
  1830. SmallVectorImpl<MachineOperand> &Cond,
  1831. bool IgnoreBr) {
  1832. MachineFunction &MF = *ToBBI.BB->getParent();
  1833. MachineBasicBlock &FromMBB = *FromBBI.BB;
  1834. for (MachineInstr &I : FromMBB) {
  1835. // Do not copy the end of the block branches.
  1836. if (IgnoreBr && I.isBranch())
  1837. break;
  1838. MachineInstr *MI = MF.CloneMachineInstr(&I);
  1839. ToBBI.BB->insert(ToBBI.BB->end(), MI);
  1840. ToBBI.NonPredSize++;
  1841. unsigned ExtraPredCost = TII->getPredicationCost(I);
  1842. unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
  1843. if (NumCycles > 1)
  1844. ToBBI.ExtraCost += NumCycles-1;
  1845. ToBBI.ExtraCost2 += ExtraPredCost;
  1846. if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
  1847. if (!TII->PredicateInstruction(*MI, Cond)) {
  1848. #ifndef NDEBUG
  1849. dbgs() << "Unable to predicate " << I << "!\n";
  1850. #endif
  1851. llvm_unreachable(nullptr);
  1852. }
  1853. }
  1854. // If the predicated instruction now redefines a register as the result of
  1855. // if-conversion, add an implicit kill.
  1856. UpdatePredRedefs(*MI, Redefs);
  1857. }
  1858. if (!IgnoreBr) {
  1859. std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
  1860. FromMBB.succ_end());
  1861. MachineBasicBlock *NBB = getNextBlock(FromMBB);
  1862. MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
  1863. for (MachineBasicBlock *Succ : Succs) {
  1864. // Fallthrough edge can't be transferred.
  1865. if (Succ == FallThrough)
  1866. continue;
  1867. ToBBI.BB->addSuccessor(Succ);
  1868. }
  1869. }
  1870. ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
  1871. ToBBI.Predicate.append(Cond.begin(), Cond.end());
  1872. ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
  1873. ToBBI.IsAnalyzed = false;
  1874. ++NumDupBBs;
  1875. }
  1876. /// Move all instructions from FromBB to the end of ToBB. This will leave
  1877. /// FromBB as an empty block, so remove all of its successor edges except for
  1878. /// the fall-through edge. If AddEdges is true, i.e., when FromBBI's branch is
  1879. /// being moved, add those successor edges to ToBBI and remove the old edge
  1880. /// from ToBBI to FromBBI.
  1881. void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
  1882. MachineBasicBlock &FromMBB = *FromBBI.BB;
  1883. assert(!FromMBB.hasAddressTaken() &&
  1884. "Removing a BB whose address is taken!");
  1885. // In case FromMBB contains terminators (e.g. return instruction),
  1886. // first move the non-terminator instructions, then the terminators.
  1887. MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
  1888. MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
  1889. ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
  1890. // If FromBB has non-predicated terminator we should copy it at the end.
  1891. if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
  1892. ToTI = ToBBI.BB->end();
  1893. ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
  1894. // Force normalizing the successors' probabilities of ToBBI.BB to convert all
  1895. // unknown probabilities into known ones.
  1896. // FIXME: This usage is too tricky and in the future we would like to
  1897. // eliminate all unknown probabilities in MBB.
  1898. if (ToBBI.IsBrAnalyzable)
  1899. ToBBI.BB->normalizeSuccProbs();
  1900. SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.succ_begin(),
  1901. FromMBB.succ_end());
  1902. MachineBasicBlock *NBB = getNextBlock(FromMBB);
  1903. MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
  1904. // The edge probability from ToBBI.BB to FromMBB, which is only needed when
  1905. // AddEdges is true and FromMBB is a successor of ToBBI.BB.
  1906. auto To2FromProb = BranchProbability::getZero();
  1907. if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
  1908. // Remove the old edge but remember the edge probability so we can calculate
  1909. // the correct weights on the new edges being added further down.
  1910. To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
  1911. ToBBI.BB->removeSuccessor(&FromMBB);
  1912. }
  1913. for (MachineBasicBlock *Succ : FromSuccs) {
  1914. // Fallthrough edge can't be transferred.
  1915. if (Succ == FallThrough)
  1916. continue;
  1917. auto NewProb = BranchProbability::getZero();
  1918. if (AddEdges) {
  1919. // Calculate the edge probability for the edge from ToBBI.BB to Succ,
  1920. // which is a portion of the edge probability from FromMBB to Succ. The
  1921. // portion ratio is the edge probability from ToBBI.BB to FromMBB (if
  1922. // FromBBI is a successor of ToBBI.BB. See comment below for excepion).
  1923. NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
  1924. // To2FromProb is 0 when FromMBB is not a successor of ToBBI.BB. This
  1925. // only happens when if-converting a diamond CFG and FromMBB is the
  1926. // tail BB. In this case FromMBB post-dominates ToBBI.BB and hence we
  1927. // could just use the probabilities on FromMBB's out-edges when adding
  1928. // new successors.
  1929. if (!To2FromProb.isZero())
  1930. NewProb *= To2FromProb;
  1931. }
  1932. FromMBB.removeSuccessor(Succ);
  1933. if (AddEdges) {
  1934. // If the edge from ToBBI.BB to Succ already exists, update the
  1935. // probability of this edge by adding NewProb to it. An example is shown
  1936. // below, in which A is ToBBI.BB and B is FromMBB. In this case we
  1937. // don't have to set C as A's successor as it already is. We only need to
  1938. // update the edge probability on A->C. Note that B will not be
  1939. // immediately removed from A's successors. It is possible that B->D is
  1940. // not removed either if D is a fallthrough of B. Later the edge A->D
  1941. // (generated here) and B->D will be combined into one edge. To maintain
  1942. // correct edge probability of this combined edge, we need to set the edge
  1943. // probability of A->B to zero, which is already done above. The edge
  1944. // probability on A->D is calculated by scaling the original probability
  1945. // on A->B by the probability of B->D.
  1946. //
  1947. // Before ifcvt: After ifcvt (assume B->D is kept):
  1948. //
  1949. // A A
  1950. // /| /|\
  1951. // / B / B|
  1952. // | /| | ||
  1953. // |/ | | |/
  1954. // C D C D
  1955. //
  1956. if (ToBBI.BB->isSuccessor(Succ))
  1957. ToBBI.BB->setSuccProbability(
  1958. find(ToBBI.BB->successors(), Succ),
  1959. MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
  1960. else
  1961. ToBBI.BB->addSuccessor(Succ, NewProb);
  1962. }
  1963. }
  1964. // Move the now empty FromMBB out of the way to the end of the function so
  1965. // it doesn't interfere with fallthrough checks done by canFallThroughTo().
  1966. MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
  1967. if (Last != &FromMBB)
  1968. FromMBB.moveAfter(Last);
  1969. // Normalize the probabilities of ToBBI.BB's successors with all adjustment
  1970. // we've done above.
  1971. if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
  1972. ToBBI.BB->normalizeSuccProbs();
  1973. ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
  1974. FromBBI.Predicate.clear();
  1975. ToBBI.NonPredSize += FromBBI.NonPredSize;
  1976. ToBBI.ExtraCost += FromBBI.ExtraCost;
  1977. ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
  1978. FromBBI.NonPredSize = 0;
  1979. FromBBI.ExtraCost = 0;
  1980. FromBBI.ExtraCost2 = 0;
  1981. ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
  1982. ToBBI.HasFallThrough = FromBBI.HasFallThrough;
  1983. ToBBI.IsAnalyzed = false;
  1984. FromBBI.IsAnalyzed = false;
  1985. }
  1986. FunctionPass *
  1987. llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
  1988. return new IfConverter(std::move(Ftor));
  1989. }