IfConversion.cpp 90 KB

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