blob: abd8994023da70331566ea3205c00da89d060da2 [file] [log] [blame]
Chris Lattnerf48f7772004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf48f7772004-04-19 18:07:02 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattnerf48f7772004-04-19 18:07:02 +00008//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops that contain branches on loop-invariant conditions
11// to have multiple loops. For example, it turns the left into the right code:
12//
13// for (...) if (lic)
14// A for (...)
15// if (lic) A; B; C
16// B else
17// C for (...)
18// A; C
19//
20// This can increase the size of the code exponentially (doubling it every time
21// a loop is unswitched) so we only unswitch if the resultant code will be
22// smaller than a threshold.
23//
24// This pass expects LICM to be run before it to hoist invariant conditions out
25// of the loop, to make the unswitching opportunity obvious.
26//
27//===----------------------------------------------------------------------===//
28
Chris Lattnerf48f7772004-04-19 18:07:02 +000029#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/Statistic.h"
James Molloyefbba722015-09-10 10:22:12 +000033#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000034#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/CodeMetrics.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Analysis/InstructionSimplify.h"
37#include "llvm/Analysis/LoopInfo.h"
38#include "llvm/Analysis/LoopPass.h"
39#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000040#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Constants.h"
42#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000043#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
45#include "llvm/IR/Instructions.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000046#include "llvm/IR/Module.h"
Weiming Zhaof1abad52015-06-23 05:31:09 +000047#include "llvm/IR/MDBuilder.h"
Chris Lattner89762192006-02-09 20:15:48 +000048#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000049#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000050#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
52#include "llvm/Transforms/Utils/Cloning.h"
53#include "llvm/Transforms/Utils/Local.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000054#include <algorithm>
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000055#include <map>
Chris Lattner2826e052006-02-09 19:14:52 +000056#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000057using namespace llvm;
58
Chandler Carruth964daaa2014-04-22 02:55:47 +000059#define DEBUG_TYPE "loop-unswitch"
60
Chris Lattner79a42ac2006-12-19 21:40:18 +000061STATISTIC(NumBranches, "Number of branches unswitched");
62STATISTIC(NumSwitches, "Number of switches unswitched");
63STATISTIC(NumSelects , "Number of selects unswitched");
64STATISTIC(NumTrivial , "Number of unswitches that are trivial");
65STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000066STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner79a42ac2006-12-19 21:40:18 +000067
Stepan Dyatkovskiy2931a592012-01-16 20:48:04 +000068// The specific value of 100 here was chosen based only on intuition and a
Dan Gohman71ca6522009-10-13 17:50:43 +000069// few specific examples.
Dan Gohmand78c4002008-05-13 00:00:25 +000070static cl::opt<unsigned>
71Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000072 cl::init(100), cl::Hidden);
Andrew Trick4104ed92012-04-10 05:14:37 +000073
Dan Gohmand78c4002008-05-13 00:00:25 +000074namespace {
Andrew Trick4104ed92012-04-10 05:14:37 +000075
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000076 class LUAnalysisCache {
77
78 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
79 UnswitchedValsMap;
Andrew Trick4104ed92012-04-10 05:14:37 +000080
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000081 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000082
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000083 struct LoopProperties {
84 unsigned CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +000085 unsigned WasUnswitchedCount;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000086 unsigned SizeEstimation;
87 UnswitchedValsMap UnswitchedVals;
88 };
Andrew Trick4104ed92012-04-10 05:14:37 +000089
90 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000091 // LoopProperties pointer for current loop for better performance.
92 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
93 typedef LoopPropsMap::iterator LoopPropsMapIt;
Andrew Trick4104ed92012-04-10 05:14:37 +000094
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000095 LoopPropsMap LoopsProperties;
Jakub Staszak27da1232013-08-06 17:03:42 +000096 UnswitchedValsMap *CurLoopInstructions;
97 LoopProperties *CurrentLoopProperties;
Andrew Trick4104ed92012-04-10 05:14:37 +000098
Mark Heffernan9b536a62015-06-23 18:26:50 +000099 // A loop unswitching with an estimated cost above this threshold
100 // is not performed. MaxSize is turned into unswitching quota for
101 // the current loop, and reduced correspondingly, though note that
102 // the quota is returned by releaseMemory() when the loop has been
103 // processed, so that MaxSize will return to its previous
104 // value. So in most cases MaxSize will equal the Threshold flag
105 // when a new loop is processed. An exception to that is that
106 // MaxSize will have a smaller value while processing nested loops
107 // that were introduced due to loop unswitching of an outer loop.
108 //
109 // FIXME: The way that MaxSize works is subtle and depends on the
110 // pass manager processing loops and calling releaseMemory() in a
111 // specific order. It would be good to find a more straightforward
112 // way of doing what MaxSize does.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000113 unsigned MaxSize;
Andrew Trick4104ed92012-04-10 05:14:37 +0000114
Mark Heffernan9b536a62015-06-23 18:26:50 +0000115 public:
116 LUAnalysisCache()
117 : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
118 MaxSize(Threshold) {}
Andrew Trick4104ed92012-04-10 05:14:37 +0000119
Mark Heffernan9b536a62015-06-23 18:26:50 +0000120 // Analyze loop. Check its size, calculate is it possible to unswitch
121 // it. Returns true if we can unswitch this loop.
122 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
123 AssumptionCache *AC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000124
Mark Heffernan9b536a62015-06-23 18:26:50 +0000125 // Clean all data related to given loop.
126 void forgetLoop(const Loop *L);
Andrew Trick4104ed92012-04-10 05:14:37 +0000127
Mark Heffernan9b536a62015-06-23 18:26:50 +0000128 // Mark case value as unswitched.
129 // Since SI instruction can be partly unswitched, in order to avoid
130 // extra unswitching in cloned loops keep track all unswitched values.
131 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000132
Mark Heffernan9b536a62015-06-23 18:26:50 +0000133 // Check was this case value unswitched before or not.
134 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000135
Mark Heffernan9b536a62015-06-23 18:26:50 +0000136 // Returns true if another unswitching could be done within the cost
137 // threshold.
138 bool CostAllowsUnswitching();
Andrew Trick4104ed92012-04-10 05:14:37 +0000139
Mark Heffernan9b536a62015-06-23 18:26:50 +0000140 // Clone all loop-unswitch related loop properties.
141 // Redistribute unswitching quotas.
142 // Note, that new loop data is stored inside the VMap.
143 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
144 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000145 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000146
Chris Lattner2dd09db2009-09-02 06:11:42 +0000147 class LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000148 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +0000149 LPPassManager *LPM;
Chandler Carruth66b31302015-01-04 12:03:27 +0000150 AssumptionCache *AC;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000151
Sanjay Patel956e29c2015-08-11 21:24:04 +0000152 // Used to check if second loop needs processing after
153 // RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000154 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000155
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000156 LUAnalysisCache BranchesInfo;
Andrew Trick4104ed92012-04-10 05:14:37 +0000157
Devang Patel506310d2007-06-06 00:21:03 +0000158 bool OptimizeForSize;
Devang Patel7d165e12007-07-30 23:07:10 +0000159 bool redoLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000160
Devang Patele149d4e2008-07-02 01:18:13 +0000161 Loop *currentLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000162 DominatorTree *DT;
Devang Patele149d4e2008-07-02 01:18:13 +0000163 BasicBlock *loopHeader;
164 BasicBlock *loopPreheader;
Andrew Trick4104ed92012-04-10 05:14:37 +0000165
Devang Pateled50fb52008-07-02 01:44:29 +0000166 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick4104ed92012-04-10 05:14:37 +0000167 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Pateled50fb52008-07-02 01:44:29 +0000168 // loop, in that order.
169 std::vector<BasicBlock*> LoopBlocks;
170 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
171 std::vector<BasicBlock*> NewBlocks;
Devang Pateleb611dd2008-07-03 17:37:52 +0000172
Chris Lattnerf48f7772004-04-19 18:07:02 +0000173 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000174 static char ID; // Pass ID, replacement for typeid
Andrew Trick4104ed92012-04-10 05:14:37 +0000175 explicit LoopUnswitch(bool Os = false) :
176 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Craig Topperf40110f2014-04-25 05:29:35 +0000177 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
178 loopPreheader(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000179 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
180 }
Devang Patel09f162c2007-05-01 21:15:47 +0000181
Craig Topper3e4c6972014-03-05 09:10:37 +0000182 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Devang Patele149d4e2008-07-02 01:18:13 +0000183 bool processCurrentLoop();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000184
185 /// This transformation requires natural loop information & requires that
Chris Lattnerbc1a65a2010-08-29 17:23:19 +0000186 /// loop preheaders be inserted into the CFG.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000187 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000188 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000189 AU.addRequired<AssumptionCacheTracker>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000190 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000191 AU.addPreservedID(LoopSimplifyID);
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000192 AU.addRequired<LoopInfoWrapperPass>();
193 AU.addPreserved<LoopInfoWrapperPass>();
Owen Andersonfd0a3d62006-06-12 21:49:21 +0000194 AU.addRequiredID(LCSSAID);
Devang Pateld4911982007-07-31 08:03:26 +0000195 AU.addPreservedID(LCSSAID);
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000196 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000197 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000198 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000199 AU.addRequired<TargetTransformInfoWrapperPass>();
James Molloyefbba722015-09-10 10:22:12 +0000200 AU.addPreserved<GlobalsAAWrapperPass>();
Chris Lattnerf48f7772004-04-19 18:07:02 +0000201 }
202
203 private:
Devang Pateld4911982007-07-31 08:03:26 +0000204
Craig Topper3e4c6972014-03-05 09:10:37 +0000205 void releaseMemory() override {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000206 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000207 }
208
Devang Patele149d4e2008-07-02 01:18:13 +0000209 void initLoopData() {
210 loopHeader = currentLoop->getHeader();
211 loopPreheader = currentLoop->getLoopPreheader();
212 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000213
Chris Lattner559c8672008-04-21 00:25:49 +0000214 /// Split all of the edges from inside the loop to their exit blocks.
215 /// Update the appropriate Phi nodes as we do so.
Sanjay Patel41f3d952015-08-11 21:11:56 +0000216 void SplitExitEdges(Loop *L,
217 const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000218
Chen Lic0f3a152015-07-22 05:26:29 +0000219 bool TryTrivialLoopUnswitch(bool &Changed);
220
Weiming Zhaof1abad52015-06-23 05:31:09 +0000221 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
222 TerminatorInst *TI = nullptr);
Chris Lattner29f771b2006-02-18 01:27:45 +0000223 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000224 BasicBlock *ExitBlock, TerminatorInst *TI);
225 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
226 TerminatorInst *TI);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000227
228 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
229 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000230
231 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000232 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000233 BasicBlock *FalseDest,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000234 Instruction *InsertPt,
235 TerminatorInst *TI);
Devang Patel3304e462007-06-28 00:49:00 +0000236
Devang Pateld4911982007-07-31 08:03:26 +0000237 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000238 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000239}
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000240
241// Analyze loop. Check its size, calculate is it possible to unswitch
242// it. Returns true if we can unswitch this loop.
Hal Finkel57f03dd2014-09-07 13:49:57 +0000243bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000244 AssumptionCache *AC) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000245
Jakub Staszak27da1232013-08-06 17:03:42 +0000246 LoopPropsMapIt PropsIt;
247 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000248 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000249 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000250
Jakub Staszak27da1232013-08-06 17:03:42 +0000251 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000252
Jakub Staszak27da1232013-08-06 17:03:42 +0000253 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000254 // New loop.
255
256 // Limit the number of instructions to avoid causing significant code
257 // expansion, and the number of basic blocks, to avoid loops with
258 // large numbers of branches which cause loop unswitching to go crazy.
259 // This is a very ad-hoc heuristic.
Andrew Trick4104ed92012-04-10 05:14:37 +0000260
Hal Finkel57f03dd2014-09-07 13:49:57 +0000261 SmallPtrSet<const Value *, 32> EphValues;
Chandler Carruth66b31302015-01-04 12:03:27 +0000262 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000263
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000264 // FIXME: This is overly conservative because it does not take into
265 // consideration code simplification opportunities and code that can
266 // be shared by the resultant unswitched loops.
267 CodeMetrics Metrics;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000268 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
269 ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000270 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000271
Mark Heffernan9b536a62015-06-23 18:26:50 +0000272 Props.SizeEstimation = Metrics.NumInsts;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000273 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
Mark Heffernan9b536a62015-06-23 18:26:50 +0000274 Props.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000275 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000276
277 if (Metrics.notDuplicatable) {
278 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000279 << L->getHeader()->getName() << ", contents cannot be "
280 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000281 return false;
282 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000283 }
284
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000285 // Be careful. This links are good only before new loop addition.
286 CurrentLoopProperties = &Props;
287 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000288
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000289 return true;
290}
291
292// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000293void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000294
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000295 LoopPropsMapIt LIt = LoopsProperties.find(L);
296
297 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000298 LoopProperties &Props = LIt->second;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000299 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
300 Props.SizeEstimation;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000301 LoopsProperties.erase(LIt);
302 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000303
Craig Topperf40110f2014-04-25 05:29:35 +0000304 CurrentLoopProperties = nullptr;
305 CurLoopInstructions = nullptr;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000306}
307
308// Mark case value as unswitched.
309// Since SI instruction can be partly unswitched, in order to avoid
310// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000311void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000312 (*CurLoopInstructions)[SI].insert(V);
313}
314
315// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000316bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000317 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000318}
319
Mark Heffernan9b536a62015-06-23 18:26:50 +0000320bool LUAnalysisCache::CostAllowsUnswitching() {
321 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
322}
323
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000324// Clone all loop-unswitch related loop properties.
325// Redistribute unswitching quotas.
326// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000327void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
328 const ValueToValueMapTy &VMap) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000329
Jakub Staszak27da1232013-08-06 17:03:42 +0000330 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
331 LoopProperties &OldLoopProps = *CurrentLoopProperties;
332 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000333
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000334 // Reallocate "can-be-unswitched quota"
335
336 --OldLoopProps.CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000337 ++OldLoopProps.WasUnswitchedCount;
338 NewLoopProps.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000339 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
340 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
341 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000342
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000343 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000344
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000345 // Clone unswitched values info:
346 // for new loop switches we clone info about values that was
347 // already unswitched and has redundant successors.
348 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000349 const SwitchInst *OldInst = I->first;
350 Value *NewI = VMap.lookup(OldInst);
351 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000352 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000353
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000354 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
355 }
356}
357
Dan Gohmand78c4002008-05-13 00:00:25 +0000358char LoopUnswitch::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000359INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
360 false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000361INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth66b31302015-01-04 12:03:27 +0000362INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000363INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000364INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000365INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000366INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
367 false, false)
Chris Lattnerf48f7772004-04-19 18:07:02 +0000368
Andrew Trick4104ed92012-04-10 05:14:37 +0000369Pass *llvm::createLoopUnswitchPass(bool Os) {
370 return new LoopUnswitch(Os);
Devang Patel506310d2007-06-06 00:21:03 +0000371}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000372
Sanjay Patel956e29c2015-08-11 21:24:04 +0000373/// Cond is a condition that occurs in L. If it is invariant in the loop, or has
374/// an invariant piece, return the invariant. Otherwise, return null.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000375static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000376
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000377 // We started analyze new instruction, increment scanned instructions counter.
378 ++TotalInsts;
Andrew Trick4104ed92012-04-10 05:14:37 +0000379
Chris Lattner302240d2010-02-02 02:26:54 +0000380 // We can never unswitch on vector conditions.
Duncan Sands19d0b472010-02-16 11:11:14 +0000381 if (Cond->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000382 return nullptr;
Chris Lattner302240d2010-02-02 02:26:54 +0000383
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000384 // Constants should be folded, not unswitched on!
Craig Topperf40110f2014-04-25 05:29:35 +0000385 if (isa<Constant>(Cond)) return nullptr;
Devang Patel3c723c82007-06-28 00:44:10 +0000386
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000387 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patelfe57d102008-11-03 19:38:07 +0000388
Dan Gohman4d6149f2009-07-14 01:37:59 +0000389 // Hoist simple values out.
Dan Gohmanc43e4792009-07-15 01:25:43 +0000390 if (L->makeLoopInvariant(Cond, Changed))
Dan Gohman4d6149f2009-07-14 01:37:59 +0000391 return Cond;
Dan Gohman4d6149f2009-07-14 01:37:59 +0000392
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000393 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
394 if (BO->getOpcode() == Instruction::And ||
395 BO->getOpcode() == Instruction::Or) {
396 // If either the left or right side is invariant, we can unswitch on this,
397 // which will cause the branch to go away in one loop and the condition to
398 // simplify in the other one.
399 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
400 return LHS;
401 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
402 return RHS;
403 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000404
Craig Topperf40110f2014-04-25 05:29:35 +0000405 return nullptr;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000406}
407
Devang Patel901a27d2007-03-07 00:26:10 +0000408bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000409 if (skipOptnoneFunction(L))
410 return false;
411
Chandler Carruth66b31302015-01-04 12:03:27 +0000412 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
413 *L->getHeader()->getParent());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000414 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Devang Patel901a27d2007-03-07 00:26:10 +0000415 LPM = &LPM_Ref;
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000416 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Devang Patele149d4e2008-07-02 01:18:13 +0000417 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000418 Function *F = currentLoop->getHeader()->getParent();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000419 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000420 do {
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000421 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel7d165e12007-07-30 23:07:10 +0000422 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000423 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000424 } while(redoLoop);
425
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000426 // FIXME: Reconstruct dom info, because it is not preserved properly.
427 if (Changed)
428 DT->recalculate(*F);
Devang Patel7d165e12007-07-30 23:07:10 +0000429 return Changed;
430}
431
Sanjay Patel956e29c2015-08-11 21:24:04 +0000432/// Do actual work and unswitch loop if possible and profitable.
Devang Patele149d4e2008-07-02 01:18:13 +0000433bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000434 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000435
436 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000437
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000438 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
439 if (!loopPreheader)
440 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000441
Andrew Trick4442bfe2012-04-10 05:14:42 +0000442 // Loops with indirectbr cannot be cloned.
443 if (!currentLoop->isSafeToClone())
444 return false;
445
446 // Without dedicated exits, splitting the exit edge may fail.
447 if (!currentLoop->hasDedicatedExits())
448 return false;
449
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000450 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000451
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000452 // Probably we reach the quota of branches for this loop. If so
453 // stop unswitching.
Chandler Carruth705b1852015-01-31 03:43:40 +0000454 if (!BranchesInfo.countLoop(
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000455 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
456 *currentLoop->getHeader()->getParent()),
Chandler Carruth705b1852015-01-31 03:43:40 +0000457 AC))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000458 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000459
Chen Lic0f3a152015-07-22 05:26:29 +0000460 // Try trivial unswitch first before loop over other basic blocks in the loop.
461 if (TryTrivialLoopUnswitch(Changed)) {
462 return true;
463 }
464
Chen Lif458c6f2015-08-13 05:24:29 +0000465 // Do not do non-trivial unswitch while optimizing for size.
466 // FIXME: Use Function::optForSize().
467 if (OptimizeForSize ||
468 loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
469 return false;
470
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000471 // Loop over all of the basic blocks in the loop. If we find an interior
472 // block that is branching on a loop-invariant condition, we can unswitch this
473 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000474 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000475 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000476 TerminatorInst *TI = (*I)->getTerminator();
477 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
478 // If this isn't branching on an invariant condition, we can't unswitch
479 // it.
480 if (BI->isConditional()) {
481 // See if this, or some part of it, is loop invariant. If so, we can
482 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000483 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000484 currentLoop, Changed);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000485 if (LoopCond &&
486 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000487 ++NumBranches;
488 return true;
489 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000490 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000491 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000492 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000493 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000494 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000495 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000496 // Find a value to unswitch on:
497 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000498 // FIXME: scan for a case with a non-critical edge?
Craig Topperf40110f2014-04-25 05:29:35 +0000499 Constant *UnswitchVal = nullptr;
Andrew Trick4104ed92012-04-10 05:14:37 +0000500
Devang Patel967b84c2007-02-26 19:31:58 +0000501 // Do not process same value again and again.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000502 // At this point we have some cases already unswitched and
503 // some not yet unswitched. Let's find the first not yet unswitched one.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000504 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000505 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000506 Constant *UnswitchValCandidate = i.getCaseValue();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000507 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
Chad Rosier3ba90a12011-12-22 21:10:46 +0000508 UnswitchVal = UnswitchValCandidate;
509 break;
510 }
511 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000512
Chad Rosier3ba90a12011-12-22 21:10:46 +0000513 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000514 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000515
Devang Patele149d4e2008-07-02 01:18:13 +0000516 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000517 ++NumSwitches;
518 return true;
519 }
520 }
521 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000522
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000523 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000524 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000525 BBI != E; ++BBI)
526 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000527 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000528 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000529 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000530 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000531 ++NumSelects;
532 return true;
533 }
534 }
535 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000536 return Changed;
537}
538
Sanjay Patel956e29c2015-08-11 21:24:04 +0000539/// Check to see if all paths from BB exit the loop with no side effects
540/// (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000541///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000542/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000543/// exit through.
544///
545static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
546 BasicBlock *&ExitBB,
547 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000548 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000549 // Already visited. Without more analysis, this could indicate an infinite
550 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000551 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000552 }
553 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000554 // Otherwise, this is a loop exit, this is fine so long as this is the
555 // first exit.
Craig Topperf40110f2014-04-25 05:29:35 +0000556 if (ExitBB) return false;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000557 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000558 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000559 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000560
Chris Lattnerbaddba42006-02-17 06:39:56 +0000561 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000562 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000563 // Check to see if the successor is a trivial loop exit.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000564 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
Chris Lattnerbaddba42006-02-17 06:39:56 +0000565 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000566 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000567
568 // Okay, everything after this looks good, check to make sure that this block
569 // doesn't include any side effects.
Chris Lattnerfdff0bb2006-02-15 22:52:05 +0000570 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sands1efabaa2009-05-06 06:49:50 +0000571 if (I->mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000572 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000573
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000574 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000575}
576
Sanjay Patel956e29c2015-08-11 21:24:04 +0000577/// Return true if the specified block unconditionally leads to an exit from
578/// the specified loop, and has no side-effects in the process. If so, return
579/// the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000580static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
581 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000582 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Craig Topperf40110f2014-04-25 05:29:35 +0000583 BasicBlock *ExitBB = nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000584 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
585 return ExitBB;
Craig Topperf40110f2014-04-25 05:29:35 +0000586 return nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000587}
Chris Lattner6e263152006-02-10 02:30:37 +0000588
Sanjay Patel956e29c2015-08-11 21:24:04 +0000589/// We have found that we can unswitch currentLoop when LoopCond == Val to
590/// simplify the loop. If we decide that this is profitable,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000591/// unswitch the loop, reprocess the pieces, then return true.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000592bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
593 TerminatorInst *TI) {
Evan Chenged66db32010-04-03 02:23:43 +0000594 // Check to see if it would be profitable to unswitch current loop.
Mark Heffernan9b536a62015-06-23 18:26:50 +0000595 if (!BranchesInfo.CostAllowsUnswitching()) {
596 DEBUG(dbgs() << "NOT unswitching loop %"
597 << currentLoop->getHeader()->getName()
598 << " at non-trivial condition '" << *Val
599 << "' == " << *LoopCond << "\n"
600 << ". Cost too high.\n");
601 return false;
602 }
Evan Chenged66db32010-04-03 02:23:43 +0000603
Weiming Zhaof1abad52015-06-23 05:31:09 +0000604 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000605 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000606}
607
Sanjay Patel956e29c2015-08-11 21:24:04 +0000608/// Recursively clone the specified loop and all of its children,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000609/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000610static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000611 LoopInfo *LI, LPPassManager *LPM) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000612 Loop *New = new Loop();
Devang Patel901a27d2007-03-07 00:26:10 +0000613 LPM->insertLoop(New, PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000614
615 // Add all of the blocks in L to the new loop.
616 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
617 I != E; ++I)
618 if (LI->getLoopFor(*I) == L)
Chandler Carruth691addc2015-01-18 01:25:51 +0000619 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000620
621 // Add all of the subloops to the new loop.
622 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Devang Patel901a27d2007-03-07 00:26:10 +0000623 CloneLoop(*I, New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000624
Chris Lattnerf48f7772004-04-19 18:07:02 +0000625 return New;
626}
627
Weiming Zhaof1abad52015-06-23 05:31:09 +0000628static void copyMetadata(Instruction *DstInst, const Instruction *SrcInst,
629 bool Swapped) {
630 if (!SrcInst || !SrcInst->hasMetadata())
631 return;
632
633 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
634 SrcInst->getAllMetadata(MDs);
635 for (auto &MD : MDs) {
636 switch (MD.first) {
637 default:
638 break;
639 case LLVMContext::MD_prof:
640 if (Swapped && MD.second->getNumOperands() == 3 &&
641 isa<MDString>(MD.second->getOperand(0))) {
642 MDString *MDName = cast<MDString>(MD.second->getOperand(0));
643 if (MDName->getString() == "branch_weights") {
644 auto *ValT = cast_or_null<ConstantAsMetadata>(
645 MD.second->getOperand(1))->getValue();
646 auto *ValF = cast_or_null<ConstantAsMetadata>(
647 MD.second->getOperand(2))->getValue();
648 assert(ValT && ValF && "Invalid Operands of branch_weights");
649 auto NewMD =
650 MDBuilder(DstInst->getParent()->getContext())
651 .createBranchWeights(cast<ConstantInt>(ValF)->getZExtValue(),
652 cast<ConstantInt>(ValT)->getZExtValue());
653 MD.second = NewMD;
654 }
655 }
656 // fallthrough.
Chen Li50efd922015-08-05 21:13:26 +0000657 case LLVMContext::MD_make_implicit:
Weiming Zhaof1abad52015-06-23 05:31:09 +0000658 case LLVMContext::MD_dbg:
659 DstInst->setMetadata(MD.first, MD.second);
660 }
661 }
662}
663
Sanjay Patel956e29c2015-08-11 21:24:04 +0000664/// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
665/// otherwise branch to FalseDest. Insert the code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000666void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
667 BasicBlock *TrueDest,
668 BasicBlock *FalseDest,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000669 Instruction *InsertPt,
670 TerminatorInst *TI) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000671 // Insert a conditional branch on LIC to the two preheaders. The original
672 // code is the true version and the new code is the false version.
673 Value *BranchVal = LIC;
Weiming Zhaof1abad52015-06-23 05:31:09 +0000674 bool Swapped = false;
Owen Anderson55f1c092009-08-13 21:58:54 +0000675 if (!isa<ConstantInt>(Val) ||
676 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000677 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000678 else if (Val != ConstantInt::getTrue(Val->getContext())) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000679 // We want to enter the new loop when the condition is true.
680 std::swap(TrueDest, FalseDest);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000681 Swapped = true;
682 }
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000683
684 // Insert the new branch.
Dan Gohman3ddbc242009-09-08 15:45:00 +0000685 BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000686 copyMetadata(BI, TI, Swapped);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000687
688 // If either edge is critical, split it. This helps preserve LoopSimplify
689 // form for enclosing loops.
Chandler Carruthf8753fc2015-01-19 12:12:00 +0000690 auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000691 SplitCriticalEdge(BI, 0, Options);
692 SplitCriticalEdge(BI, 1, Options);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000693}
694
Sanjay Patel956e29c2015-08-11 21:24:04 +0000695/// Given a loop that has a trivial unswitchable condition in it (a cond branch
696/// from its header block to its latch block, where the path through the loop
697/// that doesn't execute its body has no side-effects), unswitch it. This
698/// doesn't involve any code duplication, just moving the conditional branch
699/// outside of the loop and updating loop info.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000700void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
701 BasicBlock *ExitBlock,
702 TerminatorInst *TI) {
David Greened9c355d2010-01-05 01:27:04 +0000703 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Weiming Zhaof1abad52015-06-23 05:31:09 +0000704 << loopHeader->getName() << " [" << L->getBlocks().size()
705 << " blocks] in Function "
706 << L->getHeader()->getParent()->getName() << " on cond: " << *Val
707 << " == " << *Cond << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +0000708
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000709 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +0000710 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +0000711 // conditional branch on Cond.
Chandler Carruthd4500562015-01-19 12:36:53 +0000712 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000713
714 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000715 // to branch to: this is the exit block out of the loop that we should
716 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +0000717
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000718 // Split this block now, so that the loop maintains its exit block, and so
719 // that the jump from the preheader can execute the contents of the exit block
720 // without actually branching to it (the exit block should be dominated by the
721 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000722 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000723 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), DT, LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000724
725 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000726 // insert the new conditional branch.
Andrew Trick4104ed92012-04-10 05:14:37 +0000727 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000728 loopPreheader->getTerminator(), TI);
Devang Patele149d4e2008-07-02 01:18:13 +0000729 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
730 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattnered7a67b2006-02-10 01:24:09 +0000731
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000732 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +0000733 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +0000734
Chris Lattnered7a67b2006-02-10 01:24:09 +0000735 // Now that we know that the loop is never entered when this condition is a
736 // particular value, rewrite the loop with this info. We know that this will
737 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000738 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000739 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000740}
741
Sanjay Patel41f3d952015-08-11 21:11:56 +0000742/// Check if the first non-constant condition starting from the loop header is
743/// a trivial unswitch condition: that is, a condition controls whether or not
744/// the loop does anything at all. If it is a trivial condition, unswitching
745/// produces no code duplications (equivalently, it produces a simpler loop and
746/// a new empty loop, which gets deleted). Therefore always unswitch trivial
747/// condition.
Chen Lic0f3a152015-07-22 05:26:29 +0000748bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
Chen Li145c2f52015-07-25 03:21:06 +0000749 BasicBlock *CurrentBB = currentLoop->getHeader();
750 TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
751 LLVMContext &Context = CurrentBB->getContext();
Chen Lic0f3a152015-07-22 05:26:29 +0000752
Chen Li145c2f52015-07-25 03:21:06 +0000753 // If loop header has only one reachable successor (currently via an
754 // unconditional branch or constant foldable conditional branch, but
755 // should also consider adding constant foldable switch instruction in
756 // future), we should keep looking for trivial condition candidates in
757 // the successor as well. An alternative is to constant fold conditions
758 // and merge successors into loop header (then we only need to check header's
759 // terminator). The reason for not doing this in LoopUnswitch pass is that
760 // it could potentially break LoopPassManager's invariants. Folding dead
761 // branches could either eliminate the current loop or make other loops
Sanjay Patel41f3d952015-08-11 21:11:56 +0000762 // unreachable. LCSSA form might also not be preserved after deleting
763 // branches. The following code keeps traversing loop header's successors
764 // until it finds the trivial condition candidate (condition that is not a
765 // constant). Since unswitching generates branches with constant conditions,
766 // this scenario could be very common in practice.
Chen Li145c2f52015-07-25 03:21:06 +0000767 SmallSet<BasicBlock*, 8> Visited;
768
769 while (true) {
770 // If we exit loop or reach a previous visited block, then
771 // we can not reach any trivial condition candidates (unfoldable
772 // branch instructions or switch instructions) and no unswitch
773 // can happen. Exit and return false.
774 if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
Chen Lic0f3a152015-07-22 05:26:29 +0000775 return false;
776
Chen Li145c2f52015-07-25 03:21:06 +0000777 // Check if this loop will execute any side-effecting instructions (e.g.
778 // stores, calls, volatile loads) in the part of the loop that the code
779 // *would* execute. Check the header first.
780 for (BasicBlock::iterator I : *CurrentBB)
781 if (I->mayHaveSideEffects())
782 return false;
783
784 // FIXME: add check for constant foldable switch instructions.
785 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
786 if (BI->isUnconditional()) {
787 CurrentBB = BI->getSuccessor(0);
788 } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
789 CurrentBB = BI->getSuccessor(0);
790 } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
791 CurrentBB = BI->getSuccessor(1);
792 } else {
Sanjay Patel41f3d952015-08-11 21:11:56 +0000793 // Found a trivial condition candidate: non-foldable conditional branch.
Chen Li145c2f52015-07-25 03:21:06 +0000794 break;
795 }
796 } else {
797 break;
798 }
799
800 CurrentTerm = CurrentBB->getTerminator();
801 }
802
Chen Lic0f3a152015-07-22 05:26:29 +0000803 // CondVal is the condition that controls the trivial condition.
804 // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
805 Constant *CondVal = nullptr;
806 BasicBlock *LoopExitBB = nullptr;
807
Chen Li145c2f52015-07-25 03:21:06 +0000808 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +0000809 // If this isn't branching on an invariant condition, we can't unswitch it.
810 if (!BI->isConditional())
811 return false;
812
813 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
814 currentLoop, Changed);
815
816 // Unswitch only if the trivial condition itself is an LIV (not
817 // partial LIV which could occur in and/or)
818 if (!LoopCond || LoopCond != BI->getCondition())
819 return false;
820
821 // Check to see if a successor of the branch is guaranteed to
822 // exit through a unique exit block without having any
823 // side-effects. If so, determine the value of Cond that causes
824 // it to do this.
825 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
826 BI->getSuccessor(0)))) {
827 CondVal = ConstantInt::getTrue(Context);
828 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
829 BI->getSuccessor(1)))) {
830 CondVal = ConstantInt::getFalse(Context);
831 }
832
Sanjay Patel41f3d952015-08-11 21:11:56 +0000833 // If we didn't find a single unique LoopExit block, or if the loop exit
834 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +0000835 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
836 return false; // Can't handle this.
837
Sanjay Patel41f3d952015-08-11 21:11:56 +0000838 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
839 CurrentTerm);
Chen Lic0f3a152015-07-22 05:26:29 +0000840 ++NumBranches;
841 return true;
Chen Li145c2f52015-07-25 03:21:06 +0000842 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +0000843 // If this isn't switching on an invariant condition, we can't unswitch it.
844 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
845 currentLoop, Changed);
846
847 // Unswitch only if the trivial condition itself is an LIV (not
848 // partial LIV which could occur in and/or)
849 if (!LoopCond || LoopCond != SI->getCondition())
850 return false;
851
852 // Check to see if a successor of the switch is guaranteed to go to the
853 // latch block or exit through a one exit block without having any
854 // side-effects. If so, determine the value of Cond that causes it to do
855 // this.
856 // Note that we can't trivially unswitch on the default case or
857 // on already unswitched cases.
858 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
859 i != e; ++i) {
860 BasicBlock *LoopExitCandidate;
861 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
862 i.getCaseSuccessor()))) {
863 // Okay, we found a trivial case, remember the value that is trivial.
864 ConstantInt *CaseVal = i.getCaseValue();
865
866 // Check that it was not unswitched before, since already unswitched
867 // trivial vals are looks trivial too.
868 if (BranchesInfo.isUnswitched(SI, CaseVal))
869 continue;
870 LoopExitBB = LoopExitCandidate;
871 CondVal = CaseVal;
872 break;
873 }
874 }
875
Sanjay Patel41f3d952015-08-11 21:11:56 +0000876 // If we didn't find a single unique LoopExit block, or if the loop exit
877 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +0000878 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
879 return false; // Can't handle this.
880
Sanjay Patel41f3d952015-08-11 21:11:56 +0000881 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
882 nullptr);
Chen Lic0f3a152015-07-22 05:26:29 +0000883 ++NumSwitches;
884 return true;
885 }
886 return false;
887}
888
Sanjay Patel956e29c2015-08-11 21:24:04 +0000889/// Split all of the edges from inside the loop to their exit blocks.
890/// Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +0000891void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000892 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +0000893
Chris Lattnered7a67b2006-02-10 01:24:09 +0000894 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000895 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +0000896 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
897 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +0000898
Nick Lewycky61158242011-06-03 06:27:15 +0000899 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
900 // general, if we call it on all predecessors of all exits then it does.
Chandler Carruth96ada252015-07-22 09:52:54 +0000901 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI,
Philip Reames9198b332015-01-28 23:06:47 +0000902 /*PreserveLCSSA*/ true);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000903 }
Devang Patele192e3252007-10-03 21:16:08 +0000904}
905
Sanjay Patel956e29c2015-08-11 21:24:04 +0000906/// We determined that the loop is profitable to unswitch when LIC equal Val.
907/// Split it into loop versions and test the condition outside of either loop.
908/// Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000909void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000910 Loop *L, TerminatorInst *TI) {
Devang Patele149d4e2008-07-02 01:18:13 +0000911 Function *F = loopHeader->getParent();
David Greened9c355d2010-01-05 01:27:04 +0000912 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000913 << loopHeader->getName() << " [" << L->getBlocks().size()
914 << " blocks] in Function " << F->getName()
915 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +0000916
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000917 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
918 SEWP->getSE().forgetLoop(L);
Cameron Zwarich99de19b2011-02-11 06:08:28 +0000919
Devang Pateled50fb52008-07-02 01:44:29 +0000920 LoopBlocks.clear();
921 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +0000922
923 // First step, split the preheader and exit blocks, and add these blocks to
924 // the LoopBlocks list.
Chandler Carruthd4500562015-01-19 12:36:53 +0000925 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
Devang Patele192e3252007-10-03 21:16:08 +0000926 LoopBlocks.push_back(NewPreheader);
927
928 // We want the loop to come after the preheader, but before the exit blocks.
929 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
930
931 SmallVector<BasicBlock*, 8> ExitBlocks;
932 L->getUniqueExitBlocks(ExitBlocks);
933
934 // Split all of the edges from inside the loop to their exit blocks. Update
935 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +0000936 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +0000937
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000938 // The exit blocks may have been changed due to edge splitting, recompute.
939 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +0000940 L->getUniqueExitBlocks(ExitBlocks);
941
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000942 // Add exit blocks to the loop blocks.
943 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +0000944
945 // Next step, clone all of the basic blocks that make up the loop (including
946 // the loop preheader and exit blocks), keeping track of the mapping between
947 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000948 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +0000949 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000950 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000951 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +0000952
Evan Chengba930442010-04-05 21:16:25 +0000953 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000954 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +0000955 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000956 }
957
958 // Splice the newly inserted blocks into the function right before the
959 // original preheader.
Evan Chengba930442010-04-05 21:16:25 +0000960 F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
Chris Lattnerf48f7772004-04-19 18:07:02 +0000961 NewBlocks[0], F->end());
962
Hal Finkel74c2f352014-09-07 12:44:26 +0000963 // FIXME: We could register any cloned assumptions instead of clearing the
964 // whole function's cache.
Chandler Carruth66b31302015-01-04 12:03:27 +0000965 AC->clear();
Hal Finkel74c2f352014-09-07 12:44:26 +0000966
Chris Lattnerf48f7772004-04-19 18:07:02 +0000967 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000968 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000969
970 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
971 // Probably clone more loop-unswitch related loop properties.
972 BranchesInfo.cloneData(NewLoop, L, VMap);
973
Chris Lattnerf1b15162006-02-10 23:26:14 +0000974 Loop *ParentLoop = L->getParentLoop();
975 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000976 // Make sure to add the cloned preheader and exit blocks to the parent loop
977 // as well.
Chandler Carruth691addc2015-01-18 01:25:51 +0000978 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +0000979 }
Bill Wendling90f90da2011-09-27 00:59:31 +0000980
Chris Lattnerf1b15162006-02-10 23:26:14 +0000981 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000982 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +0000983 // The new exit block should be in the same loop as the old one.
984 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Chandler Carruth691addc2015-01-18 01:25:51 +0000985 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000986
Chris Lattnerf1b15162006-02-10 23:26:14 +0000987 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
988 "Exit block should have been split to have one successor!");
989 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +0000990
Chris Lattnerf1b15162006-02-10 23:26:14 +0000991 // If the successor of the exit block had PHI nodes, add an entry for
992 // NewExit.
Jakub Staszak27da1232013-08-06 17:03:42 +0000993 for (BasicBlock::iterator I = ExitSucc->begin();
994 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerf1b15162006-02-10 23:26:14 +0000995 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +0000996 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000997 if (It != VMap.end()) V = It->second;
Chris Lattnerf1b15162006-02-10 23:26:14 +0000998 PN->addIncoming(V, NewExit);
999 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001000
1001 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +00001002 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
1003 ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +00001004
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001005 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1006 I != E; ++I) {
1007 BasicBlock *BB = *I;
Bill Wendling90f90da2011-09-27 00:59:31 +00001008 LandingPadInst *LPI = BB->getLandingPadInst();
1009 LPI->replaceAllUsesWith(PN);
1010 PN->addIncoming(LPI, BB);
1011 }
1012 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001013 }
1014
1015 // Rewrite the code to refer to itself.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00001016 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
1017 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
1018 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner43f8d162011-01-08 08:15:20 +00001019 RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trick4104ed92012-04-10 05:14:37 +00001020
Chris Lattnerf48f7772004-04-19 18:07:02 +00001021 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +00001022 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001023 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +00001024 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +00001025
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001026 // Emit the new branch that selects between the two versions of this loop.
Weiming Zhaof1abad52015-06-23 05:31:09 +00001027 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1028 TI);
Devang Pateld4911982007-07-31 08:03:26 +00001029 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001030 OldBR->eraseFromParent();
Devang Patela8823282007-08-02 15:25:57 +00001031
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001032 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +00001033 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001034
Chris Lattner5814d9d92010-04-20 05:09:16 +00001035 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
1036 // deletes the instruction (for example by simplifying a PHI that feeds into
1037 // the condition that we're unswitching on), we don't rewrite the second
1038 // iteration.
1039 WeakVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +00001040
Chris Lattnerf48f7772004-04-19 18:07:02 +00001041 // Now we rewrite the original code to know that the condition is true and the
1042 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +00001043 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +00001044
Chris Lattner5814d9d92010-04-20 05:09:16 +00001045 // It's possible that simplifying one loop could cause the other to be
1046 // changed to another value or a constant. If its a constant, don't simplify
1047 // it.
1048 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1049 LICHandle && !isa<Constant>(LICHandle))
1050 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001051}
1052
Sanjay Patel956e29c2015-08-11 21:24:04 +00001053/// Remove all instances of I from the worklist vector specified.
Andrew Trick4104ed92012-04-10 05:14:37 +00001054static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +00001055 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +00001056
1057 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1058 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +00001059}
1060
Sanjay Patel956e29c2015-08-11 21:24:04 +00001061/// When we find that I really equals V, remove I from the
Chris Lattner6fd13622006-02-17 00:31:07 +00001062/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +00001063static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +00001064 std::vector<Instruction*> &Worklist,
1065 Loop *L, LPPassManager *LPM) {
David Greened9c355d2010-01-05 01:27:04 +00001066 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner6fd13622006-02-17 00:31:07 +00001067
1068 // Add uses to the worklist, which may be dead now.
1069 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1070 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1071 Worklist.push_back(Use);
1072
1073 // Add users to the worklist which may be simplified now.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001074 for (User *U : I->users())
1075 Worklist.push_back(cast<Instruction>(U));
Devang Pateld4911982007-07-31 08:03:26 +00001076 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001077 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001078 I->replaceAllUsesWith(V);
1079 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001080 ++NumSimplify;
1081}
1082
Sanjay Patel956e29c2015-08-11 21:24:04 +00001083/// We know either that the value LIC has the value specified by Val in the
1084/// specified loop, or we know it does NOT have that value.
1085/// Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001086void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001087 Constant *Val,
1088 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +00001089 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +00001090
Chris Lattnerf48f7772004-04-19 18:07:02 +00001091 // FIXME: Support correlated properties, like:
1092 // for (...)
1093 // if (li1 < li2)
1094 // ...
1095 // if (li1 > li2)
1096 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +00001097
Chris Lattner6e263152006-02-10 02:30:37 +00001098 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1099 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +00001100 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +00001101 LLVMContext &Context = Val->getContext();
1102
Chris Lattner6fd13622006-02-17 00:31:07 +00001103 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1104 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +00001105 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001106 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +00001107 Value *Replacement;
1108 if (IsEqual)
1109 Replacement = Val;
1110 else
Andrew Trick4104ed92012-04-10 05:14:37 +00001111 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +00001112 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +00001113
Chandler Carruthcdf47882014-03-09 03:16:01 +00001114 for (User *U : LIC->users()) {
1115 Instruction *UI = dyn_cast<Instruction>(U);
1116 if (!UI || !L->contains(UI))
Evan Cheng1b55f562011-05-24 23:12:57 +00001117 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001118 Worklist.push_back(UI);
Evan Cheng1b55f562011-05-24 23:12:57 +00001119 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001120
Jakub Staszak27da1232013-08-06 17:03:42 +00001121 for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
1122 UE = Worklist.end(); UI != UE; ++UI)
Andrew Trick4104ed92012-04-10 05:14:37 +00001123 (*UI)->replaceUsesOfWith(LIC, Replacement);
1124
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001125 SimplifyCode(Worklist, L);
1126 return;
1127 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001128
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001129 // Otherwise, we don't know the precise value of LIC, but we do know that it
1130 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1131 // can. This case occurs when we unswitch switch statements.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001132 for (User *U : LIC->users()) {
1133 Instruction *UI = dyn_cast<Instruction>(U);
1134 if (!UI || !L->contains(UI))
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001135 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001136
Chandler Carruthcdf47882014-03-09 03:16:01 +00001137 Worklist.push_back(UI);
Chris Lattner6fd13622006-02-17 00:31:07 +00001138
Andrew Trick4104ed92012-04-10 05:14:37 +00001139 // TODO: We could do other simplifications, for example, turning
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001140 // 'icmp eq LIC, Val' -> false.
1141
1142 // If we know that LIC is not Val, use this info to simplify code.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001143 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Craig Topperf40110f2014-04-25 05:29:35 +00001144 if (!SI || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001145
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001146 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001147 // Default case is live for multiple values.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001148 if (DeadCase == SI->case_default()) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001149
1150 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001151 // successor if they become single-entry, those PHI nodes may
1152 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001153
Evan Cheng1b55f562011-05-24 23:12:57 +00001154 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001155 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001156 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001157
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001158 BranchesInfo.setUnswitched(SI, Val);
Andrew Trick4104ed92012-04-10 05:14:37 +00001159
Nick Lewycky61158242011-06-03 06:27:15 +00001160 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001161 // If the DeadCase successor dominates the loop latch, then the
1162 // transformation isn't safe since it will delete the sole predecessor edge
1163 // to the latch.
1164 if (Latch && DT->dominates(SISucc, Latch))
1165 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001166
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001167 // FIXME: This is a hack. We need to keep the successor around
1168 // and hooked up so as to preserve the loop structure, because
1169 // trying to update it is complicated. So instead we preserve the
1170 // loop structure and put the block on a dead code path.
Chandler Carruthd4500562015-01-19 12:36:53 +00001171 SplitEdge(Switch, SISucc, DT, LI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001172 // Compute the successors instead of relying on the return value
1173 // of SplitEdge, since it may have split the switch successor
1174 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001175 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001176 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1177 // Create an "unreachable" destination.
1178 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1179 Switch->getParent(),
1180 OldSISucc);
1181 new UnreachableInst(Context, Abort);
1182 // Force the new case destination to branch to the "unreachable"
1183 // block while maintaining a (dead) CFG edge to the old block.
1184 NewSISucc->getTerminator()->eraseFromParent();
1185 BranchInst::Create(Abort, OldSISucc,
1186 ConstantInt::getTrue(Context), NewSISucc);
1187 // Release the PHI operands for this edge.
1188 for (BasicBlock::iterator II = NewSISucc->begin();
1189 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1190 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1191 UndefValue::get(PN->getType()));
1192 // Tell the domtree about the new block. We don't fully update the
1193 // domtree here -- instead we force it to do a full recomputation
1194 // after the pass is complete -- but we do need to inform it of
1195 // new blocks.
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +00001196 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001197 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001198
Devang Pateld4911982007-07-31 08:03:26 +00001199 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001200}
1201
Sanjay Patel956e29c2015-08-11 21:24:04 +00001202/// Now that we have simplified some instructions in the loop, walk over it and
1203/// constant prop, dce, and fold control flow where possible. Note that this is
1204/// effectively a very simple loop-structure-aware optimizer. During processing
1205/// of this loop, L could very well be deleted, so it must not be used.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001206///
1207/// FIXME: When the loop optimizer is more mature, separate this out to a new
1208/// pass.
1209///
Devang Pateld4911982007-07-31 08:03:26 +00001210void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001211 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Chris Lattner6fd13622006-02-17 00:31:07 +00001212 while (!Worklist.empty()) {
1213 Instruction *I = Worklist.back();
1214 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001215
Chris Lattner6fd13622006-02-17 00:31:07 +00001216 // Simple DCE.
1217 if (isInstructionTriviallyDead(I)) {
David Greened9c355d2010-01-05 01:27:04 +00001218 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Andrew Trick4104ed92012-04-10 05:14:37 +00001219
Chris Lattner6fd13622006-02-17 00:31:07 +00001220 // Add uses to the worklist, which may be dead now.
1221 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1222 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1223 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001224 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001225 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001226 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001227 ++NumSimplify;
1228 continue;
1229 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001230
Chris Lattner66e809a2010-04-20 05:33:18 +00001231 // See if instruction simplification can hack this up. This is common for
1232 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001233 // 'false'. TODO: update the domtree properly so we can pass it here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001234 if (Value *V = SimplifyInstruction(I, DL))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001235 if (LI->replacementPreservesLCSSAForm(I, V)) {
1236 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1237 continue;
1238 }
1239
Chris Lattner6fd13622006-02-17 00:31:07 +00001240 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001241 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001242 if (BI->isUnconditional()) {
1243 // If BI's parent is the only pred of the successor, fold the two blocks
1244 // together.
1245 BasicBlock *Pred = BI->getParent();
1246 BasicBlock *Succ = BI->getSuccessor(0);
1247 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1248 if (!SinglePred) continue; // Nothing to do.
1249 assert(SinglePred == Pred && "CFG broken");
1250
Andrew Trick4104ed92012-04-10 05:14:37 +00001251 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001252 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001253
Chris Lattner6fd13622006-02-17 00:31:07 +00001254 // Resolve any single entry PHI nodes in Succ.
1255 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001256 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001257
Jay Foad61ea0e42011-06-23 09:09:15 +00001258 // If Succ has any successors with PHI nodes, update them to have
1259 // entries coming from Pred instead of Succ.
1260 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001261
Chris Lattner6fd13622006-02-17 00:31:07 +00001262 // Move all of the successor contents from Succ to Pred.
1263 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1264 Succ->end());
Devang Pateld4911982007-07-31 08:03:26 +00001265 LPM->deleteSimpleAnalysisValue(BI, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001266 BI->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001267 RemoveFromWorklist(BI, Worklist);
Andrew Trick4104ed92012-04-10 05:14:37 +00001268
Chris Lattner6fd13622006-02-17 00:31:07 +00001269 // Remove Succ from the loop tree.
1270 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001271 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001272 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001273 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001274 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001275 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001276
Chris Lattner66e809a2010-04-20 05:33:18 +00001277 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001278 }
1279 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001280}