blob: e90985bf89942f16839f33f3cd7ad72439df7823 [file] [log] [blame]
Evan Cheng4e654852007-05-16 02:00:57 +00001//===-- IfConversion.cpp - Machine code if conversion pass. ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Cheng4e654852007-05-16 02:00:57 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the machine instruction level if-conversion pass.
11//
12//===----------------------------------------------------------------------===//
13
Evan Cheng5f702182007-06-01 00:12:12 +000014#define DEBUG_TYPE "ifcvt"
Evan Cheng030a0a02009-09-04 07:47:40 +000015#include "BranchFolding.h"
Evan Cheng5f702182007-06-01 00:12:12 +000016#include "llvm/Function.h"
Evan Cheng4e654852007-05-16 02:00:57 +000017#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
Owen Anderson7571ee72010-09-28 20:42:15 +000020#include "llvm/CodeGen/MachineLoopInfo.h"
Evan Cheng4e654852007-05-16 02:00:57 +000021#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng3ef1c872010-09-10 01:29:16 +000022#include "llvm/Target/TargetInstrItineraries.h"
Evan Cheng86cbfea2007-05-18 00:20:58 +000023#include "llvm/Target/TargetLowering.h"
Evan Cheng4e654852007-05-16 02:00:57 +000024#include "llvm/Target/TargetMachine.h"
Evan Cheng46df4eb2010-06-16 07:35:02 +000025#include "llvm/Target/TargetRegisterInfo.h"
Evan Chengedf48962007-06-08 19:10:51 +000026#include "llvm/Support/CommandLine.h"
Evan Cheng4e654852007-05-16 02:00:57 +000027#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
Evan Cheng36489bb2007-05-18 19:26:33 +000030#include "llvm/ADT/DepthFirstIterator.h"
Evan Cheng4e654852007-05-16 02:00:57 +000031#include "llvm/ADT/Statistic.h"
Evan Chenga1a87872007-06-18 08:37:25 +000032#include "llvm/ADT/STLExtras.h"
Evan Cheng4e654852007-05-16 02:00:57 +000033using namespace llvm;
34
Chris Lattnerf86e1df2008-01-07 05:40:58 +000035// Hidden options for help debugging.
36static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
37static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
38static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000039static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000040 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000041static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000042 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000043static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000044 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000045static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000046 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000047static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000048 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000049static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000050 cl::init(false), cl::Hidden);
Bob Wilson92fffe02010-06-15 22:18:54 +000051static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
Chris Lattnerf86e1df2008-01-07 05:40:58 +000052 cl::init(false), cl::Hidden);
Evan Cheng46df4eb2010-06-16 07:35:02 +000053static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
54 cl::init(true), cl::Hidden);
Evan Chengedf48962007-06-08 19:10:51 +000055
Evan Cheng1c9f91d2007-06-09 01:03:43 +000056STATISTIC(NumSimple, "Number of simple if-conversions performed");
57STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
58STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
Evan Chengcc8fb462007-06-12 23:54:05 +000059STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
Evan Cheng1c9f91d2007-06-09 01:03:43 +000060STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
61STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
62STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
63STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
Evan Cheng2c8c3a42007-06-15 07:36:12 +000064STATISTIC(NumDupBBs, "Number of duplicated blocks");
Evan Cheng4e654852007-05-16 02:00:57 +000065
66namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000067 class IfConverter : public MachineFunctionPass {
Evan Chenge882fca2007-06-16 09:34:52 +000068 enum IfcvtKind {
Evan Cheng4e654852007-05-16 02:00:57 +000069 ICNotClassfied, // BB data valid, but not classified.
Evan Chengb6665f62007-06-04 06:47:22 +000070 ICSimpleFalse, // Same as ICSimple, but on the false path.
Evan Chenge882fca2007-06-16 09:34:52 +000071 ICSimple, // BB is entry of an one split, no rejoin sub-CFG.
72 ICTriangleFRev, // Same as ICTriangleFalse, but false path rev condition.
Evan Chengcc8fb462007-06-12 23:54:05 +000073 ICTriangleRev, // Same as ICTriangle, but true path rev condition.
Evan Cheng1c9f91d2007-06-09 01:03:43 +000074 ICTriangleFalse, // Same as ICTriangle, but on the false path.
Evan Chenge882fca2007-06-16 09:34:52 +000075 ICTriangle, // BB is entry of a triangle sub-CFG.
Evan Cheng9618bca2007-06-11 22:26:22 +000076 ICDiamond // BB is entry of a diamond sub-CFG.
Evan Cheng4e654852007-05-16 02:00:57 +000077 };
78
79 /// BBInfo - One per MachineBasicBlock, this is used to cache the result
80 /// if-conversion feasibility analysis. This includes results from
81 /// TargetInstrInfo::AnalyzeBranch() (i.e. TBB, FBB, and Cond), and its
Evan Cheng86cbfea2007-05-18 00:20:58 +000082 /// classification, and common tail block of its successors (if it's a
Evan Chengcf6cc112007-05-18 18:14:37 +000083 /// diamond shape), its size, whether it's predicable, and whether any
84 /// instruction can clobber the 'would-be' predicate.
Evan Chenga13aa952007-05-23 07:23:16 +000085 ///
Evan Cheng9618bca2007-06-11 22:26:22 +000086 /// IsDone - True if BB is not to be considered for ifcvt.
87 /// IsBeingAnalyzed - True if BB is currently being analyzed.
88 /// IsAnalyzed - True if BB has been analyzed (info is still valid).
89 /// IsEnqueued - True if BB has been enqueued to be ifcvt'ed.
90 /// IsBrAnalyzable - True if AnalyzeBranch() returns false.
91 /// HasFallThrough - True if BB may fallthrough to the following BB.
92 /// IsUnpredicable - True if BB is known to be unpredicable.
Evan Cheng11ce02d2007-07-10 17:50:43 +000093 /// ClobbersPred - True if BB could modify predicates (e.g. has
Evan Cheng7a655472007-06-06 10:16:17 +000094 /// cmp, call, etc.)
Evan Cheng9618bca2007-06-11 22:26:22 +000095 /// NonPredSize - Number of non-predicated instructions.
Bob Wilson2ad40d32010-10-26 00:02:21 +000096 /// ExtraCost - Extra cost for microcoded instructions.
Evan Chenga13aa952007-05-23 07:23:16 +000097 /// BB - Corresponding MachineBasicBlock.
98 /// TrueBB / FalseBB- See AnalyzeBranch().
99 /// BrCond - Conditions for end of block conditional branches.
100 /// Predicate - Predicate used in the BB.
Evan Cheng4e654852007-05-16 02:00:57 +0000101 struct BBInfo {
Evan Cheng9618bca2007-06-11 22:26:22 +0000102 bool IsDone : 1;
103 bool IsBeingAnalyzed : 1;
104 bool IsAnalyzed : 1;
105 bool IsEnqueued : 1;
106 bool IsBrAnalyzable : 1;
107 bool HasFallThrough : 1;
108 bool IsUnpredicable : 1;
Evan Chenga2acf842007-06-15 21:18:05 +0000109 bool CannotBeCopied : 1;
Evan Cheng9618bca2007-06-11 22:26:22 +0000110 bool ClobbersPred : 1;
Evan Chenga13aa952007-05-23 07:23:16 +0000111 unsigned NonPredSize;
Bob Wilson2ad40d32010-10-26 00:02:21 +0000112 unsigned ExtraCost;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000113 MachineBasicBlock *BB;
114 MachineBasicBlock *TrueBB;
115 MachineBasicBlock *FalseBB;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000116 SmallVector<MachineOperand, 4> BrCond;
117 SmallVector<MachineOperand, 4> Predicate;
Evan Chenge882fca2007-06-16 09:34:52 +0000118 BBInfo() : IsDone(false), IsBeingAnalyzed(false),
Evan Cheng9618bca2007-06-11 22:26:22 +0000119 IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
120 HasFallThrough(false), IsUnpredicable(false),
Evan Chenga2acf842007-06-15 21:18:05 +0000121 CannotBeCopied(false), ClobbersPred(false), NonPredSize(0),
Bob Wilson2ad40d32010-10-26 00:02:21 +0000122 ExtraCost(0), BB(0), TrueBB(0), FalseBB(0) {}
Evan Chenge882fca2007-06-16 09:34:52 +0000123 };
124
Bob Wilson669db042010-06-15 18:19:27 +0000125 /// IfcvtToken - Record information about pending if-conversions to attempt:
Evan Chenge882fca2007-06-16 09:34:52 +0000126 /// BBI - Corresponding BBInfo.
127 /// Kind - Type of block. See IfcvtKind.
Bob Wilson9c4856a2009-05-13 23:25:24 +0000128 /// NeedSubsumption - True if the to-be-predicated BB has already been
Evan Chenge882fca2007-06-16 09:34:52 +0000129 /// predicated.
Evan Chenga1a87872007-06-18 08:37:25 +0000130 /// NumDups - Number of instructions that would be duplicated due
131 /// to this if-conversion. (For diamonds, the number of
132 /// identical instructions at the beginnings of both
133 /// paths).
134 /// NumDups2 - For diamonds, the number of identical instructions
135 /// at the ends of both paths.
Evan Chenge882fca2007-06-16 09:34:52 +0000136 struct IfcvtToken {
137 BBInfo &BBI;
138 IfcvtKind Kind;
Bob Wilson9c4856a2009-05-13 23:25:24 +0000139 bool NeedSubsumption;
Evan Chenga1a87872007-06-18 08:37:25 +0000140 unsigned NumDups;
141 unsigned NumDups2;
142 IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0)
Bob Wilson9c4856a2009-05-13 23:25:24 +0000143 : BBI(b), Kind(k), NeedSubsumption(s), NumDups(d), NumDups2(d2) {}
Evan Cheng4e654852007-05-16 02:00:57 +0000144 };
145
Evan Cheng82582102007-05-30 19:49:19 +0000146 /// Roots - Basic blocks that do not have successors. These are the starting
147 /// points of Graph traversal.
148 std::vector<MachineBasicBlock*> Roots;
149
Evan Cheng4e654852007-05-16 02:00:57 +0000150 /// BBAnalysis - Results of if-conversion feasibility analysis indexed by
151 /// basic block number.
152 std::vector<BBInfo> BBAnalysis;
153
Evan Cheng86cbfea2007-05-18 00:20:58 +0000154 const TargetLowering *TLI;
Evan Cheng4e654852007-05-16 02:00:57 +0000155 const TargetInstrInfo *TII;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000156 const TargetRegisterInfo *TRI;
Evan Cheng3ef1c872010-09-10 01:29:16 +0000157 const InstrItineraryData *InstrItins;
Owen Anderson7571ee72010-09-28 20:42:15 +0000158 const MachineLoopInfo *MLI;
Evan Cheng4e654852007-05-16 02:00:57 +0000159 bool MadeChange;
Owen Anderson13bbe4b2009-06-24 23:41:44 +0000160 int FnNum;
Evan Cheng4e654852007-05-16 02:00:57 +0000161 public:
162 static char ID;
Owen Anderson081c34b2010-10-19 17:21:58 +0000163 IfConverter() : MachineFunctionPass(ID), FnNum(-1) {
164 initializeIfConverterPass(*PassRegistry::getPassRegistry());
165 }
Owen Anderson7571ee72010-09-28 20:42:15 +0000166
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequired<MachineLoopInfo>();
169 MachineFunctionPass::getAnalysisUsage(AU);
170 }
Evan Cheng4e654852007-05-16 02:00:57 +0000171
172 virtual bool runOnMachineFunction(MachineFunction &MF);
Evan Chengb3dd2642008-06-04 09:15:51 +0000173 virtual const char *getPassName() const { return "If Converter"; }
Evan Cheng4e654852007-05-16 02:00:57 +0000174
175 private:
Evan Chengb6665f62007-06-04 06:47:22 +0000176 bool ReverseBranchCondition(BBInfo &BBI);
Owen Andersone3cc84a2010-10-01 22:45:50 +0000177 bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
178 float Prediction, float Confidence) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000179 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000180 bool FalseBranch, unsigned &Dups,
181 float Prediction, float Confidence) const;
Evan Chenga1a87872007-06-18 08:37:25 +0000182 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
183 unsigned &Dups1, unsigned &Dups2) const;
Evan Chengac5f1422007-06-08 09:36:04 +0000184 void ScanInstructions(BBInfo &BBI);
Evan Chenge882fca2007-06-16 09:34:52 +0000185 BBInfo &AnalyzeBlock(MachineBasicBlock *BB,
186 std::vector<IfcvtToken*> &Tokens);
Owen Anderson44eb65c2008-08-14 22:49:33 +0000187 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Cond,
Evan Chengac5f1422007-06-08 09:36:04 +0000188 bool isTriangle = false, bool RevBranch = false);
Bob Wilson6fb124b2010-06-15 18:57:15 +0000189 void AnalyzeBlocks(MachineFunction &MF, std::vector<IfcvtToken*> &Tokens);
Evan Chenga1a87872007-06-18 08:37:25 +0000190 void InvalidatePreds(MachineBasicBlock *BB);
Evan Cheng7e75ba82007-06-08 22:01:07 +0000191 void RemoveExtraEdges(BBInfo &BBI);
Evan Chenge882fca2007-06-16 09:34:52 +0000192 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
193 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
Evan Chenga1a87872007-06-18 08:37:25 +0000194 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
195 unsigned NumDups1, unsigned NumDups2);
Evan Chenga13aa952007-05-23 07:23:16 +0000196 void PredicateBlock(BBInfo &BBI,
Evan Chenga1a87872007-06-18 08:37:25 +0000197 MachineBasicBlock::iterator E,
Evan Cheng46df4eb2010-06-16 07:35:02 +0000198 SmallVectorImpl<MachineOperand> &Cond,
199 SmallSet<unsigned, 4> &Redefs);
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000200 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000201 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng46df4eb2010-06-16 07:35:02 +0000202 SmallSet<unsigned, 4> &Redefs,
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000203 bool IgnoreBr = false);
Bob Wilson8eab75f2010-06-29 00:55:23 +0000204 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
Evan Cheng5f702182007-06-01 00:12:12 +0000205
Owen Anderson7571ee72010-09-28 20:42:15 +0000206 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB, unsigned Size,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000207 float Prediction, float Confidence) const {
208 return Size > 0 && TII->isProfitableToIfCvt(BB, Size,
209 Prediction, Confidence);
Evan Cheng13151432010-06-25 22:42:03 +0000210 }
211
212 bool MeetIfcvtSizeLimit(MachineBasicBlock &TBB, unsigned TSize,
Owen Anderson7571ee72010-09-28 20:42:15 +0000213 MachineBasicBlock &FBB, unsigned FSize,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000214 float Prediction, float Confidence) const {
Evan Cheng13151432010-06-25 22:42:03 +0000215 return TSize > 0 && FSize > 0 &&
Owen Andersone3cc84a2010-10-01 22:45:50 +0000216 TII->isProfitableToIfCvt(TBB, TSize, FBB, FSize,
217 Prediction, Confidence);
Evan Chenga1a87872007-06-18 08:37:25 +0000218 }
219
Evan Chengd4de6d92007-06-07 02:12:15 +0000220 // blockAlwaysFallThrough - Block ends without a terminator.
221 bool blockAlwaysFallThrough(BBInfo &BBI) const {
Evan Cheng9618bca2007-06-11 22:26:22 +0000222 return BBI.IsBrAnalyzable && BBI.TrueBB == NULL;
Evan Cheng7a655472007-06-06 10:16:17 +0000223 }
224
Evan Chenge882fca2007-06-16 09:34:52 +0000225 // IfcvtTokenCmp - Used to sort if-conversion candidates.
226 static bool IfcvtTokenCmp(IfcvtToken *C1, IfcvtToken *C2) {
Evan Chenga1a87872007-06-18 08:37:25 +0000227 int Incr1 = (C1->Kind == ICDiamond)
228 ? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
229 int Incr2 = (C2->Kind == ICDiamond)
230 ? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
231 if (Incr1 > Incr2)
Evan Chenge882fca2007-06-16 09:34:52 +0000232 return true;
Evan Chenga1a87872007-06-18 08:37:25 +0000233 else if (Incr1 == Incr2) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000234 // Favors subsumption.
235 if (C1->NeedSubsumption == false && C2->NeedSubsumption == true)
Evan Chenge882fca2007-06-16 09:34:52 +0000236 return true;
Bob Wilson9c4856a2009-05-13 23:25:24 +0000237 else if (C1->NeedSubsumption == C2->NeedSubsumption) {
Evan Chenge882fca2007-06-16 09:34:52 +0000238 // Favors diamond over triangle, etc.
239 if ((unsigned)C1->Kind < (unsigned)C2->Kind)
240 return true;
241 else if (C1->Kind == C2->Kind)
242 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
243 }
244 }
245 return false;
Evan Cheng5f702182007-06-01 00:12:12 +0000246 }
Evan Cheng4e654852007-05-16 02:00:57 +0000247 };
Evan Chenge882fca2007-06-16 09:34:52 +0000248
Evan Cheng4e654852007-05-16 02:00:57 +0000249 char IfConverter::ID = 0;
250}
251
Owen Anderson2ab36d32010-10-12 19:48:12 +0000252INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, false)
253INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
254INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, false)
Bob Wilsona5971032009-10-28 20:46:46 +0000255
256FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
Evan Cheng4e654852007-05-16 02:00:57 +0000257
258bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng86cbfea2007-05-18 00:20:58 +0000259 TLI = MF.getTarget().getTargetLowering();
Evan Cheng4e654852007-05-16 02:00:57 +0000260 TII = MF.getTarget().getInstrInfo();
Evan Cheng46df4eb2010-06-16 07:35:02 +0000261 TRI = MF.getTarget().getRegisterInfo();
Owen Anderson7571ee72010-09-28 20:42:15 +0000262 MLI = &getAnalysis<MachineLoopInfo>();
Evan Cheng3ef1c872010-09-10 01:29:16 +0000263 InstrItins = MF.getTarget().getInstrItineraryData();
Evan Cheng4e654852007-05-16 02:00:57 +0000264 if (!TII) return false;
265
Evan Cheng86050dc2010-06-18 23:09:54 +0000266 // Tail merge tend to expose more if-conversion opportunities.
267 BranchFolder BF(true);
268 bool BFChange = BF.OptimizeFunction(MF, TII,
269 MF.getTarget().getRegisterInfo(),
270 getAnalysisIfAvailable<MachineModuleInfo>());
271
David Greene083b7ff2010-01-04 22:02:01 +0000272 DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
Bill Wendling44ff7942009-08-22 20:11:17 +0000273 << MF.getFunction()->getName() << "\'");
Evan Chengedf48962007-06-08 19:10:51 +0000274
275 if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
David Greene083b7ff2010-01-04 22:02:01 +0000276 DEBUG(dbgs() << " skipped\n");
Evan Chengedf48962007-06-08 19:10:51 +0000277 return false;
278 }
David Greene083b7ff2010-01-04 22:02:01 +0000279 DEBUG(dbgs() << "\n");
Evan Cheng5f702182007-06-01 00:12:12 +0000280
Evan Cheng4e654852007-05-16 02:00:57 +0000281 MF.RenumberBlocks();
Evan Cheng5f702182007-06-01 00:12:12 +0000282 BBAnalysis.resize(MF.getNumBlockIDs());
Evan Cheng4e654852007-05-16 02:00:57 +0000283
Evan Cheng82582102007-05-30 19:49:19 +0000284 // Look for root nodes, i.e. blocks without successors.
285 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Dan Gohman30359592008-01-29 13:02:09 +0000286 if (I->succ_empty())
Evan Cheng82582102007-05-30 19:49:19 +0000287 Roots.push_back(I);
288
Evan Chenge882fca2007-06-16 09:34:52 +0000289 std::vector<IfcvtToken*> Tokens;
Evan Cheng47d25022007-05-18 01:55:58 +0000290 MadeChange = false;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000291 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
292 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
293 while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000294 // Do an initial analysis for each basic block and find all the potential
295 // candidates to perform if-conversion.
Bob Wilson6fb124b2010-06-15 18:57:15 +0000296 bool Change = false;
297 AnalyzeBlocks(MF, Tokens);
Evan Chenge882fca2007-06-16 09:34:52 +0000298 while (!Tokens.empty()) {
299 IfcvtToken *Token = Tokens.back();
300 Tokens.pop_back();
301 BBInfo &BBI = Token->BBI;
302 IfcvtKind Kind = Token->Kind;
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000303 unsigned NumDups = Token->NumDups;
Duncan Sands20d629c2008-11-04 18:05:30 +0000304 unsigned NumDups2 = Token->NumDups2;
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000305
306 delete Token;
Evan Chengb6665f62007-06-04 06:47:22 +0000307
Evan Cheng9618bca2007-06-11 22:26:22 +0000308 // If the block has been evicted out of the queue or it has already been
309 // marked dead (due to it being predicated), then skip it.
Evan Chenge882fca2007-06-16 09:34:52 +0000310 if (BBI.IsDone)
311 BBI.IsEnqueued = false;
312 if (!BBI.IsEnqueued)
Evan Cheng9618bca2007-06-11 22:26:22 +0000313 continue;
Evan Chenge882fca2007-06-16 09:34:52 +0000314
Evan Cheng86ff2962007-06-14 20:28:52 +0000315 BBI.IsEnqueued = false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000316
Evan Chengb6665f62007-06-04 06:47:22 +0000317 bool RetVal = false;
Evan Chenge882fca2007-06-16 09:34:52 +0000318 switch (Kind) {
Evan Chenga13aa952007-05-23 07:23:16 +0000319 default: assert(false && "Unexpected!");
320 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000321 case ICSimple:
Evan Chengcb78d672007-06-06 01:12:44 +0000322 case ICSimpleFalse: {
Evan Chenge882fca2007-06-16 09:34:52 +0000323 bool isFalse = Kind == ICSimpleFalse;
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000324 if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
Bob Wilson92fffe02010-06-15 22:18:54 +0000325 DEBUG(dbgs() << "Ifcvt (Simple" << (Kind == ICSimpleFalse ?
326 " false" : "")
Bill Wendling44ff7942009-08-22 20:11:17 +0000327 << "): BB#" << BBI.BB->getNumber() << " ("
328 << ((Kind == ICSimpleFalse)
329 ? BBI.FalseBB->getNumber()
330 : BBI.TrueBB->getNumber()) << ") ");
Evan Chenge882fca2007-06-16 09:34:52 +0000331 RetVal = IfConvertSimple(BBI, Kind);
David Greene083b7ff2010-01-04 22:02:01 +0000332 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +0000333 if (RetVal) {
Dan Gohmanfe601042010-06-22 15:08:57 +0000334 if (isFalse) ++NumSimpleFalse;
335 else ++NumSimple;
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +0000336 }
Evan Chengb6665f62007-06-04 06:47:22 +0000337 break;
Evan Chengcb78d672007-06-06 01:12:44 +0000338 }
Evan Chenga13aa952007-05-23 07:23:16 +0000339 case ICTriangle:
Evan Chengcc8fb462007-06-12 23:54:05 +0000340 case ICTriangleRev:
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000341 case ICTriangleFalse:
Reid Spencera9bf49c2007-06-10 00:19:17 +0000342 case ICTriangleFRev: {
Evan Chenge882fca2007-06-16 09:34:52 +0000343 bool isFalse = Kind == ICTriangleFalse;
344 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
Evan Chengcc8fb462007-06-12 23:54:05 +0000345 if (DisableTriangle && !isFalse && !isRev) break;
346 if (DisableTriangleR && !isFalse && isRev) break;
347 if (DisableTriangleF && isFalse && !isRev) break;
348 if (DisableTriangleFR && isFalse && isRev) break;
David Greene083b7ff2010-01-04 22:02:01 +0000349 DEBUG(dbgs() << "Ifcvt (Triangle");
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000350 if (isFalse)
David Greene083b7ff2010-01-04 22:02:01 +0000351 DEBUG(dbgs() << " false");
Evan Chengcc8fb462007-06-12 23:54:05 +0000352 if (isRev)
David Greene083b7ff2010-01-04 22:02:01 +0000353 DEBUG(dbgs() << " rev");
354 DEBUG(dbgs() << "): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendling44ff7942009-08-22 20:11:17 +0000355 << BBI.TrueBB->getNumber() << ",F:"
356 << BBI.FalseBB->getNumber() << ") ");
Evan Chenge882fca2007-06-16 09:34:52 +0000357 RetVal = IfConvertTriangle(BBI, Kind);
David Greene083b7ff2010-01-04 22:02:01 +0000358 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000359 if (RetVal) {
Evan Chengcc8fb462007-06-12 23:54:05 +0000360 if (isFalse) {
Dan Gohmanfe601042010-06-22 15:08:57 +0000361 if (isRev) ++NumTriangleFRev;
362 else ++NumTriangleFalse;
Evan Chengcc8fb462007-06-12 23:54:05 +0000363 } else {
Dan Gohmanfe601042010-06-22 15:08:57 +0000364 if (isRev) ++NumTriangleRev;
365 else ++NumTriangle;
Evan Chengcc8fb462007-06-12 23:54:05 +0000366 }
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000367 }
Evan Chenga13aa952007-05-23 07:23:16 +0000368 break;
Reid Spencera9bf49c2007-06-10 00:19:17 +0000369 }
Evan Chenge882fca2007-06-16 09:34:52 +0000370 case ICDiamond: {
Evan Chengedf48962007-06-08 19:10:51 +0000371 if (DisableDiamond) break;
David Greene083b7ff2010-01-04 22:02:01 +0000372 DEBUG(dbgs() << "Ifcvt (Diamond): BB#" << BBI.BB->getNumber() << " (T:"
Bill Wendling44ff7942009-08-22 20:11:17 +0000373 << BBI.TrueBB->getNumber() << ",F:"
374 << BBI.FalseBB->getNumber() << ") ");
Nuno Lopes7ecbfd12008-11-04 13:02:59 +0000375 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2);
David Greene083b7ff2010-01-04 22:02:01 +0000376 DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
Dan Gohmanfe601042010-06-22 15:08:57 +0000377 if (RetVal) ++NumDiamonds;
Evan Chenga13aa952007-05-23 07:23:16 +0000378 break;
379 }
Evan Chenge882fca2007-06-16 09:34:52 +0000380 }
381
Evan Chengb6665f62007-06-04 06:47:22 +0000382 Change |= RetVal;
Evan Chengedf48962007-06-08 19:10:51 +0000383
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000384 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
385 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
386 if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
Evan Chengedf48962007-06-08 19:10:51 +0000387 break;
Evan Cheng4e654852007-05-16 02:00:57 +0000388 }
Evan Chenga13aa952007-05-23 07:23:16 +0000389
Evan Chenga13aa952007-05-23 07:23:16 +0000390 if (!Change)
391 break;
Evan Chengb6665f62007-06-04 06:47:22 +0000392 MadeChange |= Change;
Evan Cheng4e654852007-05-16 02:00:57 +0000393 }
Evan Cheng47d25022007-05-18 01:55:58 +0000394
Evan Chenge882fca2007-06-16 09:34:52 +0000395 // Delete tokens in case of early exit.
396 while (!Tokens.empty()) {
397 IfcvtToken *Token = Tokens.back();
398 Tokens.pop_back();
399 delete Token;
400 }
401
402 Tokens.clear();
Evan Cheng82582102007-05-30 19:49:19 +0000403 Roots.clear();
Evan Cheng47d25022007-05-18 01:55:58 +0000404 BBAnalysis.clear();
405
Evan Cheng6a5e2832010-06-18 22:17:13 +0000406 if (MadeChange && IfCvtBranchFold) {
Bob Wilsona5971032009-10-28 20:46:46 +0000407 BranchFolder BF(false);
Evan Cheng030a0a02009-09-04 07:47:40 +0000408 BF.OptimizeFunction(MF, TII,
409 MF.getTarget().getRegisterInfo(),
410 getAnalysisIfAvailable<MachineModuleInfo>());
411 }
412
Evan Cheng86050dc2010-06-18 23:09:54 +0000413 MadeChange |= BFChange;
Evan Cheng4e654852007-05-16 02:00:57 +0000414 return MadeChange;
415}
416
Evan Chenge882fca2007-06-16 09:34:52 +0000417/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
418/// its 'true' successor.
Evan Cheng4e654852007-05-16 02:00:57 +0000419static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
Evan Cheng86cbfea2007-05-18 00:20:58 +0000420 MachineBasicBlock *TrueBB) {
Evan Cheng4e654852007-05-16 02:00:57 +0000421 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
422 E = BB->succ_end(); SI != E; ++SI) {
423 MachineBasicBlock *SuccBB = *SI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000424 if (SuccBB != TrueBB)
Evan Cheng4e654852007-05-16 02:00:57 +0000425 return SuccBB;
426 }
427 return NULL;
428}
429
Evan Chenge882fca2007-06-16 09:34:52 +0000430/// ReverseBranchCondition - Reverse the condition of the end of the block
Bob Wilson9c4856a2009-05-13 23:25:24 +0000431/// branch. Swap block's 'true' and 'false' successors.
Evan Chengb6665f62007-06-04 06:47:22 +0000432bool IfConverter::ReverseBranchCondition(BBInfo &BBI) {
Stuart Hastings3bf91252010-06-17 22:43:56 +0000433 DebugLoc dl; // FIXME: this is nowhere
Evan Chengb6665f62007-06-04 06:47:22 +0000434 if (!TII->ReverseBranchCondition(BBI.BrCond)) {
435 TII->RemoveBranch(*BBI.BB);
Stuart Hastings3bf91252010-06-17 22:43:56 +0000436 TII->InsertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
Evan Chengb6665f62007-06-04 06:47:22 +0000437 std::swap(BBI.TrueBB, BBI.FalseBB);
438 return true;
439 }
440 return false;
441}
442
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000443/// getNextBlock - Returns the next block in the function blocks ordering. If
444/// it is the end, returns NULL.
445static inline MachineBasicBlock *getNextBlock(MachineBasicBlock *BB) {
446 MachineFunction::iterator I = BB;
447 MachineFunction::iterator E = BB->getParent()->end();
448 if (++I == E)
449 return NULL;
450 return I;
451}
452
Evan Chengac5f1422007-06-08 09:36:04 +0000453/// ValidSimple - Returns true if the 'true' block (along with its
Evan Chenge882fca2007-06-16 09:34:52 +0000454/// predecessor) forms a valid simple shape for ifcvt. It also returns the
455/// number of instructions that the ifcvt would need to duplicate if performed
456/// in Dups.
Owen Anderson7571ee72010-09-28 20:42:15 +0000457bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000458 float Prediction, float Confidence) const {
Evan Chenge882fca2007-06-16 09:34:52 +0000459 Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000460 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000461 return false;
462
Evan Cheng9ffd3402007-06-19 21:45:13 +0000463 if (TrueBBI.IsBrAnalyzable)
464 return false;
465
Evan Chenga2acf842007-06-15 21:18:05 +0000466 if (TrueBBI.BB->pred_size() > 1) {
467 if (TrueBBI.CannotBeCopied ||
Owen Anderson7571ee72010-09-28 20:42:15 +0000468 !TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000469 Prediction, Confidence))
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000470 return false;
Evan Chenge882fca2007-06-16 09:34:52 +0000471 Dups = TrueBBI.NonPredSize;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000472 }
473
Evan Cheng9ffd3402007-06-19 21:45:13 +0000474 return true;
Evan Cheng7a655472007-06-06 10:16:17 +0000475}
476
Evan Chengac5f1422007-06-08 09:36:04 +0000477/// ValidTriangle - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000478/// with their common predecessor) forms a valid triangle shape for ifcvt.
Evan Chenge882fca2007-06-16 09:34:52 +0000479/// If 'FalseBranch' is true, it checks if 'true' block's false branch
Bob Wilson92fffe02010-06-15 22:18:54 +0000480/// branches to the 'false' block rather than the other way around. It also
Evan Chenge882fca2007-06-16 09:34:52 +0000481/// returns the number of instructions that the ifcvt would need to duplicate
482/// if performed in 'Dups'.
Evan Chengac5f1422007-06-08 09:36:04 +0000483bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000484 bool FalseBranch, unsigned &Dups,
485 float Prediction, float Confidence) const {
Evan Chenge882fca2007-06-16 09:34:52 +0000486 Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000487 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000488 return false;
489
Evan Chenga2acf842007-06-15 21:18:05 +0000490 if (TrueBBI.BB->pred_size() > 1) {
491 if (TrueBBI.CannotBeCopied)
492 return false;
493
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000494 unsigned Size = TrueBBI.NonPredSize;
Evan Chenge882fca2007-06-16 09:34:52 +0000495 if (TrueBBI.IsBrAnalyzable) {
Dan Gohman30359592008-01-29 13:02:09 +0000496 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
Bob Wilson9c4856a2009-05-13 23:25:24 +0000497 // Ends with an unconditional branch. It will be removed.
Evan Chenge882fca2007-06-16 09:34:52 +0000498 --Size;
499 else {
500 MachineBasicBlock *FExit = FalseBranch
501 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
502 if (FExit)
503 // Require a conditional branch
504 ++Size;
505 }
506 }
Owen Andersone3cc84a2010-10-01 22:45:50 +0000507 if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size,
508 Prediction, Confidence))
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000509 return false;
Evan Chenge882fca2007-06-16 09:34:52 +0000510 Dups = Size;
Evan Cheng2c8c3a42007-06-15 07:36:12 +0000511 }
Evan Chengd4de6d92007-06-07 02:12:15 +0000512
Evan Chengac5f1422007-06-08 09:36:04 +0000513 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
514 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
Evan Chengd4de6d92007-06-07 02:12:15 +0000515 MachineFunction::iterator I = TrueBBI.BB;
516 if (++I == TrueBBI.BB->getParent()->end())
517 return false;
Evan Chengac5f1422007-06-08 09:36:04 +0000518 TExit = I;
Evan Chengd4de6d92007-06-07 02:12:15 +0000519 }
Evan Chengac5f1422007-06-08 09:36:04 +0000520 return TExit && TExit == FalseBBI.BB;
Evan Chengd4de6d92007-06-07 02:12:15 +0000521}
522
Evan Chengac5f1422007-06-08 09:36:04 +0000523/// ValidDiamond - Returns true if the 'true' and 'false' blocks (along
Evan Chengd4de6d92007-06-07 02:12:15 +0000524/// with their common predecessor) forms a valid diamond shape for ifcvt.
Evan Chenga1a87872007-06-18 08:37:25 +0000525bool IfConverter::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
526 unsigned &Dups1, unsigned &Dups2) const {
527 Dups1 = Dups2 = 0;
528 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
529 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
Evan Cheng9618bca2007-06-11 22:26:22 +0000530 return false;
531
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000532 MachineBasicBlock *TT = TrueBBI.TrueBB;
533 MachineBasicBlock *FT = FalseBBI.TrueBB;
534
535 if (!TT && blockAlwaysFallThrough(TrueBBI))
536 TT = getNextBlock(TrueBBI.BB);
537 if (!FT && blockAlwaysFallThrough(FalseBBI))
538 FT = getNextBlock(FalseBBI.BB);
539 if (TT != FT)
540 return false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000541 if (TT == NULL && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
Evan Cheng1c9f91d2007-06-09 01:03:43 +0000542 return false;
Evan Chengc4047a82007-06-18 22:44:57 +0000543 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
544 return false;
545
546 // FIXME: Allow true block to have an early exit?
547 if (TrueBBI.FalseBB || FalseBBI.FalseBB ||
548 (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred))
Evan Chenga1a87872007-06-18 08:37:25 +0000549 return false;
550
Bob Wilson7c730e72010-10-26 00:02:24 +0000551 // Count duplicate instructions at the beginning of the true and false blocks.
Jim Grosbach66f360e2010-06-07 21:28:55 +0000552 MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
553 MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
Bob Wilson7c730e72010-10-26 00:02:24 +0000554 MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
555 MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
556 while (TIB != TIE && FIB != FIE) {
Evan Chenga9934dc2010-06-18 21:52:57 +0000557 // Skip dbg_value instructions. These do not count.
Bob Wilson7c730e72010-10-26 00:02:24 +0000558 if (TIB->isDebugValue()) {
559 while (TIB != TIE && TIB->isDebugValue())
560 ++TIB;
561 if (TIB == TIE)
Evan Chenga9934dc2010-06-18 21:52:57 +0000562 break;
563 }
Bob Wilson7c730e72010-10-26 00:02:24 +0000564 if (FIB->isDebugValue()) {
565 while (FIB != FIE && FIB->isDebugValue())
566 ++FIB;
567 if (FIB == FIE)
Evan Chenga9934dc2010-06-18 21:52:57 +0000568 break;
569 }
Bob Wilson7c730e72010-10-26 00:02:24 +0000570 if (!TIB->isIdenticalTo(FIB))
571 break;
572 ++Dups1;
573 ++TIB;
574 ++FIB;
575 }
576
577 // Now, in preparation for counting duplicate instructions at the ends of the
578 // blocks, move the end iterators up past any branch instructions.
579 while (TIE != TIB) {
580 --TIE;
581 if (!TIE->getDesc().isBranch())
582 break;
583 }
584 while (FIE != FIB) {
585 --FIE;
586 if (!FIE->getDesc().isBranch())
587 break;
588 }
589
590 // If Dups1 includes all of a block, then don't count duplicate
591 // instructions at the end of the blocks.
592 if (TIB == TIE || FIB == FIE)
593 return true;
594
595 // Count duplicate instructions at the ends of the blocks.
596 while (TIE != TIB && FIE != FIB) {
597 // Skip dbg_value instructions. These do not count.
598 if (TIE->isDebugValue()) {
599 while (TIE != TIB && TIE->isDebugValue())
600 --TIE;
601 if (TIE == TIB)
602 break;
603 }
604 if (FIE->isDebugValue()) {
605 while (FIE != FIB && FIE->isDebugValue())
606 --FIE;
607 if (FIE == FIB)
608 break;
609 }
610 if (!TIE->isIdenticalTo(FIE))
Evan Chenga1a87872007-06-18 08:37:25 +0000611 break;
612 ++Dups2;
Bob Wilson7c730e72010-10-26 00:02:24 +0000613 --TIE;
614 --FIE;
Evan Chenga1a87872007-06-18 08:37:25 +0000615 }
616
617 return true;
Evan Chengd4de6d92007-06-07 02:12:15 +0000618}
619
Evan Cheng9618bca2007-06-11 22:26:22 +0000620/// ScanInstructions - Scan all the instructions in the block to determine if
621/// the block is predicable. In most cases, that means all the instructions
Chris Lattner69244302008-01-07 01:56:04 +0000622/// in the block are isPredicable(). Also checks if the block contains any
Evan Cheng9618bca2007-06-11 22:26:22 +0000623/// instruction which can clobber a predicate (e.g. condition code register).
624/// If so, the block is not predicable unless it's the last instruction.
625void IfConverter::ScanInstructions(BBInfo &BBI) {
626 if (BBI.IsDone)
627 return;
628
Evan Chengd2c5eb82007-07-06 23:24:39 +0000629 bool AlreadyPredicated = BBI.Predicate.size() > 0;
Evan Cheng9618bca2007-06-11 22:26:22 +0000630 // First analyze the end of BB branches.
Evan Chengb7c908b2007-06-14 21:26:08 +0000631 BBI.TrueBB = BBI.FalseBB = NULL;
Evan Cheng9618bca2007-06-11 22:26:22 +0000632 BBI.BrCond.clear();
633 BBI.IsBrAnalyzable =
634 !TII->AnalyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
635 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == NULL;
636
637 if (BBI.BrCond.size()) {
638 // No false branch. This BB must end with a conditional branch and a
639 // fallthrough.
640 if (!BBI.FalseBB)
Bob Wilson92fffe02010-06-15 22:18:54 +0000641 BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
Evan Cheng2077e182009-06-15 21:24:34 +0000642 if (!BBI.FalseBB) {
643 // Malformed bcc? True and false blocks are the same?
644 BBI.IsUnpredicable = true;
645 return;
646 }
Evan Cheng9618bca2007-06-11 22:26:22 +0000647 }
648
649 // Then scan all the instructions.
650 BBI.NonPredSize = 0;
Bob Wilson2ad40d32010-10-26 00:02:21 +0000651 BBI.ExtraCost = 0;
Evan Cheng9618bca2007-06-11 22:26:22 +0000652 BBI.ClobbersPred = false;
Evan Cheng9618bca2007-06-11 22:26:22 +0000653 for (MachineBasicBlock::iterator I = BBI.BB->begin(), E = BBI.BB->end();
654 I != E; ++I) {
Jim Grosbach870c8052010-06-04 23:01:26 +0000655 if (I->isDebugValue())
656 continue;
657
Chris Lattner749c6f62008-01-07 07:27:27 +0000658 const TargetInstrDesc &TID = I->getDesc();
659 if (TID.isNotDuplicable())
Evan Chenga2acf842007-06-15 21:18:05 +0000660 BBI.CannotBeCopied = true;
661
Evan Cheng9618bca2007-06-11 22:26:22 +0000662 bool isPredicated = TII->isPredicated(I);
Chris Lattner749c6f62008-01-07 07:27:27 +0000663 bool isCondBr = BBI.IsBrAnalyzable && TID.isConditionalBranch();
Evan Cheng9618bca2007-06-11 22:26:22 +0000664
Evan Chengd2c5eb82007-07-06 23:24:39 +0000665 if (!isCondBr) {
Evan Cheng3ef1c872010-09-10 01:29:16 +0000666 if (!isPredicated) {
Bob Wilson2ad40d32010-10-26 00:02:21 +0000667 BBI.NonPredSize++;
Evan Cheng3ef1c872010-09-10 01:29:16 +0000668 unsigned NumOps = TII->getNumMicroOps(&*I, InstrItins);
Bob Wilson2ad40d32010-10-26 00:02:21 +0000669 if (NumOps > 1)
670 BBI.ExtraCost += NumOps-1;
Evan Cheng3ef1c872010-09-10 01:29:16 +0000671 } else if (!AlreadyPredicated) {
Evan Chengd2c5eb82007-07-06 23:24:39 +0000672 // FIXME: This instruction is already predicated before the
673 // if-conversion pass. It's probably something like a conditional move.
674 // Mark this block unpredicable for now.
675 BBI.IsUnpredicable = true;
676 return;
677 }
Evan Chengd2c5eb82007-07-06 23:24:39 +0000678 }
Evan Cheng9618bca2007-06-11 22:26:22 +0000679
680 if (BBI.ClobbersPred && !isPredicated) {
681 // Predicate modification instruction should end the block (except for
682 // already predicated instructions and end of block branches).
683 if (isCondBr) {
Bob Wilson9c4856a2009-05-13 23:25:24 +0000684 // A conditional branch is not predicable, but it may be eliminated.
Evan Cheng9618bca2007-06-11 22:26:22 +0000685 continue;
686 }
687
688 // Predicate may have been modified, the subsequent (currently)
Evan Chengd2c5eb82007-07-06 23:24:39 +0000689 // unpredicated instructions cannot be correctly predicated.
Evan Cheng9618bca2007-06-11 22:26:22 +0000690 BBI.IsUnpredicable = true;
691 return;
692 }
693
Evan Cheng11ce02d2007-07-10 17:50:43 +0000694 // FIXME: Make use of PredDefs? e.g. ADDC, SUBC sets predicates but are
695 // still potentially predicable.
696 std::vector<MachineOperand> PredDefs;
697 if (TII->DefinesPredicate(I, PredDefs))
Evan Cheng9618bca2007-06-11 22:26:22 +0000698 BBI.ClobbersPred = true;
699
Evan Chenge54cb162009-11-21 06:20:26 +0000700 if (!TII->isPredicable(I)) {
Evan Cheng9618bca2007-06-11 22:26:22 +0000701 BBI.IsUnpredicable = true;
702 return;
703 }
704 }
705}
706
707/// FeasibilityAnalysis - Determine if the block is a suitable candidate to be
708/// predicated by the specified predicate.
709bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000710 SmallVectorImpl<MachineOperand> &Pred,
Evan Cheng9618bca2007-06-11 22:26:22 +0000711 bool isTriangle, bool RevBranch) {
Evan Chenge882fca2007-06-16 09:34:52 +0000712 // If the block is dead or unpredicable, then it cannot be predicated.
713 if (BBI.IsDone || BBI.IsUnpredicable)
Evan Cheng9618bca2007-06-11 22:26:22 +0000714 return false;
715
Evan Cheng9618bca2007-06-11 22:26:22 +0000716 // If it is already predicated, check if its predicate subsumes the new
717 // predicate.
718 if (BBI.Predicate.size() && !TII->SubsumesPredicate(BBI.Predicate, Pred))
719 return false;
720
721 if (BBI.BrCond.size()) {
722 if (!isTriangle)
723 return false;
724
Bob Wilson9c4856a2009-05-13 23:25:24 +0000725 // Test predicate subsumption.
Owen Anderson44eb65c2008-08-14 22:49:33 +0000726 SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
727 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Cheng9618bca2007-06-11 22:26:22 +0000728 if (RevBranch) {
729 if (TII->ReverseBranchCondition(Cond))
730 return false;
731 }
732 if (TII->ReverseBranchCondition(RevPred) ||
733 !TII->SubsumesPredicate(Cond, RevPred))
734 return false;
735 }
736
737 return true;
738}
739
Evan Chengac5f1422007-06-08 09:36:04 +0000740/// AnalyzeBlock - Analyze the structure of the sub-CFG starting from
Evan Chengcf6cc112007-05-18 18:14:37 +0000741/// the specified block. Record its successors and whether it looks like an
742/// if-conversion candidate.
Evan Chenge882fca2007-06-16 09:34:52 +0000743IfConverter::BBInfo &IfConverter::AnalyzeBlock(MachineBasicBlock *BB,
744 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng4e654852007-05-16 02:00:57 +0000745 BBInfo &BBI = BBAnalysis[BB->getNumber()];
746
Evan Cheng9618bca2007-06-11 22:26:22 +0000747 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed)
748 return BBI;
Evan Cheng86cbfea2007-05-18 00:20:58 +0000749
Evan Cheng9618bca2007-06-11 22:26:22 +0000750 BBI.BB = BB;
751 BBI.IsBeingAnalyzed = true;
Evan Cheng9618bca2007-06-11 22:26:22 +0000752
753 ScanInstructions(BBI);
754
Bob Wilson9c4856a2009-05-13 23:25:24 +0000755 // Unanalyzable or ends with fallthrough or unconditional branch.
Dan Gohman30359592008-01-29 13:02:09 +0000756 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty()) {
Evan Cheng9618bca2007-06-11 22:26:22 +0000757 BBI.IsBeingAnalyzed = false;
758 BBI.IsAnalyzed = true;
759 return BBI;
Evan Cheng7a655472007-06-06 10:16:17 +0000760 }
761
Evan Cheng9618bca2007-06-11 22:26:22 +0000762 // Do not ifcvt if either path is a back edge to the entry block.
763 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
764 BBI.IsBeingAnalyzed = false;
765 BBI.IsAnalyzed = true;
766 return BBI;
767 }
768
Evan Cheng2077e182009-06-15 21:24:34 +0000769 // Do not ifcvt if true and false fallthrough blocks are the same.
770 if (!BBI.FalseBB) {
771 BBI.IsBeingAnalyzed = false;
772 BBI.IsAnalyzed = true;
773 return BBI;
774 }
775
Evan Chenge882fca2007-06-16 09:34:52 +0000776 BBInfo &TrueBBI = AnalyzeBlock(BBI.TrueBB, Tokens);
777 BBInfo &FalseBBI = AnalyzeBlock(BBI.FalseBB, Tokens);
Evan Cheng9618bca2007-06-11 22:26:22 +0000778
779 if (TrueBBI.IsDone && FalseBBI.IsDone) {
780 BBI.IsBeingAnalyzed = false;
781 BBI.IsAnalyzed = true;
782 return BBI;
783 }
784
Owen Anderson44eb65c2008-08-14 22:49:33 +0000785 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chengb6665f62007-06-04 06:47:22 +0000786 bool CanRevCond = !TII->ReverseBranchCondition(RevCond);
Evan Chengac5f1422007-06-08 09:36:04 +0000787
Evan Chenge882fca2007-06-16 09:34:52 +0000788 unsigned Dups = 0;
Evan Chenga1a87872007-06-18 08:37:25 +0000789 unsigned Dups2 = 0;
Evan Chenge882fca2007-06-16 09:34:52 +0000790 bool TNeedSub = TrueBBI.Predicate.size() > 0;
791 bool FNeedSub = FalseBBI.Predicate.size() > 0;
792 bool Enqueued = false;
Owen Anderson7571ee72010-09-28 20:42:15 +0000793
794 // Try to predict the branch, using loop info to guide us.
795 // General heuristics are:
796 // - backedge -> 90% taken
797 // - early exit -> 20% taken
Owen Andersone3cc84a2010-10-01 22:45:50 +0000798 // - branch predictor confidence -> 90%
Benjamin Kramer6406d002010-09-29 22:38:50 +0000799 float Prediction = 0.5f;
Owen Andersone3cc84a2010-10-01 22:45:50 +0000800 float Confidence = 0.9f;
Owen Anderson7571ee72010-09-28 20:42:15 +0000801 MachineLoop *Loop = MLI->getLoopFor(BB);
802 if (Loop) {
803 if (TrueBBI.BB == Loop->getHeader())
Benjamin Kramer6406d002010-09-29 22:38:50 +0000804 Prediction = 0.9f;
Owen Anderson7571ee72010-09-28 20:42:15 +0000805 else if (FalseBBI.BB == Loop->getHeader())
Benjamin Kramer6406d002010-09-29 22:38:50 +0000806 Prediction = 0.1f;
807
Owen Anderson7571ee72010-09-28 20:42:15 +0000808 MachineLoop *TrueLoop = MLI->getLoopFor(TrueBBI.BB);
809 MachineLoop *FalseLoop = MLI->getLoopFor(FalseBBI.BB);
810 if (!TrueLoop || TrueLoop->getParentLoop() == Loop)
Benjamin Kramer6406d002010-09-29 22:38:50 +0000811 Prediction = 0.2f;
Owen Anderson7571ee72010-09-28 20:42:15 +0000812 else if (!FalseLoop || FalseLoop->getParentLoop() == Loop)
Benjamin Kramer6406d002010-09-29 22:38:50 +0000813 Prediction = 0.8f;
Owen Anderson7571ee72010-09-28 20:42:15 +0000814 }
815
Evan Chenga1a87872007-06-18 08:37:25 +0000816 if (CanRevCond && ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000817 MeetIfcvtSizeLimit(*TrueBBI.BB, (TrueBBI.NonPredSize - (Dups + Dups2) +
818 TrueBBI.ExtraCost),
819 *FalseBBI.BB, (FalseBBI.NonPredSize - (Dups + Dups2) +
820 FalseBBI.ExtraCost),
Owen Andersone3cc84a2010-10-01 22:45:50 +0000821 Prediction, Confidence) &&
Evan Chengac5f1422007-06-08 09:36:04 +0000822 FeasibilityAnalysis(TrueBBI, BBI.BrCond) &&
823 FeasibilityAnalysis(FalseBBI, RevCond)) {
Evan Cheng4e654852007-05-16 02:00:57 +0000824 // Diamond:
825 // EBB
826 // / \_
827 // | |
828 // TBB FBB
829 // \ /
Evan Cheng86cbfea2007-05-18 00:20:58 +0000830 // TailBB
Evan Cheng993fc952007-06-05 23:46:14 +0000831 // Note TailBB can be empty.
Evan Chenga1a87872007-06-18 08:37:25 +0000832 Tokens.push_back(new IfcvtToken(BBI, ICDiamond, TNeedSub|FNeedSub, Dups,
833 Dups2));
Evan Chenge882fca2007-06-16 09:34:52 +0000834 Enqueued = true;
835 }
836
Owen Andersone3cc84a2010-10-01 22:45:50 +0000837 if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction, Confidence) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000838 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000839 Prediction, Confidence) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000840 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
841 // Triangle:
842 // EBB
843 // | \_
844 // | |
845 // | TBB
846 // | /
847 // FBB
848 Tokens.push_back(new IfcvtToken(BBI, ICTriangle, TNeedSub, Dups));
849 Enqueued = true;
850 }
Bob Wilson92fffe02010-06-15 22:18:54 +0000851
Owen Andersone3cc84a2010-10-01 22:45:50 +0000852 if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction, Confidence) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000853 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000854 Prediction, Confidence) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000855 FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
856 Tokens.push_back(new IfcvtToken(BBI, ICTriangleRev, TNeedSub, Dups));
857 Enqueued = true;
858 }
859
Owen Andersone3cc84a2010-10-01 22:45:50 +0000860 if (ValidSimple(TrueBBI, Dups, Prediction, Confidence) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000861 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000862 Prediction, Confidence) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000863 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
864 // Simple (split, no rejoin):
865 // EBB
866 // | \_
867 // | |
868 // | TBB---> exit
Bob Wilson92fffe02010-06-15 22:18:54 +0000869 // |
Evan Chenge882fca2007-06-16 09:34:52 +0000870 // FBB
871 Tokens.push_back(new IfcvtToken(BBI, ICSimple, TNeedSub, Dups));
872 Enqueued = true;
873 }
874
875 if (CanRevCond) {
876 // Try the other path...
Owen Andersone3cc84a2010-10-01 22:45:50 +0000877 if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
878 1.0-Prediction, Confidence) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000879 MeetIfcvtSizeLimit(*FalseBBI.BB,
880 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000881 1.0-Prediction, Confidence) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000882 FeasibilityAnalysis(FalseBBI, RevCond, true)) {
883 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFalse, FNeedSub, Dups));
884 Enqueued = true;
885 }
886
Owen Andersone3cc84a2010-10-01 22:45:50 +0000887 if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
888 1.0-Prediction, Confidence) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000889 MeetIfcvtSizeLimit(*FalseBBI.BB,
890 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000891 1.0-Prediction, Confidence) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000892 FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
893 Tokens.push_back(new IfcvtToken(BBI, ICTriangleFRev, FNeedSub, Dups));
894 Enqueued = true;
895 }
896
Owen Andersone3cc84a2010-10-01 22:45:50 +0000897 if (ValidSimple(FalseBBI, Dups, 1.0-Prediction, Confidence) &&
Bob Wilson2ad40d32010-10-26 00:02:21 +0000898 MeetIfcvtSizeLimit(*FalseBBI.BB,
899 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
Owen Andersone3cc84a2010-10-01 22:45:50 +0000900 1.0-Prediction, Confidence) &&
Evan Chenge882fca2007-06-16 09:34:52 +0000901 FeasibilityAnalysis(FalseBBI, RevCond)) {
902 Tokens.push_back(new IfcvtToken(BBI, ICSimpleFalse, FNeedSub, Dups));
903 Enqueued = true;
Evan Chengb6665f62007-06-04 06:47:22 +0000904 }
Evan Cheng4e654852007-05-16 02:00:57 +0000905 }
Evan Cheng4e654852007-05-16 02:00:57 +0000906
Evan Chenge882fca2007-06-16 09:34:52 +0000907 BBI.IsEnqueued = Enqueued;
Evan Cheng9618bca2007-06-11 22:26:22 +0000908 BBI.IsBeingAnalyzed = false;
909 BBI.IsAnalyzed = true;
910 return BBI;
Evan Chengcf6cc112007-05-18 18:14:37 +0000911}
912
Evan Cheng82582102007-05-30 19:49:19 +0000913/// AnalyzeBlocks - Analyze all blocks and find entries for all if-conversion
Bob Wilson6fb124b2010-06-15 18:57:15 +0000914/// candidates.
915void IfConverter::AnalyzeBlocks(MachineFunction &MF,
Evan Chenge882fca2007-06-16 09:34:52 +0000916 std::vector<IfcvtToken*> &Tokens) {
Evan Cheng36489bb2007-05-18 19:26:33 +0000917 std::set<MachineBasicBlock*> Visited;
Evan Cheng82582102007-05-30 19:49:19 +0000918 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
919 for (idf_ext_iterator<MachineBasicBlock*> I=idf_ext_begin(Roots[i],Visited),
920 E = idf_ext_end(Roots[i], Visited); I != E; ++I) {
921 MachineBasicBlock *BB = *I;
Evan Chenge882fca2007-06-16 09:34:52 +0000922 AnalyzeBlock(BB, Tokens);
Evan Chenga6b4f432007-05-21 22:22:58 +0000923 }
Evan Cheng4e654852007-05-16 02:00:57 +0000924 }
Evan Cheng82582102007-05-30 19:49:19 +0000925
Evan Cheng5f702182007-06-01 00:12:12 +0000926 // Sort to favor more complex ifcvt scheme.
Evan Chenge882fca2007-06-16 09:34:52 +0000927 std::stable_sort(Tokens.begin(), Tokens.end(), IfcvtTokenCmp);
Evan Cheng4e654852007-05-16 02:00:57 +0000928}
929
Evan Cheng7e75ba82007-06-08 22:01:07 +0000930/// canFallThroughTo - Returns true either if ToBB is the next block after BB or
931/// that all the intervening blocks are empty (given BB can fall through to its
932/// next block).
933static bool canFallThroughTo(MachineBasicBlock *BB, MachineBasicBlock *ToBB) {
Evan Cheng46df4eb2010-06-16 07:35:02 +0000934 MachineFunction::iterator PI = BB;
935 MachineFunction::iterator I = llvm::next(PI);
Evan Chengc53ef582007-06-05 07:05:25 +0000936 MachineFunction::iterator TI = ToBB;
937 MachineFunction::iterator E = BB->getParent()->end();
Evan Cheng46df4eb2010-06-16 07:35:02 +0000938 while (I != TI) {
939 // Check isSuccessor to avoid case where the next block is empty, but
940 // it's not a successor.
941 if (I == E || !I->empty() || !PI->isSuccessor(I))
Evan Chengb6665f62007-06-04 06:47:22 +0000942 return false;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000943 PI = I++;
944 }
Evan Chengb6665f62007-06-04 06:47:22 +0000945 return true;
Evan Chenga6b4f432007-05-21 22:22:58 +0000946}
947
Evan Chenga1a87872007-06-18 08:37:25 +0000948/// InvalidatePreds - Invalidate predecessor BB info so it would be re-analyzed
949/// to determine if it can be if-converted. If predecessor is already enqueued,
950/// dequeue it!
951void IfConverter::InvalidatePreds(MachineBasicBlock *BB) {
Evan Chenga13aa952007-05-23 07:23:16 +0000952 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
953 E = BB->pred_end(); PI != E; ++PI) {
954 BBInfo &PBBI = BBAnalysis[(*PI)->getNumber()];
Evan Chengbc198ee2007-06-14 23:34:09 +0000955 if (PBBI.IsDone || PBBI.BB == BB)
Evan Chenge37e2432007-06-14 23:13:19 +0000956 continue;
Evan Chengbc198ee2007-06-14 23:34:09 +0000957 PBBI.IsAnalyzed = false;
958 PBBI.IsEnqueued = false;
Evan Chenga13aa952007-05-23 07:23:16 +0000959 }
960}
961
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000962/// InsertUncondBranch - Inserts an unconditional branch from BB to ToBB.
963///
964static void InsertUncondBranch(MachineBasicBlock *BB, MachineBasicBlock *ToBB,
965 const TargetInstrInfo *TII) {
Stuart Hastings3bf91252010-06-17 22:43:56 +0000966 DebugLoc dl; // FIXME: this is nowhere
Dan Gohman1501cdb2008-08-22 16:07:55 +0000967 SmallVector<MachineOperand, 0> NoCond;
Stuart Hastings3bf91252010-06-17 22:43:56 +0000968 TII->InsertBranch(*BB, ToBB, NULL, NoCond, dl);
Evan Chengc8ed9ba2007-05-29 22:31:16 +0000969}
970
Evan Cheng7e75ba82007-06-08 22:01:07 +0000971/// RemoveExtraEdges - Remove true / false edges if either / both are no longer
972/// successors.
973void IfConverter::RemoveExtraEdges(BBInfo &BBI) {
974 MachineBasicBlock *TBB = NULL, *FBB = NULL;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000975 SmallVector<MachineOperand, 4> Cond;
Evan Chengc4047a82007-06-18 22:44:57 +0000976 if (!TII->AnalyzeBranch(*BBI.BB, TBB, FBB, Cond))
977 BBI.BB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng7e75ba82007-06-08 22:01:07 +0000978}
979
Evan Cheng46df4eb2010-06-16 07:35:02 +0000980/// InitPredRedefs / UpdatePredRedefs - Defs by predicated instructions are
981/// modeled as read + write (sort like two-address instructions). These
982/// routines track register liveness and add implicit uses to if-converted
983/// instructions to conform to the model.
984static void InitPredRedefs(MachineBasicBlock *BB, SmallSet<unsigned,4> &Redefs,
985 const TargetRegisterInfo *TRI) {
986 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
987 E = BB->livein_end(); I != E; ++I) {
988 unsigned Reg = *I;
989 Redefs.insert(Reg);
990 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
991 *Subreg; ++Subreg)
992 Redefs.insert(*Subreg);
993 }
994}
995
996static void UpdatePredRedefs(MachineInstr *MI, SmallSet<unsigned,4> &Redefs,
997 const TargetRegisterInfo *TRI,
998 bool AddImpUse = false) {
999 SmallVector<unsigned, 4> Defs;
1000 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1001 const MachineOperand &MO = MI->getOperand(i);
1002 if (!MO.isReg())
1003 continue;
1004 unsigned Reg = MO.getReg();
1005 if (!Reg)
1006 continue;
1007 if (MO.isDef())
1008 Defs.push_back(Reg);
1009 else if (MO.isKill()) {
1010 Redefs.erase(Reg);
1011 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1012 Redefs.erase(*SR);
1013 }
1014 }
1015 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1016 unsigned Reg = Defs[i];
1017 if (Redefs.count(Reg)) {
1018 if (AddImpUse)
1019 // Treat predicated update as read + write.
1020 MI->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
Jim Grosbach135ec502010-06-25 22:02:28 +00001021 true/*IsImp*/,false/*IsKill*/));
Evan Cheng46df4eb2010-06-16 07:35:02 +00001022 } else {
1023 Redefs.insert(Reg);
1024 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
1025 Redefs.insert(*SR);
1026 }
1027 }
1028}
1029
1030static void UpdatePredRedefs(MachineBasicBlock::iterator I,
1031 MachineBasicBlock::iterator E,
1032 SmallSet<unsigned,4> &Redefs,
1033 const TargetRegisterInfo *TRI) {
1034 while (I != E) {
1035 UpdatePredRedefs(I, Redefs, TRI);
1036 ++I;
1037 }
1038}
1039
Evan Chengb6665f62007-06-04 06:47:22 +00001040/// IfConvertSimple - If convert a simple (split, no rejoin) sub-CFG.
Evan Chenga6b4f432007-05-21 22:22:58 +00001041///
Evan Chenge882fca2007-06-16 09:34:52 +00001042bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenga6b4f432007-05-21 22:22:58 +00001043 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1044 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1045 BBInfo *CvtBBI = &TrueBBI;
1046 BBInfo *NextBBI = &FalseBBI;
Evan Chenga13aa952007-05-23 07:23:16 +00001047
Owen Anderson44eb65c2008-08-14 22:49:33 +00001048 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chenge882fca2007-06-16 09:34:52 +00001049 if (Kind == ICSimpleFalse)
Evan Chengb5a06902007-06-01 20:29:21 +00001050 std::swap(CvtBBI, NextBBI);
Evan Chenga2acf842007-06-15 21:18:05 +00001051
Evan Chenga1a87872007-06-18 08:37:25 +00001052 if (CvtBBI->IsDone ||
1053 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Chenga2acf842007-06-15 21:18:05 +00001054 // Something has changed. It's no longer safe to predicate this block.
Evan Chenga2acf842007-06-15 21:18:05 +00001055 BBI.IsAnalyzed = false;
1056 CvtBBI->IsAnalyzed = false;
1057 return false;
Evan Chengb5a06902007-06-01 20:29:21 +00001058 }
Evan Chenga13aa952007-05-23 07:23:16 +00001059
Evan Chenge882fca2007-06-16 09:34:52 +00001060 if (Kind == ICSimpleFalse)
Dan Gohman279c22e2008-10-21 03:29:32 +00001061 if (TII->ReverseBranchCondition(Cond))
1062 assert(false && "Unable to reverse branch condition!");
Evan Chenga2acf842007-06-15 21:18:05 +00001063
Bob Wilson54eee522010-06-19 05:33:57 +00001064 // Initialize liveins to the first BB. These are potentiall redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001065 // predicated instructions.
1066 SmallSet<unsigned, 4> Redefs;
1067 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1068 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1069
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001070 if (CvtBBI->BB->pred_size() > 1) {
1071 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson9c4856a2009-05-13 23:25:24 +00001072 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001073 // the entry block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001074 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001075 } else {
Evan Cheng46df4eb2010-06-16 07:35:02 +00001076 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Evan Chenga6b4f432007-05-21 22:22:58 +00001077
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001078 // Merge converted block into entry block.
1079 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1080 MergeBlocks(BBI, *CvtBBI);
1081 }
Evan Chengd4de6d92007-06-07 02:12:15 +00001082
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001083 bool IterIfcvt = true;
Evan Cheng7e75ba82007-06-08 22:01:07 +00001084 if (!canFallThroughTo(BBI.BB, NextBBI->BB)) {
Evan Chengc8ed9ba2007-05-29 22:31:16 +00001085 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001086 BBI.HasFallThrough = false;
Evan Chengac5f1422007-06-08 09:36:04 +00001087 // Now ifcvt'd block will look like this:
1088 // BB:
1089 // ...
1090 // t, f = cmp
1091 // if t op
1092 // b BBf
1093 //
1094 // We cannot further ifcvt this block because the unconditional branch
1095 // will have to be predicated on the new condition, that will not be
1096 // available if cmp executes.
1097 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001098 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001099
Evan Cheng7e75ba82007-06-08 22:01:07 +00001100 RemoveExtraEdges(BBI);
1101
Evan Chenga13aa952007-05-23 07:23:16 +00001102 // Update block info. BB can be iteratively if-converted.
Evan Cheng9618bca2007-06-11 22:26:22 +00001103 if (!IterIfcvt)
1104 BBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001105 InvalidatePreds(BBI.BB);
Evan Cheng9618bca2007-06-11 22:26:22 +00001106 CvtBBI->IsDone = true;
Evan Chenga6b4f432007-05-21 22:22:58 +00001107
1108 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001109 return true;
1110}
1111
Evan Chengd6ddc302007-05-16 21:54:37 +00001112/// IfConvertTriangle - If convert a triangle sub-CFG.
1113///
Evan Chenge882fca2007-06-16 09:34:52 +00001114bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
Evan Chenga13aa952007-05-23 07:23:16 +00001115 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001116 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1117 BBInfo *CvtBBI = &TrueBBI;
1118 BBInfo *NextBBI = &FalseBBI;
Stuart Hastings3bf91252010-06-17 22:43:56 +00001119 DebugLoc dl; // FIXME: this is nowhere
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001120
Owen Anderson44eb65c2008-08-14 22:49:33 +00001121 SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
Evan Chenge882fca2007-06-16 09:34:52 +00001122 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001123 std::swap(CvtBBI, NextBBI);
Evan Chenga2acf842007-06-15 21:18:05 +00001124
Evan Chenga1a87872007-06-18 08:37:25 +00001125 if (CvtBBI->IsDone ||
1126 (CvtBBI->CannotBeCopied && CvtBBI->BB->pred_size() > 1)) {
Evan Chenga2acf842007-06-15 21:18:05 +00001127 // Something has changed. It's no longer safe to predicate this block.
Evan Chenga2acf842007-06-15 21:18:05 +00001128 BBI.IsAnalyzed = false;
1129 CvtBBI->IsAnalyzed = false;
1130 return false;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001131 }
Evan Chenga2acf842007-06-15 21:18:05 +00001132
Evan Chenge882fca2007-06-16 09:34:52 +00001133 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
Dan Gohman279c22e2008-10-21 03:29:32 +00001134 if (TII->ReverseBranchCondition(Cond))
1135 assert(false && "Unable to reverse branch condition!");
Evan Chenga2acf842007-06-15 21:18:05 +00001136
Evan Chenge882fca2007-06-16 09:34:52 +00001137 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
Dan Gohman279c22e2008-10-21 03:29:32 +00001138 if (ReverseBranchCondition(*CvtBBI)) {
1139 // BB has been changed, modify its predecessors (except for this
1140 // one) so they don't get ifcvt'ed based on bad intel.
1141 for (MachineBasicBlock::pred_iterator PI = CvtBBI->BB->pred_begin(),
1142 E = CvtBBI->BB->pred_end(); PI != E; ++PI) {
1143 MachineBasicBlock *PBB = *PI;
1144 if (PBB == BBI.BB)
1145 continue;
1146 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1147 if (PBBI.IsEnqueued) {
1148 PBBI.IsAnalyzed = false;
1149 PBBI.IsEnqueued = false;
1150 }
Evan Chengbc198ee2007-06-14 23:34:09 +00001151 }
Evan Chengcc8fb462007-06-12 23:54:05 +00001152 }
1153 }
Evan Cheng8c529382007-06-01 07:41:07 +00001154
Bob Wilson54eee522010-06-19 05:33:57 +00001155 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001156 // predicated instructions.
1157 SmallSet<unsigned, 4> Redefs;
1158 InitPredRedefs(CvtBBI->BB, Redefs, TRI);
1159 InitPredRedefs(NextBBI->BB, Redefs, TRI);
1160
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001161 bool HasEarlyExit = CvtBBI->FalseBB != NULL;
Bob Wilson8eab75f2010-06-29 00:55:23 +00001162 if (CvtBBI->BB->pred_size() > 1) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001163 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson9c4856a2009-05-13 23:25:24 +00001164 // Copy instructions in the true block, predicate them, and add them to
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001165 // the entry block.
Evan Cheng46df4eb2010-06-16 07:35:02 +00001166 CopyAndPredicateBlock(BBI, *CvtBBI, Cond, Redefs, true);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001167 } else {
1168 // Predicate the 'true' block after removing its branch.
1169 CvtBBI->NonPredSize -= TII->RemoveBranch(*CvtBBI->BB);
Evan Cheng46df4eb2010-06-16 07:35:02 +00001170 PredicateBlock(*CvtBBI, CvtBBI->BB->end(), Cond, Redefs);
Evan Chenga6b4f432007-05-21 22:22:58 +00001171
Evan Chengc4047a82007-06-18 22:44:57 +00001172 // Now merge the entry of the triangle with the true block.
1173 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
Bob Wilson8eab75f2010-06-29 00:55:23 +00001174 MergeBlocks(BBI, *CvtBBI, false);
Evan Chengc4047a82007-06-18 22:44:57 +00001175 }
1176
Evan Chengb6665f62007-06-04 06:47:22 +00001177 // If 'true' block has a 'false' successor, add an exit branch to it.
Evan Cheng8ed680c2007-06-05 01:31:40 +00001178 if (HasEarlyExit) {
Owen Anderson44eb65c2008-08-14 22:49:33 +00001179 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1180 CvtBBI->BrCond.end());
Evan Cheng8c529382007-06-01 07:41:07 +00001181 if (TII->ReverseBranchCondition(RevCond))
1182 assert(false && "Unable to reverse branch condition!");
Stuart Hastings3bf91252010-06-17 22:43:56 +00001183 TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
Evan Chengc4047a82007-06-18 22:44:57 +00001184 BBI.BB->addSuccessor(CvtBBI->FalseBB);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001185 }
Evan Chengac5f1422007-06-08 09:36:04 +00001186
1187 // Merge in the 'false' block if the 'false' block has no other
Bob Wilson9c4856a2009-05-13 23:25:24 +00001188 // predecessors. Otherwise, add an unconditional branch to 'false'.
Evan Chengf5305f92007-06-05 00:07:37 +00001189 bool FalseBBDead = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001190 bool IterIfcvt = true;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001191 bool isFallThrough = canFallThroughTo(BBI.BB, NextBBI->BB);
Evan Chengf4769612007-06-07 08:13:00 +00001192 if (!isFallThrough) {
1193 // Only merge them if the true block does not fallthrough to the false
1194 // block. By not merging them, we make it possible to iteratively
1195 // ifcvt the blocks.
Evan Chenga1a87872007-06-18 08:37:25 +00001196 if (!HasEarlyExit &&
1197 NextBBI->BB->pred_size() == 1 && !NextBBI->HasFallThrough) {
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001198 MergeBlocks(BBI, *NextBBI);
Evan Chengf4769612007-06-07 08:13:00 +00001199 FalseBBDead = true;
Evan Chengf4769612007-06-07 08:13:00 +00001200 } else {
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001201 InsertUncondBranch(BBI.BB, NextBBI->BB, TII);
1202 BBI.HasFallThrough = false;
Evan Chengf4769612007-06-07 08:13:00 +00001203 }
Evan Chengac5f1422007-06-08 09:36:04 +00001204 // Mixed predicated and unpredicated code. This cannot be iteratively
1205 // predicated.
1206 IterIfcvt = false;
Evan Cheng3d6f60e2007-06-06 02:08:52 +00001207 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001208
Evan Cheng7e75ba82007-06-08 22:01:07 +00001209 RemoveExtraEdges(BBI);
Evan Chenga6b4f432007-05-21 22:22:58 +00001210
Evan Chenga13aa952007-05-23 07:23:16 +00001211 // Update block info. BB can be iteratively if-converted.
Bob Wilson92fffe02010-06-15 22:18:54 +00001212 if (!IterIfcvt)
Evan Cheng9618bca2007-06-11 22:26:22 +00001213 BBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001214 InvalidatePreds(BBI.BB);
Evan Cheng9618bca2007-06-11 22:26:22 +00001215 CvtBBI->IsDone = true;
Evan Chengf5305f92007-06-05 00:07:37 +00001216 if (FalseBBDead)
Evan Cheng9618bca2007-06-11 22:26:22 +00001217 NextBBI->IsDone = true;
Evan Chenga6b4f432007-05-21 22:22:58 +00001218
1219 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001220 return true;
Evan Cheng4e654852007-05-16 02:00:57 +00001221}
1222
Evan Chengd6ddc302007-05-16 21:54:37 +00001223/// IfConvertDiamond - If convert a diamond sub-CFG.
1224///
Evan Chenga1a87872007-06-18 08:37:25 +00001225bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
1226 unsigned NumDups1, unsigned NumDups2) {
Evan Chengb6665f62007-06-04 06:47:22 +00001227 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
Evan Chengcf6cc112007-05-18 18:14:37 +00001228 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
Evan Chenge882fca2007-06-16 09:34:52 +00001229 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
Bob Wilson9c4856a2009-05-13 23:25:24 +00001230 // True block must fall through or end with an unanalyzable terminator.
Evan Chenge882fca2007-06-16 09:34:52 +00001231 if (!TailBB) {
Evan Chenga1a87872007-06-18 08:37:25 +00001232 if (blockAlwaysFallThrough(TrueBBI))
1233 TailBB = FalseBBI.TrueBB;
1234 assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
Evan Cheng4e654852007-05-16 02:00:57 +00001235 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001236
Evan Chenga1a87872007-06-18 08:37:25 +00001237 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1238 TrueBBI.BB->pred_size() > 1 ||
1239 FalseBBI.BB->pred_size() > 1) {
1240 // Something has changed. It's no longer safe to predicate these blocks.
1241 BBI.IsAnalyzed = false;
1242 TrueBBI.IsAnalyzed = false;
1243 FalseBBI.IsAnalyzed = false;
1244 return false;
Evan Chenga6b4f432007-05-21 22:22:58 +00001245 }
Evan Chenga1a87872007-06-18 08:37:25 +00001246
Bob Wilson8eab75f2010-06-29 00:55:23 +00001247 // Put the predicated instructions from the 'true' block before the
1248 // instructions from the 'false' block, unless the true block would clobber
1249 // the predicate, in which case, do the opposite.
Evan Cheng993fc952007-06-05 23:46:14 +00001250 BBInfo *BBI1 = &TrueBBI;
1251 BBInfo *BBI2 = &FalseBBI;
Owen Anderson44eb65c2008-08-14 22:49:33 +00001252 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
Dan Gohman279c22e2008-10-21 03:29:32 +00001253 if (TII->ReverseBranchCondition(RevCond))
1254 assert(false && "Unable to reverse branch condition!");
Owen Anderson44eb65c2008-08-14 22:49:33 +00001255 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1256 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
Evan Chenge7052132007-06-06 00:57:55 +00001257
Evan Chenge882fca2007-06-16 09:34:52 +00001258 // Figure out the more profitable ordering.
1259 bool DoSwap = false;
1260 if (TrueBBI.ClobbersPred && !FalseBBI.ClobbersPred)
1261 DoSwap = true;
1262 else if (TrueBBI.ClobbersPred == FalseBBI.ClobbersPred) {
Evan Chengc4047a82007-06-18 22:44:57 +00001263 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
Evan Chenge882fca2007-06-16 09:34:52 +00001264 DoSwap = true;
Evan Chenge882fca2007-06-16 09:34:52 +00001265 }
1266 if (DoSwap) {
Evan Chenge7052132007-06-06 00:57:55 +00001267 std::swap(BBI1, BBI2);
1268 std::swap(Cond1, Cond2);
Evan Chenge7052132007-06-06 00:57:55 +00001269 }
Evan Cheng993fc952007-06-05 23:46:14 +00001270
Evan Chenga1a87872007-06-18 08:37:25 +00001271 // Remove the conditional branch from entry to the blocks.
1272 BBI.NonPredSize -= TII->RemoveBranch(*BBI.BB);
1273
Jim Grosbach135ec502010-06-25 22:02:28 +00001274 // Initialize liveins to the first BB. These are potentially redefined by
Evan Cheng46df4eb2010-06-16 07:35:02 +00001275 // predicated instructions.
1276 SmallSet<unsigned, 4> Redefs;
1277 InitPredRedefs(BBI1->BB, Redefs, TRI);
1278
Evan Chenga1a87872007-06-18 08:37:25 +00001279 // Remove the duplicated instructions at the beginnings of both paths.
1280 MachineBasicBlock::iterator DI1 = BBI1->BB->begin();
1281 MachineBasicBlock::iterator DI2 = BBI2->BB->begin();
Jim Grosbachc834f412010-06-14 21:30:32 +00001282 MachineBasicBlock::iterator DIE1 = BBI1->BB->end();
1283 MachineBasicBlock::iterator DIE2 = BBI2->BB->end();
1284 // Skip dbg_value instructions
1285 while (DI1 != DIE1 && DI1->isDebugValue())
1286 ++DI1;
1287 while (DI2 != DIE2 && DI2->isDebugValue())
1288 ++DI2;
Evan Chenga1a87872007-06-18 08:37:25 +00001289 BBI1->NonPredSize -= NumDups1;
1290 BBI2->NonPredSize -= NumDups1;
Jim Grosbachd459f452010-06-28 20:26:00 +00001291
1292 // Skip past the dups on each side separately since there may be
1293 // differing dbg_value entries.
1294 for (unsigned i = 0; i < NumDups1; ++DI1) {
1295 if (!DI1->isDebugValue())
1296 ++i;
1297 }
Jim Grosbach9f054f02010-06-25 23:05:46 +00001298 while (NumDups1 != 0) {
Evan Chenga1a87872007-06-18 08:37:25 +00001299 ++DI2;
Jim Grosbachd459f452010-06-28 20:26:00 +00001300 if (!DI2->isDebugValue())
1301 --NumDups1;
Evan Chenga1a87872007-06-18 08:37:25 +00001302 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001303
1304 UpdatePredRedefs(BBI1->BB->begin(), DI1, Redefs, TRI);
Evan Chenga1a87872007-06-18 08:37:25 +00001305 BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
1306 BBI2->BB->erase(BBI2->BB->begin(), DI2);
1307
Evan Cheng993fc952007-06-05 23:46:14 +00001308 // Predicate the 'true' block after removing its branch.
1309 BBI1->NonPredSize -= TII->RemoveBranch(*BBI1->BB);
Evan Chenga1a87872007-06-18 08:37:25 +00001310 DI1 = BBI1->BB->end();
Jim Grosbachc834f412010-06-14 21:30:32 +00001311 for (unsigned i = 0; i != NumDups2; ) {
1312 // NumDups2 only counted non-dbg_value instructions, so this won't
1313 // run off the head of the list.
1314 assert (DI1 != BBI1->BB->begin());
Evan Chenga1a87872007-06-18 08:37:25 +00001315 --DI1;
Jim Grosbachc834f412010-06-14 21:30:32 +00001316 // skip dbg_value instructions
1317 if (!DI1->isDebugValue())
1318 ++i;
1319 }
Evan Chenga1a87872007-06-18 08:37:25 +00001320 BBI1->BB->erase(DI1, BBI1->BB->end());
Evan Cheng46df4eb2010-06-16 07:35:02 +00001321 PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
Evan Cheng993fc952007-06-05 23:46:14 +00001322
Evan Cheng993fc952007-06-05 23:46:14 +00001323 // Predicate the 'false' block.
Evan Chenga1a87872007-06-18 08:37:25 +00001324 BBI2->NonPredSize -= TII->RemoveBranch(*BBI2->BB);
1325 DI2 = BBI2->BB->end();
1326 while (NumDups2 != 0) {
Jim Grosbachc834f412010-06-14 21:30:32 +00001327 // NumDups2 only counted non-dbg_value instructions, so this won't
1328 // run off the head of the list.
1329 assert (DI2 != BBI2->BB->begin());
Evan Chenga1a87872007-06-18 08:37:25 +00001330 --DI2;
Jim Grosbachc834f412010-06-14 21:30:32 +00001331 // skip dbg_value instructions
1332 if (!DI2->isDebugValue())
1333 --NumDups2;
Evan Chenga1a87872007-06-18 08:37:25 +00001334 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001335 PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
Evan Cheng993fc952007-06-05 23:46:14 +00001336
Evan Chengc4047a82007-06-18 22:44:57 +00001337 // Merge the true block into the entry of the diamond.
Bob Wilson8eab75f2010-06-29 00:55:23 +00001338 MergeBlocks(BBI, *BBI1, TailBB == 0);
1339 MergeBlocks(BBI, *BBI2, TailBB == 0);
Evan Chenge7052132007-06-06 00:57:55 +00001340
Bob Wilson9c4856a2009-05-13 23:25:24 +00001341 // If the if-converted block falls through or unconditionally branches into
1342 // the tail block, and the tail block does not have other predecessors, then
Evan Chenga1a87872007-06-18 08:37:25 +00001343 // fold the tail block in as well. Otherwise, unless it falls through to the
1344 // tail, add a unconditional branch to it.
1345 if (TailBB) {
Evan Chenge882fca2007-06-16 09:34:52 +00001346 BBInfo TailBBI = BBAnalysis[TailBB->getNumber()];
Bob Wilson8eab75f2010-06-29 00:55:23 +00001347 bool CanMergeTail = !TailBBI.HasFallThrough;
1348 // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
1349 // check if there are any other predecessors besides those.
1350 unsigned NumPreds = TailBB->pred_size();
1351 if (NumPreds > 1)
1352 CanMergeTail = false;
1353 else if (NumPreds == 1 && CanMergeTail) {
1354 MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
1355 if (*PI != BBI1->BB && *PI != BBI2->BB)
1356 CanMergeTail = false;
1357 }
1358 if (CanMergeTail) {
Evan Chengc4047a82007-06-18 22:44:57 +00001359 MergeBlocks(BBI, TailBBI);
Evan Chenga1a87872007-06-18 08:37:25 +00001360 TailBBI.IsDone = true;
1361 } else {
Bob Wilson8eab75f2010-06-29 00:55:23 +00001362 BBI.BB->addSuccessor(TailBB);
Evan Chengc4047a82007-06-18 22:44:57 +00001363 InsertUncondBranch(BBI.BB, TailBB, TII);
1364 BBI.HasFallThrough = false;
Evan Chenga1a87872007-06-18 08:37:25 +00001365 }
Evan Chenga6b4f432007-05-21 22:22:58 +00001366 }
1367
Bob Wilson8eab75f2010-06-29 00:55:23 +00001368 // RemoveExtraEdges won't work if the block has an unanalyzable branch,
1369 // which can happen here if TailBB is unanalyzable and is merged, so
1370 // explicitly remove BBI1 and BBI2 as successors.
1371 BBI.BB->removeSuccessor(BBI1->BB);
1372 BBI.BB->removeSuccessor(BBI2->BB);
Evan Cheng7e75ba82007-06-08 22:01:07 +00001373 RemoveExtraEdges(BBI);
1374
Evan Cheng993fc952007-06-05 23:46:14 +00001375 // Update block info.
Evan Cheng9618bca2007-06-11 22:26:22 +00001376 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
Evan Chenga1a87872007-06-18 08:37:25 +00001377 InvalidatePreds(BBI.BB);
Evan Chenga6b4f432007-05-21 22:22:58 +00001378
1379 // FIXME: Must maintain LiveIns.
Evan Chenga6b4f432007-05-21 22:22:58 +00001380 return true;
Evan Cheng4e654852007-05-16 02:00:57 +00001381}
1382
Evan Chenga1a87872007-06-18 08:37:25 +00001383/// PredicateBlock - Predicate instructions from the start of the block to the
1384/// specified end with the specified condition.
Evan Chenga13aa952007-05-23 07:23:16 +00001385void IfConverter::PredicateBlock(BBInfo &BBI,
Evan Chenga1a87872007-06-18 08:37:25 +00001386 MachineBasicBlock::iterator E,
Evan Cheng46df4eb2010-06-16 07:35:02 +00001387 SmallVectorImpl<MachineOperand> &Cond,
1388 SmallSet<unsigned, 4> &Redefs) {
Evan Chenga1a87872007-06-18 08:37:25 +00001389 for (MachineBasicBlock::iterator I = BBI.BB->begin(); I != E; ++I) {
Jim Grosbach870c8052010-06-04 23:01:26 +00001390 if (I->isDebugValue() || TII->isPredicated(I))
Evan Chenga13aa952007-05-23 07:23:16 +00001391 continue;
Evan Chengb6665f62007-06-04 06:47:22 +00001392 if (!TII->PredicateInstruction(I, Cond)) {
Torok Edwinf3689232009-07-12 20:07:01 +00001393#ifndef NDEBUG
David Greene083b7ff2010-01-04 22:02:01 +00001394 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwinf3689232009-07-12 20:07:01 +00001395#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001396 llvm_unreachable(0);
Evan Chengd6ddc302007-05-16 21:54:37 +00001397 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001398
Bob Wilson54eee522010-06-19 05:33:57 +00001399 // If the predicated instruction now redefines a register as the result of
Evan Cheng46df4eb2010-06-16 07:35:02 +00001400 // if-conversion, add an implicit kill.
1401 UpdatePredRedefs(I, Redefs, TRI, true);
Evan Cheng4e654852007-05-16 02:00:57 +00001402 }
Evan Chenga13aa952007-05-23 07:23:16 +00001403
Evan Cheng2acdbcc2007-06-08 19:17:12 +00001404 std::copy(Cond.begin(), Cond.end(), std::back_inserter(BBI.Predicate));
1405
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001406 BBI.IsAnalyzed = false;
1407 BBI.NonPredSize = 0;
1408
Dan Gohmanfe601042010-06-22 15:08:57 +00001409 ++NumIfConvBBs;
Evan Chengb6665f62007-06-04 06:47:22 +00001410}
1411
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001412/// CopyAndPredicateBlock - Copy and predicate instructions from source BB to
1413/// the destination block. Skip end of block branches if IgnoreBr is true.
1414void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
Owen Anderson44eb65c2008-08-14 22:49:33 +00001415 SmallVectorImpl<MachineOperand> &Cond,
Evan Cheng46df4eb2010-06-16 07:35:02 +00001416 SmallSet<unsigned, 4> &Redefs,
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001417 bool IgnoreBr) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001418 MachineFunction &MF = *ToBBI.BB->getParent();
1419
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001420 for (MachineBasicBlock::iterator I = FromBBI.BB->begin(),
1421 E = FromBBI.BB->end(); I != E; ++I) {
Chris Lattner749c6f62008-01-07 07:27:27 +00001422 const TargetInstrDesc &TID = I->getDesc();
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001423 // Do not copy the end of the block branches.
Bob Wilsonf50e9522010-06-18 17:07:23 +00001424 if (IgnoreBr && TID.isBranch())
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001425 break;
1426
Dan Gohman8e5f2c62008-07-07 23:14:23 +00001427 MachineInstr *MI = MF.CloneMachineInstr(I);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001428 ToBBI.BB->insert(ToBBI.BB->end(), MI);
Bob Wilson2ad40d32010-10-26 00:02:21 +00001429 ToBBI.NonPredSize++;
Evan Cheng3ef1c872010-09-10 01:29:16 +00001430 unsigned NumOps = TII->getNumMicroOps(MI, InstrItins);
Bob Wilson2ad40d32010-10-26 00:02:21 +00001431 if (NumOps > 1)
1432 ToBBI.ExtraCost += NumOps-1;
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001433
Bob Wilsonf50e9522010-06-18 17:07:23 +00001434 if (!TII->isPredicated(I) && !MI->isDebugValue()) {
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001435 if (!TII->PredicateInstruction(MI, Cond)) {
Torok Edwinf3689232009-07-12 20:07:01 +00001436#ifndef NDEBUG
David Greene083b7ff2010-01-04 22:02:01 +00001437 dbgs() << "Unable to predicate " << *I << "!\n";
Torok Edwinf3689232009-07-12 20:07:01 +00001438#endif
Torok Edwinc23197a2009-07-14 16:55:14 +00001439 llvm_unreachable(0);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001440 }
Evan Cheng46df4eb2010-06-16 07:35:02 +00001441 }
1442
Bob Wilson54eee522010-06-19 05:33:57 +00001443 // If the predicated instruction now redefines a register as the result of
Evan Cheng46df4eb2010-06-16 07:35:02 +00001444 // if-conversion, add an implicit kill.
1445 UpdatePredRedefs(MI, Redefs, TRI, true);
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001446 }
1447
Bob Wilson8eab75f2010-06-29 00:55:23 +00001448 if (!IgnoreBr) {
1449 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1450 FromBBI.BB->succ_end());
1451 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
1452 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Evan Chengc4047a82007-06-18 22:44:57 +00001453
Bob Wilson8eab75f2010-06-29 00:55:23 +00001454 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1455 MachineBasicBlock *Succ = Succs[i];
1456 // Fallthrough edge can't be transferred.
1457 if (Succ == FallThrough)
1458 continue;
1459 ToBBI.BB->addSuccessor(Succ);
1460 }
Evan Chengc4047a82007-06-18 22:44:57 +00001461 }
1462
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001463 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1464 std::back_inserter(ToBBI.Predicate));
1465 std::copy(Cond.begin(), Cond.end(), std::back_inserter(ToBBI.Predicate));
1466
1467 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
1468 ToBBI.IsAnalyzed = false;
1469
Dan Gohmanfe601042010-06-22 15:08:57 +00001470 ++NumDupBBs;
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001471}
1472
Evan Cheng86cbfea2007-05-18 00:20:58 +00001473/// MergeBlocks - Move all instructions from FromBB to the end of ToBB.
Bob Wilson8eab75f2010-06-29 00:55:23 +00001474/// This will leave FromBB as an empty block, so remove all of its
1475/// successor edges except for the fall-through edge. If AddEdges is true,
1476/// i.e., when FromBBI's branch is being moved, add those successor edges to
1477/// ToBBI.
1478void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
Evan Cheng86cbfea2007-05-18 00:20:58 +00001479 ToBBI.BB->splice(ToBBI.BB->end(),
1480 FromBBI.BB, FromBBI.BB->begin(), FromBBI.BB->end());
Evan Chenga13aa952007-05-23 07:23:16 +00001481
Evan Chengd4de6d92007-06-07 02:12:15 +00001482 std::vector<MachineBasicBlock *> Succs(FromBBI.BB->succ_begin(),
1483 FromBBI.BB->succ_end());
Evan Cheng7e75ba82007-06-08 22:01:07 +00001484 MachineBasicBlock *NBB = getNextBlock(FromBBI.BB);
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001485 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : NULL;
Evan Chengb6665f62007-06-04 06:47:22 +00001486
Evan Chengd4de6d92007-06-07 02:12:15 +00001487 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1488 MachineBasicBlock *Succ = Succs[i];
Evan Cheng7e75ba82007-06-08 22:01:07 +00001489 // Fallthrough edge can't be transferred.
Evan Chengd4de6d92007-06-07 02:12:15 +00001490 if (Succ == FallThrough)
1491 continue;
1492 FromBBI.BB->removeSuccessor(Succ);
Bob Wilson8eab75f2010-06-29 00:55:23 +00001493 if (AddEdges)
1494 ToBBI.BB->addSuccessor(Succ);
Evan Chengd4de6d92007-06-07 02:12:15 +00001495 }
1496
Bob Wilson9c4856a2009-05-13 23:25:24 +00001497 // Now FromBBI always falls through to the next block!
Bob Wilson8308e8f2009-05-13 23:48:58 +00001498 if (NBB && !FromBBI.BB->isSuccessor(NBB))
Evan Cheng7e75ba82007-06-08 22:01:07 +00001499 FromBBI.BB->addSuccessor(NBB);
1500
Evan Cheng2c8c3a42007-06-15 07:36:12 +00001501 std::copy(FromBBI.Predicate.begin(), FromBBI.Predicate.end(),
1502 std::back_inserter(ToBBI.Predicate));
1503 FromBBI.Predicate.clear();
1504
Evan Chenga13aa952007-05-23 07:23:16 +00001505 ToBBI.NonPredSize += FromBBI.NonPredSize;
Bob Wilson2ad40d32010-10-26 00:02:21 +00001506 ToBBI.ExtraCost += FromBBI.ExtraCost;
Evan Chenga13aa952007-05-23 07:23:16 +00001507 FromBBI.NonPredSize = 0;
Bob Wilson2ad40d32010-10-26 00:02:21 +00001508 FromBBI.ExtraCost = 0;
Evan Cheng7a655472007-06-06 10:16:17 +00001509
Evan Cheng9618bca2007-06-11 22:26:22 +00001510 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
Evan Cheng1c9f91d2007-06-09 01:03:43 +00001511 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
Evan Cheng86ff2962007-06-14 20:28:52 +00001512 ToBBI.IsAnalyzed = false;
1513 FromBBI.IsAnalyzed = false;
Evan Cheng4e654852007-05-16 02:00:57 +00001514}