blob: 76fe91884c7b8384229569c7359a44b31256d2b3 [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"
Daniel Jasperaec2fa32016-12-19 08:22:17 +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"
Chen Li9f27fc02015-09-29 05:03:32 +000041#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
42#include "llvm/Analysis/BlockFrequencyInfo.h"
43#include "llvm/Analysis/BranchProbabilityInfo.h"
44#include "llvm/Support/BranchProbability.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/Constants.h"
46#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000047#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Function.h"
49#include "llvm/IR/Instructions.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000050#include "llvm/IR/Module.h"
Weiming Zhaof1abad52015-06-23 05:31:09 +000051#include "llvm/IR/MDBuilder.h"
Chris Lattner89762192006-02-09 20:15:48 +000052#include "llvm/Support/CommandLine.h"
Reid Spencer557ab152007-02-05 23:32:05 +000053#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000055#include "llvm/Transforms/Utils/BasicBlockUtils.h"
56#include "llvm/Transforms/Utils/Cloning.h"
57#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000058#include "llvm/Transforms/Utils/LoopUtils.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000059#include <algorithm>
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000060#include <map>
Chris Lattner2826e052006-02-09 19:14:52 +000061#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000062using namespace llvm;
63
Chandler Carruth964daaa2014-04-22 02:55:47 +000064#define DEBUG_TYPE "loop-unswitch"
65
Chris Lattner79a42ac2006-12-19 21:40:18 +000066STATISTIC(NumBranches, "Number of branches unswitched");
67STATISTIC(NumSwitches, "Number of switches unswitched");
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +000068STATISTIC(NumGuards, "Number of guards unswitched");
Chris Lattner79a42ac2006-12-19 21:40:18 +000069STATISTIC(NumSelects , "Number of selects unswitched");
70STATISTIC(NumTrivial , "Number of unswitches that are trivial");
71STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000072STATISTIC(TotalInsts, "Total number of instructions analyzed");
Chris Lattner79a42ac2006-12-19 21:40:18 +000073
Stepan Dyatkovskiy2931a592012-01-16 20:48:04 +000074// The specific value of 100 here was chosen based only on intuition and a
Dan Gohman71ca6522009-10-13 17:50:43 +000075// few specific examples.
Dan Gohmand78c4002008-05-13 00:00:25 +000076static cl::opt<unsigned>
77Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +000078 cl::init(100), cl::Hidden);
Andrew Trick4104ed92012-04-10 05:14:37 +000079
Chen Li9f27fc02015-09-29 05:03:32 +000080static cl::opt<bool>
81LoopUnswitchWithBlockFrequency("loop-unswitch-with-block-frequency",
82 cl::init(false), cl::Hidden,
83 cl::desc("Enable the use of the block frequency analysis to access PGO "
84 "heuristics to minimize code growth in cold regions."));
85
86static cl::opt<unsigned>
87ColdnessThreshold("loop-unswitch-coldness-threshold", cl::init(1), cl::Hidden,
88 cl::desc("Coldness threshold in percentage. The loop header frequency "
89 "(relative to the entry frequency) is compared with this "
90 "threshold to determine if non-trivial unswitching should be "
91 "enabled."));
92
Dan Gohmand78c4002008-05-13 00:00:25 +000093namespace {
Andrew Trick4104ed92012-04-10 05:14:37 +000094
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +000095 class LUAnalysisCache {
96
97 typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
98 UnswitchedValsMap;
Andrew Trick4104ed92012-04-10 05:14:37 +000099
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000100 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
Andrew Trick4104ed92012-04-10 05:14:37 +0000101
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000102 struct LoopProperties {
103 unsigned CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000104 unsigned WasUnswitchedCount;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000105 unsigned SizeEstimation;
106 UnswitchedValsMap UnswitchedVals;
107 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000108
109 // Here we use std::map instead of DenseMap, since we need to keep valid
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000110 // LoopProperties pointer for current loop for better performance.
111 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
112 typedef LoopPropsMap::iterator LoopPropsMapIt;
Andrew Trick4104ed92012-04-10 05:14:37 +0000113
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000114 LoopPropsMap LoopsProperties;
Jakub Staszak27da1232013-08-06 17:03:42 +0000115 UnswitchedValsMap *CurLoopInstructions;
116 LoopProperties *CurrentLoopProperties;
Andrew Trick4104ed92012-04-10 05:14:37 +0000117
Mark Heffernan9b536a62015-06-23 18:26:50 +0000118 // A loop unswitching with an estimated cost above this threshold
119 // is not performed. MaxSize is turned into unswitching quota for
120 // the current loop, and reduced correspondingly, though note that
121 // the quota is returned by releaseMemory() when the loop has been
122 // processed, so that MaxSize will return to its previous
123 // value. So in most cases MaxSize will equal the Threshold flag
124 // when a new loop is processed. An exception to that is that
125 // MaxSize will have a smaller value while processing nested loops
126 // that were introduced due to loop unswitching of an outer loop.
127 //
128 // FIXME: The way that MaxSize works is subtle and depends on the
129 // pass manager processing loops and calling releaseMemory() in a
130 // specific order. It would be good to find a more straightforward
131 // way of doing what MaxSize does.
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000132 unsigned MaxSize;
Andrew Trick4104ed92012-04-10 05:14:37 +0000133
Mark Heffernan9b536a62015-06-23 18:26:50 +0000134 public:
135 LUAnalysisCache()
136 : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
137 MaxSize(Threshold) {}
Andrew Trick4104ed92012-04-10 05:14:37 +0000138
Mark Heffernan9b536a62015-06-23 18:26:50 +0000139 // Analyze loop. Check its size, calculate is it possible to unswitch
140 // it. Returns true if we can unswitch this loop.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000141 bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
142 AssumptionCache *AC);
Andrew Trick4104ed92012-04-10 05:14:37 +0000143
Mark Heffernan9b536a62015-06-23 18:26:50 +0000144 // Clean all data related to given loop.
145 void forgetLoop(const Loop *L);
Andrew Trick4104ed92012-04-10 05:14:37 +0000146
Mark Heffernan9b536a62015-06-23 18:26:50 +0000147 // Mark case value as unswitched.
148 // Since SI instruction can be partly unswitched, in order to avoid
149 // extra unswitching in cloned loops keep track all unswitched values.
150 void setUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000151
Mark Heffernan9b536a62015-06-23 18:26:50 +0000152 // Check was this case value unswitched before or not.
153 bool isUnswitched(const SwitchInst *SI, const Value *V);
Andrew Trick4104ed92012-04-10 05:14:37 +0000154
Mark Heffernan9b536a62015-06-23 18:26:50 +0000155 // Returns true if another unswitching could be done within the cost
156 // threshold.
157 bool CostAllowsUnswitching();
Andrew Trick4104ed92012-04-10 05:14:37 +0000158
Mark Heffernan9b536a62015-06-23 18:26:50 +0000159 // Clone all loop-unswitch related loop properties.
160 // Redistribute unswitching quotas.
161 // Note, that new loop data is stored inside the VMap.
162 void cloneData(const Loop *NewLoop, const Loop *OldLoop,
163 const ValueToValueMapTy &VMap);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000164 };
Andrew Trick4104ed92012-04-10 05:14:37 +0000165
Chris Lattner2dd09db2009-09-02 06:11:42 +0000166 class LoopUnswitch : public LoopPass {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000167 LoopInfo *LI; // Loop information
Devang Patel901a27d2007-03-07 00:26:10 +0000168 LPPassManager *LPM;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000169 AssumptionCache *AC;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000170
Sanjay Patel956e29c2015-08-11 21:24:04 +0000171 // Used to check if second loop needs processing after
172 // RewriteLoopBodyWithConditionConstant rewrites first loop.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000173 std::vector<Loop*> LoopProcessWorklist;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000174
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000175 LUAnalysisCache BranchesInfo;
Andrew Trick4104ed92012-04-10 05:14:37 +0000176
Chen Li9f27fc02015-09-29 05:03:32 +0000177 bool EnabledPGO;
178
179 // BFI and ColdEntryFreq are only used when PGO and
180 // LoopUnswitchWithBlockFrequency are enabled.
181 BlockFrequencyInfo BFI;
182 BlockFrequency ColdEntryFreq;
183
Devang Patel506310d2007-06-06 00:21:03 +0000184 bool OptimizeForSize;
Devang Patel7d165e12007-07-30 23:07:10 +0000185 bool redoLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000186
Devang Patele149d4e2008-07-02 01:18:13 +0000187 Loop *currentLoop;
Devang Patela69f9872007-10-05 22:29:34 +0000188 DominatorTree *DT;
Devang Patele149d4e2008-07-02 01:18:13 +0000189 BasicBlock *loopHeader;
190 BasicBlock *loopPreheader;
Andrew Trick4104ed92012-04-10 05:14:37 +0000191
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000192 bool SanitizeMemory;
193 LoopSafetyInfo SafetyInfo;
194
Devang Pateled50fb52008-07-02 01:44:29 +0000195 // LoopBlocks contains all of the basic blocks of the loop, including the
Andrew Trick4104ed92012-04-10 05:14:37 +0000196 // preheader of the loop, the body of the loop, and the exit blocks of the
Devang Pateled50fb52008-07-02 01:44:29 +0000197 // loop, in that order.
198 std::vector<BasicBlock*> LoopBlocks;
199 // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
200 std::vector<BasicBlock*> NewBlocks;
Devang Pateleb611dd2008-07-03 17:37:52 +0000201
Chris Lattnerf48f7772004-04-19 18:07:02 +0000202 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000203 static char ID; // Pass ID, replacement for typeid
Andrew Trick4104ed92012-04-10 05:14:37 +0000204 explicit LoopUnswitch(bool Os = false) :
205 LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
Craig Topperf40110f2014-04-25 05:29:35 +0000206 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
207 loopPreheader(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000208 initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
209 }
Devang Patel09f162c2007-05-01 21:15:47 +0000210
Craig Topper3e4c6972014-03-05 09:10:37 +0000211 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Devang Patele149d4e2008-07-02 01:18:13 +0000212 bool processCurrentLoop();
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000213 bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000214 /// This transformation requires natural loop information & requires that
Chris Lattnerbc1a65a2010-08-29 17:23:19 +0000215 /// loop preheaders be inserted into the CFG.
Chris Lattnerf48f7772004-04-19 18:07:02 +0000216 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000217 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000218 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000219 AU.addRequired<TargetTransformInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000220 getLoopAnalysisUsage(AU);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000221 }
222
223 private:
Devang Pateld4911982007-07-31 08:03:26 +0000224
Craig Topper3e4c6972014-03-05 09:10:37 +0000225 void releaseMemory() override {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000226 BranchesInfo.forgetLoop(currentLoop);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000227 }
228
Devang Patele149d4e2008-07-02 01:18:13 +0000229 void initLoopData() {
230 loopHeader = currentLoop->getHeader();
231 loopPreheader = currentLoop->getLoopPreheader();
232 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000233
Chris Lattner559c8672008-04-21 00:25:49 +0000234 /// Split all of the edges from inside the loop to their exit blocks.
235 /// Update the appropriate Phi nodes as we do so.
Sanjay Patel41f3d952015-08-11 21:11:56 +0000236 void SplitExitEdges(Loop *L,
237 const SmallVectorImpl<BasicBlock *> &ExitBlocks);
Devang Patela69f9872007-10-05 22:29:34 +0000238
Chen Lic0f3a152015-07-22 05:26:29 +0000239 bool TryTrivialLoopUnswitch(bool &Changed);
240
Weiming Zhaof1abad52015-06-23 05:31:09 +0000241 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
242 TerminatorInst *TI = nullptr);
Chris Lattner29f771b2006-02-18 01:27:45 +0000243 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000244 BasicBlock *ExitBlock, TerminatorInst *TI);
245 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
246 TerminatorInst *TI);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000247
248 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
249 Constant *Val, bool isEqual);
Devang Patel3304e462007-06-28 00:49:00 +0000250
251 void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
Andrew Trick4104ed92012-04-10 05:14:37 +0000252 BasicBlock *TrueDest,
Devang Patel3304e462007-06-28 00:49:00 +0000253 BasicBlock *FalseDest,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000254 Instruction *InsertPt,
255 TerminatorInst *TI);
Devang Patel3304e462007-06-28 00:49:00 +0000256
Devang Pateld4911982007-07-31 08:03:26 +0000257 void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000258 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000259}
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000260
261// Analyze loop. Check its size, calculate is it possible to unswitch
262// it. Returns true if we can unswitch this loop.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000263bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
264 AssumptionCache *AC) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000265
Jakub Staszak27da1232013-08-06 17:03:42 +0000266 LoopPropsMapIt PropsIt;
267 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000268 std::tie(PropsIt, Inserted) =
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000269 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
Andrew Trick4104ed92012-04-10 05:14:37 +0000270
Jakub Staszak27da1232013-08-06 17:03:42 +0000271 LoopProperties &Props = PropsIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000272
Jakub Staszak27da1232013-08-06 17:03:42 +0000273 if (Inserted) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000274 // New loop.
275
276 // Limit the number of instructions to avoid causing significant code
277 // expansion, and the number of basic blocks, to avoid loops with
278 // large numbers of branches which cause loop unswitching to go crazy.
279 // This is a very ad-hoc heuristic.
Andrew Trick4104ed92012-04-10 05:14:37 +0000280
Hal Finkel57f03dd2014-09-07 13:49:57 +0000281 SmallPtrSet<const Value *, 32> EphValues;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000282 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
Hal Finkel57f03dd2014-09-07 13:49:57 +0000283
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000284 // FIXME: This is overly conservative because it does not take into
285 // consideration code simplification opportunities and code that can
286 // be shared by the resultant unswitched loops.
287 CodeMetrics Metrics;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000288 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
289 ++I)
Hal Finkel57f03dd2014-09-07 13:49:57 +0000290 Metrics.analyzeBasicBlock(*I, TTI, EphValues);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000291
Mark Heffernan9b536a62015-06-23 18:26:50 +0000292 Props.SizeEstimation = Metrics.NumInsts;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000293 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
Mark Heffernan9b536a62015-06-23 18:26:50 +0000294 Props.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000295 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
James Molloy4f6fb952012-12-20 16:04:27 +0000296
297 if (Metrics.notDuplicatable) {
298 DEBUG(dbgs() << "NOT unswitching loop %"
Jakub Staszak27da1232013-08-06 17:03:42 +0000299 << L->getHeader()->getName() << ", contents cannot be "
300 << "duplicated!\n");
James Molloy4f6fb952012-12-20 16:04:27 +0000301 return false;
302 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000303 }
304
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000305 // Be careful. This links are good only before new loop addition.
306 CurrentLoopProperties = &Props;
307 CurLoopInstructions = &Props.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000308
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000309 return true;
310}
311
312// Clean all data related to given loop.
Jakub Staszak27da1232013-08-06 17:03:42 +0000313void LUAnalysisCache::forgetLoop(const Loop *L) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000314
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000315 LoopPropsMapIt LIt = LoopsProperties.find(L);
316
317 if (LIt != LoopsProperties.end()) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000318 LoopProperties &Props = LIt->second;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000319 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
320 Props.SizeEstimation;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000321 LoopsProperties.erase(LIt);
322 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000323
Craig Topperf40110f2014-04-25 05:29:35 +0000324 CurrentLoopProperties = nullptr;
325 CurLoopInstructions = nullptr;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000326}
327
328// Mark case value as unswitched.
329// Since SI instruction can be partly unswitched, in order to avoid
330// extra unswitching in cloned loops keep track all unswitched values.
Jakub Staszak27da1232013-08-06 17:03:42 +0000331void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000332 (*CurLoopInstructions)[SI].insert(V);
333}
334
335// Check was this case value unswitched before or not.
Jakub Staszak27da1232013-08-06 17:03:42 +0000336bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000337 return (*CurLoopInstructions)[SI].count(V);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000338}
339
Mark Heffernan9b536a62015-06-23 18:26:50 +0000340bool LUAnalysisCache::CostAllowsUnswitching() {
341 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
342}
343
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000344// Clone all loop-unswitch related loop properties.
345// Redistribute unswitching quotas.
346// Note, that new loop data is stored inside the VMap.
Jakub Staszak27da1232013-08-06 17:03:42 +0000347void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
348 const ValueToValueMapTy &VMap) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000349
Jakub Staszak27da1232013-08-06 17:03:42 +0000350 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
351 LoopProperties &OldLoopProps = *CurrentLoopProperties;
352 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
Andrew Trick4104ed92012-04-10 05:14:37 +0000353
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000354 // Reallocate "can-be-unswitched quota"
355
356 --OldLoopProps.CanBeUnswitchedCount;
Mark Heffernan9b536a62015-06-23 18:26:50 +0000357 ++OldLoopProps.WasUnswitchedCount;
358 NewLoopProps.WasUnswitchedCount = 0;
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000359 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
360 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
361 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
Andrew Trick4104ed92012-04-10 05:14:37 +0000362
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000363 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
Andrew Trick4104ed92012-04-10 05:14:37 +0000364
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000365 // Clone unswitched values info:
366 // for new loop switches we clone info about values that was
367 // already unswitched and has redundant successors.
368 for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000369 const SwitchInst *OldInst = I->first;
370 Value *NewI = VMap.lookup(OldInst);
371 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000372 assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
Andrew Trick4104ed92012-04-10 05:14:37 +0000373
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000374 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
375 }
376}
377
Dan Gohmand78c4002008-05-13 00:00:25 +0000378char LoopUnswitch::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000379INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
380 false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000381INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth31088a92016-02-19 10:45:18 +0000382INITIALIZE_PASS_DEPENDENCY(LoopPass)
383INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000384INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
385 false, false)
Chris Lattnerf48f7772004-04-19 18:07:02 +0000386
Andrew Trick4104ed92012-04-10 05:14:37 +0000387Pass *llvm::createLoopUnswitchPass(bool Os) {
388 return new LoopUnswitch(Os);
Devang Patel506310d2007-06-06 00:21:03 +0000389}
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000390
Sanjay Patel956e29c2015-08-11 21:24:04 +0000391/// Cond is a condition that occurs in L. If it is invariant in the loop, or has
392/// an invariant piece, return the invariant. Otherwise, return null.
Sanjoy Dasd8500682016-06-25 01:14:19 +0000393static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
394 DenseMap<Value *, Value *> &Cache) {
395 auto CacheIt = Cache.find(Cond);
396 if (CacheIt != Cache.end())
397 return CacheIt->second;
Andrew Trick4104ed92012-04-10 05:14:37 +0000398
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000399 // We started analyze new instruction, increment scanned instructions counter.
400 ++TotalInsts;
Andrew Trick4104ed92012-04-10 05:14:37 +0000401
Chris Lattner302240d2010-02-02 02:26:54 +0000402 // We can never unswitch on vector conditions.
Duncan Sands19d0b472010-02-16 11:11:14 +0000403 if (Cond->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000404 return nullptr;
Chris Lattner302240d2010-02-02 02:26:54 +0000405
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000406 // Constants should be folded, not unswitched on!
Craig Topperf40110f2014-04-25 05:29:35 +0000407 if (isa<Constant>(Cond)) return nullptr;
Devang Patel3c723c82007-06-28 00:44:10 +0000408
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000409 // TODO: Handle: br (VARIANT|INVARIANT).
Devang Patelfe57d102008-11-03 19:38:07 +0000410
Dan Gohman4d6149f2009-07-14 01:37:59 +0000411 // Hoist simple values out.
Sanjoy Dasd8500682016-06-25 01:14:19 +0000412 if (L->makeLoopInvariant(Cond, Changed)) {
413 Cache[Cond] = Cond;
Dan Gohman4d6149f2009-07-14 01:37:59 +0000414 return Cond;
Sanjoy Dasd8500682016-06-25 01:14:19 +0000415 }
Dan Gohman4d6149f2009-07-14 01:37:59 +0000416
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
418 if (BO->getOpcode() == Instruction::And ||
419 BO->getOpcode() == Instruction::Or) {
420 // If either the left or right side is invariant, we can unswitch on this,
421 // which will cause the branch to go away in one loop and the condition to
422 // simplify in the other one.
Sanjoy Dasd8500682016-06-25 01:14:19 +0000423 if (Value *LHS =
424 FindLIVLoopCondition(BO->getOperand(0), L, Changed, Cache)) {
425 Cache[Cond] = LHS;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000426 return LHS;
Sanjoy Dasd8500682016-06-25 01:14:19 +0000427 }
428 if (Value *RHS =
429 FindLIVLoopCondition(BO->getOperand(1), L, Changed, Cache)) {
430 Cache[Cond] = RHS;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000431 return RHS;
Sanjoy Dasd8500682016-06-25 01:14:19 +0000432 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000433 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000434
Sanjoy Dasd8500682016-06-25 01:14:19 +0000435 Cache[Cond] = nullptr;
Craig Topperf40110f2014-04-25 05:29:35 +0000436 return nullptr;
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000437}
438
Sanjoy Dasd8500682016-06-25 01:14:19 +0000439static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
440 DenseMap<Value *, Value *> Cache;
441 return FindLIVLoopCondition(Cond, L, Changed, Cache);
442}
443
Devang Patel901a27d2007-03-07 00:26:10 +0000444bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000445 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000446 return false;
447
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000448 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
449 *L->getHeader()->getParent());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000450 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Devang Patel901a27d2007-03-07 00:26:10 +0000451 LPM = &LPM_Ref;
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000452 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Devang Patele149d4e2008-07-02 01:18:13 +0000453 currentLoop = L;
Devang Patel40519f02008-09-04 22:43:59 +0000454 Function *F = currentLoop->getHeader()->getParent();
Chen Li9f27fc02015-09-29 05:03:32 +0000455
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000456 SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
457 if (SanitizeMemory)
458 computeLoopSafetyInfo(&SafetyInfo, L);
459
Chen Li9f27fc02015-09-29 05:03:32 +0000460 EnabledPGO = F->getEntryCount().hasValue();
461
462 if (LoopUnswitchWithBlockFrequency && EnabledPGO) {
463 BranchProbabilityInfo BPI(*F, *LI);
464 BFI.calculate(*L->getHeader()->getParent(), BPI, *LI);
465
466 // Use BranchProbability to compute a minimum frequency based on
467 // function entry baseline frequency. Loops with headers below this
468 // frequency are considered as cold.
469 const BranchProbability ColdProb(ColdnessThreshold, 100);
470 ColdEntryFreq = BlockFrequency(BFI.getEntryFreq()) * ColdProb;
471 }
472
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000473 bool Changed = false;
Devang Patel7d165e12007-07-30 23:07:10 +0000474 do {
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000475 assert(currentLoop->isLCSSAForm(*DT));
Devang Patel7d165e12007-07-30 23:07:10 +0000476 redoLoop = false;
Devang Patele149d4e2008-07-02 01:18:13 +0000477 Changed |= processCurrentLoop();
Devang Patel7d165e12007-07-30 23:07:10 +0000478 } while(redoLoop);
479
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +0000480 // FIXME: Reconstruct dom info, because it is not preserved properly.
481 if (Changed)
482 DT->recalculate(*F);
Devang Patel7d165e12007-07-30 23:07:10 +0000483 return Changed;
484}
485
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000486// Return true if the BasicBlock BB is unreachable from the loop header.
487// Return false, otherwise.
488bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
489 auto *Node = DT->getNode(BB)->getIDom();
490 BasicBlock *DomBB = Node->getBlock();
491 while (currentLoop->contains(DomBB)) {
492 BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
493
494 Node = DT->getNode(DomBB)->getIDom();
495 DomBB = Node->getBlock();
496
497 if (!BInst || !BInst->isConditional())
498 continue;
499
500 Value *Cond = BInst->getCondition();
501 if (!isa<ConstantInt>(Cond))
502 continue;
503
504 BasicBlock *UnreachableSucc =
505 Cond == ConstantInt::getTrue(Cond->getContext())
506 ? BInst->getSuccessor(1)
507 : BInst->getSuccessor(0);
508
509 if (DT->dominates(UnreachableSucc, BB))
510 return true;
511 }
512 return false;
513}
514
Sanjay Patel956e29c2015-08-11 21:24:04 +0000515/// Do actual work and unswitch loop if possible and profitable.
Devang Patele149d4e2008-07-02 01:18:13 +0000516bool LoopUnswitch::processCurrentLoop() {
Devang Patel7d165e12007-07-30 23:07:10 +0000517 bool Changed = false;
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000518
519 initLoopData();
Andrew Trick4104ed92012-04-10 05:14:37 +0000520
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000521 // If LoopSimplify was unable to form a preheader, don't do any unswitching.
522 if (!loopPreheader)
523 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000524
Andrew Trick4442bfe2012-04-10 05:14:42 +0000525 // Loops with indirectbr cannot be cloned.
526 if (!currentLoop->isSafeToClone())
527 return false;
528
529 // Without dedicated exits, splitting the exit edge may fail.
530 if (!currentLoop->hasDedicatedExits())
531 return false;
532
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000533 LLVMContext &Context = loopHeader->getContext();
Andrew Trick4104ed92012-04-10 05:14:37 +0000534
Chen Li567aa7a2015-10-14 19:47:43 +0000535 // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
Chandler Carruth705b1852015-01-31 03:43:40 +0000536 if (!BranchesInfo.countLoop(
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000537 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000538 *currentLoop->getHeader()->getParent()),
539 AC))
Stepan Dyatkovskiy82165692012-01-11 08:40:51 +0000540 return false;
Devang Patel7d165e12007-07-30 23:07:10 +0000541
Chen Lic0f3a152015-07-22 05:26:29 +0000542 // Try trivial unswitch first before loop over other basic blocks in the loop.
543 if (TryTrivialLoopUnswitch(Changed)) {
544 return true;
545 }
546
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000547 // Run through the instructions in the loop, keeping track of three things:
548 //
549 // - That we do not unswitch loops containing convergent operations, as we
550 // might be making them control dependent on the unswitch value when they
551 // were not before.
552 // FIXME: This could be refined to only bail if the convergent operation is
553 // not already control-dependent on the unswitch value.
554 //
555 // - That basic blocks in the loop contain invokes whose predecessor edges we
556 // cannot split.
557 //
558 // - The set of guard intrinsics encountered (these are non terminator
559 // instructions that are also profitable to be unswitched).
560
561 SmallVector<IntrinsicInst *, 4> Guards;
562
Owen Anderson2c9978b2015-10-09 18:40:20 +0000563 for (const auto BB : currentLoop->blocks()) {
Owen Anderson97ca0f32015-10-09 20:17:46 +0000564 for (auto &I : *BB) {
565 auto CS = CallSite(&I);
566 if (!CS) continue;
567 if (CS.hasFnAttr(Attribute::Convergent))
Owen Anderson2c9978b2015-10-09 18:40:20 +0000568 return false;
David Majnemer3d90bb72016-05-03 03:57:40 +0000569 if (auto *II = dyn_cast<InvokeInst>(&I))
570 if (!II->getUnwindDest()->canSplitPredecessors())
571 return false;
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000572 if (auto *II = dyn_cast<IntrinsicInst>(&I))
573 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
574 Guards.push_back(II);
Owen Anderson2c9978b2015-10-09 18:40:20 +0000575 }
576 }
577
Chen Lif458c6f2015-08-13 05:24:29 +0000578 // Do not do non-trivial unswitch while optimizing for size.
579 // FIXME: Use Function::optForSize().
580 if (OptimizeForSize ||
581 loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
582 return false;
583
Chen Li9f27fc02015-09-29 05:03:32 +0000584 if (LoopUnswitchWithBlockFrequency && EnabledPGO) {
585 // Compute the weighted frequency of the hottest block in the
586 // loop (loopHeader in this case since inner loops should be
587 // processed before outer loop). If it is less than ColdFrequency,
588 // we should not unswitch.
589 BlockFrequency LoopEntryFreq = BFI.getBlockFreq(loopHeader);
590 if (LoopEntryFreq < ColdEntryFreq)
591 return false;
592 }
593
Sanjoy Dasa37bb4a2016-06-26 05:10:45 +0000594 for (IntrinsicInst *Guard : Guards) {
595 Value *LoopCond =
596 FindLIVLoopCondition(Guard->getOperand(0), currentLoop, Changed);
597 if (LoopCond &&
598 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
599 // NB! Unswitching (if successful) could have erased some of the
600 // instructions in Guards leaving dangling pointers there. This is fine
601 // because we're returning now, and won't look at Guards again.
602 ++NumGuards;
603 return true;
604 }
605 }
606
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000607 // Loop over all of the basic blocks in the loop. If we find an interior
608 // block that is branching on a loop-invariant condition, we can unswitch this
609 // loop.
Andrew Trick4104ed92012-04-10 05:14:37 +0000610 for (Loop::block_iterator I = currentLoop->block_begin(),
Chris Lattnerc832c1b2010-04-05 21:18:32 +0000611 E = currentLoop->block_end(); I != E; ++I) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000612 TerminatorInst *TI = (*I)->getTerminator();
Evgeniy Stepanoveaea2972016-06-10 20:03:20 +0000613
614 // Unswitching on a potentially uninitialized predicate is not
615 // MSan-friendly. Limit this to the cases when the original predicate is
616 // guaranteed to execute, to avoid creating a use-of-uninitialized-value
617 // in the code that did not have one.
618 // This is a workaround for the discrepancy between LLVM IR and MSan
619 // semantics. See PR28054 for more details.
620 if (SanitizeMemory &&
621 !isGuaranteedToExecute(*TI, DT, currentLoop, &SafetyInfo))
622 continue;
623
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000624 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Abhilash Bhandari54e5a1a2016-11-25 14:07:44 +0000625 // Some branches may be rendered unreachable because of previous
626 // unswitching.
627 // Unswitch only those branches that are reachable.
628 if (isUnreachableDueToPreviousUnswitching(*I))
629 continue;
630
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000631 // If this isn't branching on an invariant condition, we can't unswitch
632 // it.
633 if (BI->isConditional()) {
634 // See if this, or some part of it, is loop invariant. If so, we can
635 // unswitch on it if we desire.
Andrew Trick4104ed92012-04-10 05:14:37 +0000636 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000637 currentLoop, Changed);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000638 if (LoopCond &&
639 UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000640 ++NumBranches;
641 return true;
642 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000643 }
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000644 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000645 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000646 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000647 unsigned NumCases = SI->getNumCases();
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000648 if (LoopCond && NumCases) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000649 // Find a value to unswitch on:
650 // FIXME: this should chose the most expensive case!
Nick Lewycky61158242011-06-03 06:27:15 +0000651 // FIXME: scan for a case with a non-critical edge?
Craig Topperf40110f2014-04-25 05:29:35 +0000652 Constant *UnswitchVal = nullptr;
Andrew Trick4104ed92012-04-10 05:14:37 +0000653
Devang Patel967b84c2007-02-26 19:31:58 +0000654 // Do not process same value again and again.
Chad Rosier3ba90a12011-12-22 21:10:46 +0000655 // At this point we have some cases already unswitched and
656 // some not yet unswitched. Let's find the first not yet unswitched one.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +0000657 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000658 i != e; ++i) {
Jakub Staszak27da1232013-08-06 17:03:42 +0000659 Constant *UnswitchValCandidate = i.getCaseValue();
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +0000660 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
Chad Rosier3ba90a12011-12-22 21:10:46 +0000661 UnswitchVal = UnswitchValCandidate;
662 break;
663 }
664 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000665
Chad Rosier3ba90a12011-12-22 21:10:46 +0000666 if (!UnswitchVal)
Devang Patel967b84c2007-02-26 19:31:58 +0000667 continue;
Devang Patel967b84c2007-02-26 19:31:58 +0000668
Devang Patele149d4e2008-07-02 01:18:13 +0000669 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000670 ++NumSwitches;
671 return true;
672 }
673 }
674 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000675
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000676 // Scan the instructions to check for unswitchable values.
Andrew Trick4104ed92012-04-10 05:14:37 +0000677 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000678 BBI != E; ++BBI)
679 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
Andrew Trick4104ed92012-04-10 05:14:37 +0000680 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
Devang Patele149d4e2008-07-02 01:18:13 +0000681 currentLoop, Changed);
Andrew Trick4104ed92012-04-10 05:14:37 +0000682 if (LoopCond && UnswitchIfProfitable(LoopCond,
Owen Anderson23a204d2009-07-31 17:39:07 +0000683 ConstantInt::getTrue(Context))) {
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000684 ++NumSelects;
685 return true;
686 }
687 }
688 }
Chris Lattnerf48f7772004-04-19 18:07:02 +0000689 return Changed;
690}
691
Sanjay Patel956e29c2015-08-11 21:24:04 +0000692/// Check to see if all paths from BB exit the loop with no side effects
693/// (including infinite loops).
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000694///
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000695/// If true, we return true and set ExitBB to the block we
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000696/// exit through.
697///
698static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
699 BasicBlock *&ExitBB,
700 std::set<BasicBlock*> &Visited) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000701 if (!Visited.insert(BB).second) {
Nick Lewyckyd9d1de42011-12-23 23:49:25 +0000702 // Already visited. Without more analysis, this could indicate an infinite
703 // loop.
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000704 return false;
Jakub Staszak27da1232013-08-06 17:03:42 +0000705 }
706 if (!L->contains(BB)) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000707 // Otherwise, this is a loop exit, this is fine so long as this is the
708 // first exit.
Craig Topperf40110f2014-04-25 05:29:35 +0000709 if (ExitBB) return false;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000710 ExitBB = BB;
Edward O'Callaghan2b8fed12009-11-25 05:38:41 +0000711 return true;
Chris Lattnerbaddba42006-02-17 06:39:56 +0000712 }
Andrew Trick4104ed92012-04-10 05:14:37 +0000713
Chris Lattnerbaddba42006-02-17 06:39:56 +0000714 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000715 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattnerbaddba42006-02-17 06:39:56 +0000716 // Check to see if the successor is a trivial loop exit.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000717 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
Chris Lattnerbaddba42006-02-17 06:39:56 +0000718 return false;
Chris Lattner6e263152006-02-10 02:30:37 +0000719 }
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000720
721 // Okay, everything after this looks good, check to make sure that this block
722 // doesn't include any side effects.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000723 for (Instruction &I : *BB)
724 if (I.mayHaveSideEffects())
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000725 return false;
Andrew Trick4104ed92012-04-10 05:14:37 +0000726
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000727 return true;
Chris Lattner6e263152006-02-10 02:30:37 +0000728}
729
Sanjay Patel956e29c2015-08-11 21:24:04 +0000730/// Return true if the specified block unconditionally leads to an exit from
731/// the specified loop, and has no side-effects in the process. If so, return
732/// the block that is exited to, otherwise return null.
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000733static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
734 std::set<BasicBlock*> Visited;
Dan Gohman0ad7d9c2010-09-01 21:46:45 +0000735 Visited.insert(L->getHeader()); // Branches to header make infinite loops.
Craig Topperf40110f2014-04-25 05:29:35 +0000736 BasicBlock *ExitBB = nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000737 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
738 return ExitBB;
Craig Topperf40110f2014-04-25 05:29:35 +0000739 return nullptr;
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000740}
Chris Lattner6e263152006-02-10 02:30:37 +0000741
Sanjay Patel956e29c2015-08-11 21:24:04 +0000742/// We have found that we can unswitch currentLoop when LoopCond == Val to
743/// simplify the loop. If we decide that this is profitable,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000744/// unswitch the loop, reprocess the pieces, then return true.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000745bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
746 TerminatorInst *TI) {
Evan Chenged66db32010-04-03 02:23:43 +0000747 // Check to see if it would be profitable to unswitch current loop.
Mark Heffernan9b536a62015-06-23 18:26:50 +0000748 if (!BranchesInfo.CostAllowsUnswitching()) {
749 DEBUG(dbgs() << "NOT unswitching loop %"
750 << currentLoop->getHeader()->getName()
751 << " at non-trivial condition '" << *Val
752 << "' == " << *LoopCond << "\n"
753 << ". Cost too high.\n");
754 return false;
755 }
Evan Chenged66db32010-04-03 02:23:43 +0000756
Weiming Zhaof1abad52015-06-23 05:31:09 +0000757 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
Andrew Trick4442bfe2012-04-10 05:14:42 +0000758 return true;
Chris Lattnerfbadd7e2006-02-11 00:43:37 +0000759}
760
Sanjay Patel956e29c2015-08-11 21:24:04 +0000761/// Recursively clone the specified loop and all of its children,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000762/// mapping the blocks with the specified map.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000763static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
Devang Patel901a27d2007-03-07 00:26:10 +0000764 LoopInfo *LI, LPPassManager *LPM) {
Justin Bogner35e46cd2015-10-22 21:21:32 +0000765 Loop &New = LPM->addLoop(PL);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000766
767 // Add all of the blocks in L to the new loop.
768 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
769 I != E; ++I)
770 if (LI->getLoopFor(*I) == L)
Justin Bogner35e46cd2015-10-22 21:21:32 +0000771 New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
Chris Lattnerf48f7772004-04-19 18:07:02 +0000772
773 // Add all of the subloops to the new loop.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000774 for (Loop *I : *L)
775 CloneLoop(I, &New, VM, LI, LPM);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000776
Justin Bogner35e46cd2015-10-22 21:21:32 +0000777 return &New;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000778}
779
Sanjay Patel956e29c2015-08-11 21:24:04 +0000780/// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
781/// otherwise branch to FalseDest. Insert the code immediately before InsertPt.
Devang Patel3304e462007-06-28 00:49:00 +0000782void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
783 BasicBlock *TrueDest,
784 BasicBlock *FalseDest,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000785 Instruction *InsertPt,
786 TerminatorInst *TI) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000787 // Insert a conditional branch on LIC to the two preheaders. The original
788 // code is the true version and the new code is the false version.
789 Value *BranchVal = LIC;
Weiming Zhaof1abad52015-06-23 05:31:09 +0000790 bool Swapped = false;
Owen Anderson55f1c092009-08-13 21:58:54 +0000791 if (!isa<ConstantInt>(Val) ||
792 Val->getType() != Type::getInt1Ty(LIC->getContext()))
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000793 BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000794 else if (Val != ConstantInt::getTrue(Val->getContext())) {
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000795 // We want to enter the new loop when the condition is true.
796 std::swap(TrueDest, FalseDest);
Weiming Zhaof1abad52015-06-23 05:31:09 +0000797 Swapped = true;
798 }
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000799
800 // Insert the new branch.
Xinliang David Li7a28a7f2016-09-03 22:26:11 +0000801 BranchInst *BI =
802 IRBuilder<>(InsertPt).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
803 if (Swapped)
804 BI->swapProfMetadata();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000805
806 // If either edge is critical, split it. This helps preserve LoopSimplify
807 // form for enclosing loops.
Chandler Carruthf8753fc2015-01-19 12:12:00 +0000808 auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000809 SplitCriticalEdge(BI, 0, Options);
810 SplitCriticalEdge(BI, 1, Options);
Chris Lattnerb0cbe712006-02-15 00:07:43 +0000811}
812
Sanjay Patel956e29c2015-08-11 21:24:04 +0000813/// Given a loop that has a trivial unswitchable condition in it (a cond branch
814/// from its header block to its latch block, where the path through the loop
815/// that doesn't execute its body has no side-effects), unswitch it. This
816/// doesn't involve any code duplication, just moving the conditional branch
817/// outside of the loop and updating loop info.
Weiming Zhaof1abad52015-06-23 05:31:09 +0000818void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
819 BasicBlock *ExitBlock,
820 TerminatorInst *TI) {
David Greened9c355d2010-01-05 01:27:04 +0000821 DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
Weiming Zhaof1abad52015-06-23 05:31:09 +0000822 << loopHeader->getName() << " [" << L->getBlocks().size()
823 << " blocks] in Function "
824 << L->getHeader()->getParent()->getName() << " on cond: " << *Val
825 << " == " << *Cond << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +0000826
Chris Lattnerfe4151e2006-02-10 23:16:39 +0000827 // First step, split the preheader, so that we know that there is a safe place
Devang Patele149d4e2008-07-02 01:18:13 +0000828 // to insert the conditional branch. We will change loopPreheader to have a
Chris Lattnered7a67b2006-02-10 01:24:09 +0000829 // conditional branch on Cond.
Chandler Carruthd4500562015-01-19 12:36:53 +0000830 BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
Chris Lattnered7a67b2006-02-10 01:24:09 +0000831
832 // Now that we have a place to insert the conditional branch, create a place
Chris Lattner49354172006-02-10 02:01:22 +0000833 // to branch to: this is the exit block out of the loop that we should
834 // short-circuit to.
Andrew Trick4104ed92012-04-10 05:14:37 +0000835
Chris Lattnere5cb76d2006-02-15 22:03:36 +0000836 // Split this block now, so that the loop maintains its exit block, and so
837 // that the jump from the preheader can execute the contents of the exit block
838 // without actually branching to it (the exit block should be dominated by the
839 // loop header, not the preheader).
Chris Lattner49354172006-02-10 02:01:22 +0000840 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000841 BasicBlock *NewExit = SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI);
Andrew Trick4104ed92012-04-10 05:14:37 +0000842
843 // Okay, now we have a position to branch from and a position to branch to,
Chris Lattnered7a67b2006-02-10 01:24:09 +0000844 // insert the new conditional branch.
Andrew Trick4104ed92012-04-10 05:14:37 +0000845 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
Weiming Zhaof1abad52015-06-23 05:31:09 +0000846 loopPreheader->getTerminator(), TI);
Devang Patele149d4e2008-07-02 01:18:13 +0000847 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
848 loopPreheader->getTerminator()->eraseFromParent();
Chris Lattnered7a67b2006-02-10 01:24:09 +0000849
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +0000850 // We need to reprocess this loop, it could be unswitched again.
Devang Patel7d165e12007-07-30 23:07:10 +0000851 redoLoop = true;
Andrew Trick4104ed92012-04-10 05:14:37 +0000852
Chris Lattnered7a67b2006-02-10 01:24:09 +0000853 // Now that we know that the loop is never entered when this condition is a
854 // particular value, rewrite the loop with this info. We know that this will
855 // at least eliminate the old branch.
Chris Lattner8a5a3242006-02-22 06:37:14 +0000856 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner0b8ec1a2006-02-14 01:01:41 +0000857 ++NumTrivial;
Chris Lattnered7a67b2006-02-10 01:24:09 +0000858}
859
Sanjay Patel41f3d952015-08-11 21:11:56 +0000860/// Check if the first non-constant condition starting from the loop header is
861/// a trivial unswitch condition: that is, a condition controls whether or not
862/// the loop does anything at all. If it is a trivial condition, unswitching
863/// produces no code duplications (equivalently, it produces a simpler loop and
864/// a new empty loop, which gets deleted). Therefore always unswitch trivial
865/// condition.
Chen Lic0f3a152015-07-22 05:26:29 +0000866bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
Chen Li145c2f52015-07-25 03:21:06 +0000867 BasicBlock *CurrentBB = currentLoop->getHeader();
868 TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
869 LLVMContext &Context = CurrentBB->getContext();
Chen Lic0f3a152015-07-22 05:26:29 +0000870
Chen Li145c2f52015-07-25 03:21:06 +0000871 // If loop header has only one reachable successor (currently via an
872 // unconditional branch or constant foldable conditional branch, but
873 // should also consider adding constant foldable switch instruction in
874 // future), we should keep looking for trivial condition candidates in
875 // the successor as well. An alternative is to constant fold conditions
876 // and merge successors into loop header (then we only need to check header's
877 // terminator). The reason for not doing this in LoopUnswitch pass is that
878 // it could potentially break LoopPassManager's invariants. Folding dead
879 // branches could either eliminate the current loop or make other loops
Sanjay Patel41f3d952015-08-11 21:11:56 +0000880 // unreachable. LCSSA form might also not be preserved after deleting
881 // branches. The following code keeps traversing loop header's successors
882 // until it finds the trivial condition candidate (condition that is not a
883 // constant). Since unswitching generates branches with constant conditions,
884 // this scenario could be very common in practice.
Chen Li145c2f52015-07-25 03:21:06 +0000885 SmallSet<BasicBlock*, 8> Visited;
886
887 while (true) {
888 // If we exit loop or reach a previous visited block, then
889 // we can not reach any trivial condition candidates (unfoldable
890 // branch instructions or switch instructions) and no unswitch
891 // can happen. Exit and return false.
892 if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
Chen Lic0f3a152015-07-22 05:26:29 +0000893 return false;
894
Chen Li145c2f52015-07-25 03:21:06 +0000895 // Check if this loop will execute any side-effecting instructions (e.g.
896 // stores, calls, volatile loads) in the part of the loop that the code
897 // *would* execute. Check the header first.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000898 for (Instruction &I : *CurrentBB)
899 if (I.mayHaveSideEffects())
Chen Li145c2f52015-07-25 03:21:06 +0000900 return false;
901
902 // FIXME: add check for constant foldable switch instructions.
903 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
904 if (BI->isUnconditional()) {
905 CurrentBB = BI->getSuccessor(0);
906 } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
907 CurrentBB = BI->getSuccessor(0);
908 } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
909 CurrentBB = BI->getSuccessor(1);
910 } else {
Sanjay Patel41f3d952015-08-11 21:11:56 +0000911 // Found a trivial condition candidate: non-foldable conditional branch.
Chen Li145c2f52015-07-25 03:21:06 +0000912 break;
913 }
914 } else {
915 break;
916 }
917
918 CurrentTerm = CurrentBB->getTerminator();
919 }
920
Chen Lic0f3a152015-07-22 05:26:29 +0000921 // CondVal is the condition that controls the trivial condition.
922 // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
923 Constant *CondVal = nullptr;
924 BasicBlock *LoopExitBB = nullptr;
925
Chen Li145c2f52015-07-25 03:21:06 +0000926 if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +0000927 // If this isn't branching on an invariant condition, we can't unswitch it.
928 if (!BI->isConditional())
929 return false;
930
931 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
932 currentLoop, Changed);
933
934 // Unswitch only if the trivial condition itself is an LIV (not
935 // partial LIV which could occur in and/or)
936 if (!LoopCond || LoopCond != BI->getCondition())
937 return false;
938
939 // Check to see if a successor of the branch is guaranteed to
940 // exit through a unique exit block without having any
941 // side-effects. If so, determine the value of Cond that causes
942 // it to do this.
943 if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
944 BI->getSuccessor(0)))) {
945 CondVal = ConstantInt::getTrue(Context);
946 } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
947 BI->getSuccessor(1)))) {
948 CondVal = ConstantInt::getFalse(Context);
949 }
950
Sanjay Patel41f3d952015-08-11 21:11:56 +0000951 // If we didn't find a single unique LoopExit block, or if the loop exit
952 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +0000953 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
954 return false; // Can't handle this.
955
Sanjay Patel41f3d952015-08-11 21:11:56 +0000956 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
957 CurrentTerm);
Chen Lic0f3a152015-07-22 05:26:29 +0000958 ++NumBranches;
959 return true;
Chen Li145c2f52015-07-25 03:21:06 +0000960 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
Chen Lic0f3a152015-07-22 05:26:29 +0000961 // If this isn't switching on an invariant condition, we can't unswitch it.
962 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
963 currentLoop, Changed);
964
965 // Unswitch only if the trivial condition itself is an LIV (not
966 // partial LIV which could occur in and/or)
967 if (!LoopCond || LoopCond != SI->getCondition())
968 return false;
969
970 // Check to see if a successor of the switch is guaranteed to go to the
971 // latch block or exit through a one exit block without having any
972 // side-effects. If so, determine the value of Cond that causes it to do
973 // this.
974 // Note that we can't trivially unswitch on the default case or
975 // on already unswitched cases.
976 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
977 i != e; ++i) {
978 BasicBlock *LoopExitCandidate;
979 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
980 i.getCaseSuccessor()))) {
981 // Okay, we found a trivial case, remember the value that is trivial.
982 ConstantInt *CaseVal = i.getCaseValue();
983
984 // Check that it was not unswitched before, since already unswitched
985 // trivial vals are looks trivial too.
986 if (BranchesInfo.isUnswitched(SI, CaseVal))
987 continue;
988 LoopExitBB = LoopExitCandidate;
989 CondVal = CaseVal;
990 break;
991 }
992 }
993
Sanjay Patel41f3d952015-08-11 21:11:56 +0000994 // If we didn't find a single unique LoopExit block, or if the loop exit
995 // block contains phi nodes, this isn't trivial.
Chen Lic0f3a152015-07-22 05:26:29 +0000996 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
997 return false; // Can't handle this.
998
Sanjay Patel41f3d952015-08-11 21:11:56 +0000999 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1000 nullptr);
Chen Lic0f3a152015-07-22 05:26:29 +00001001 ++NumSwitches;
1002 return true;
1003 }
1004 return false;
1005}
1006
Sanjay Patel956e29c2015-08-11 21:24:04 +00001007/// Split all of the edges from inside the loop to their exit blocks.
1008/// Update the appropriate Phi nodes as we do so.
Andrew Trick4104ed92012-04-10 05:14:37 +00001009void LoopUnswitch::SplitExitEdges(Loop *L,
Craig Topperb94011f2013-07-14 04:42:23 +00001010 const SmallVectorImpl<BasicBlock *> &ExitBlocks){
Devang Patela69f9872007-10-05 22:29:34 +00001011
Chris Lattnered7a67b2006-02-10 01:24:09 +00001012 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001013 BasicBlock *ExitBlock = ExitBlocks[i];
Dan Gohman3ddbc242009-09-08 15:45:00 +00001014 SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1015 pred_end(ExitBlock));
Bill Wendling90f90da2011-09-27 00:59:31 +00001016
Nick Lewycky61158242011-06-03 06:27:15 +00001017 // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1018 // general, if we call it on all predecessors of all exits then it does.
Chandler Carruth96ada252015-07-22 09:52:54 +00001019 SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI,
Philip Reames9198b332015-01-28 23:06:47 +00001020 /*PreserveLCSSA*/ true);
Chris Lattnered7a67b2006-02-10 01:24:09 +00001021 }
Devang Patele192e3252007-10-03 21:16:08 +00001022}
1023
Sanjay Patel956e29c2015-08-11 21:24:04 +00001024/// We determined that the loop is profitable to unswitch when LIC equal Val.
1025/// Split it into loop versions and test the condition outside of either loop.
1026/// Return the loops created as Out1/Out2.
Andrew Trick4442bfe2012-04-10 05:14:42 +00001027void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
Weiming Zhaof1abad52015-06-23 05:31:09 +00001028 Loop *L, TerminatorInst *TI) {
Devang Patele149d4e2008-07-02 01:18:13 +00001029 Function *F = loopHeader->getParent();
David Greened9c355d2010-01-05 01:27:04 +00001030 DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001031 << loopHeader->getName() << " [" << L->getBlocks().size()
1032 << " blocks] in Function " << F->getName()
1033 << " when '" << *Val << "' == " << *LIC << "\n");
Devang Patele192e3252007-10-03 21:16:08 +00001034
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001035 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1036 SEWP->getSE().forgetLoop(L);
Cameron Zwarich99de19b2011-02-11 06:08:28 +00001037
Devang Pateled50fb52008-07-02 01:44:29 +00001038 LoopBlocks.clear();
1039 NewBlocks.clear();
Devang Patele192e3252007-10-03 21:16:08 +00001040
1041 // First step, split the preheader and exit blocks, and add these blocks to
1042 // the LoopBlocks list.
Chandler Carruthd4500562015-01-19 12:36:53 +00001043 BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
Devang Patele192e3252007-10-03 21:16:08 +00001044 LoopBlocks.push_back(NewPreheader);
1045
1046 // We want the loop to come after the preheader, but before the exit blocks.
1047 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
1048
1049 SmallVector<BasicBlock*, 8> ExitBlocks;
1050 L->getUniqueExitBlocks(ExitBlocks);
1051
1052 // Split all of the edges from inside the loop to their exit blocks. Update
1053 // the appropriate Phi nodes as we do so.
Devang Pateleb611dd2008-07-03 17:37:52 +00001054 SplitExitEdges(L, ExitBlocks);
Devang Patele192e3252007-10-03 21:16:08 +00001055
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001056 // The exit blocks may have been changed due to edge splitting, recompute.
1057 ExitBlocks.clear();
Devang Patelf489d0f2006-08-29 22:29:16 +00001058 L->getUniqueExitBlocks(ExitBlocks);
1059
Chris Lattnerfe4151e2006-02-10 23:16:39 +00001060 // Add exit blocks to the loop blocks.
1061 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf48f7772004-04-19 18:07:02 +00001062
1063 // Next step, clone all of the basic blocks that make up the loop (including
1064 // the loop preheader and exit blocks), keeping track of the mapping between
1065 // the instructions and blocks.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001066 NewBlocks.reserve(LoopBlocks.size());
Rafael Espindola229e38f2010-10-13 01:36:30 +00001067 ValueToValueMapTy VMap;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001068 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001069 BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
Andrew Trick4104ed92012-04-10 05:14:37 +00001070
Evan Chengba930442010-04-05 21:16:25 +00001071 NewBlocks.push_back(NewBB);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001072 VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
Evan Chengba930442010-04-05 21:16:25 +00001073 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001074 }
1075
1076 // Splice the newly inserted blocks into the function right before the
1077 // original preheader.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001078 F->getBasicBlockList().splice(NewPreheader->getIterator(),
1079 F->getBasicBlockList(),
1080 NewBlocks[0]->getIterator(), F->end());
Chris Lattnerf48f7772004-04-19 18:07:02 +00001081
1082 // Now we create the new Loop object for the versioned loop.
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001083 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001084
1085 // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1086 // Probably clone more loop-unswitch related loop properties.
1087 BranchesInfo.cloneData(NewLoop, L, VMap);
1088
Chris Lattnerf1b15162006-02-10 23:26:14 +00001089 Loop *ParentLoop = L->getParentLoop();
1090 if (ParentLoop) {
Chris Lattnerf48f7772004-04-19 18:07:02 +00001091 // Make sure to add the cloned preheader and exit blocks to the parent loop
1092 // as well.
Chandler Carruth691addc2015-01-18 01:25:51 +00001093 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
Chris Lattnerf1b15162006-02-10 23:26:14 +00001094 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001095
Chris Lattnerf1b15162006-02-10 23:26:14 +00001096 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001097 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
Chris Lattner8e44ff52006-02-18 00:55:32 +00001098 // The new exit block should be in the same loop as the old one.
1099 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
Chandler Carruth691addc2015-01-18 01:25:51 +00001100 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Andrew Trick4104ed92012-04-10 05:14:37 +00001101
Chris Lattnerf1b15162006-02-10 23:26:14 +00001102 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1103 "Exit block should have been split to have one successor!");
1104 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Devang Pateleb611dd2008-07-03 17:37:52 +00001105
Chris Lattnerf1b15162006-02-10 23:26:14 +00001106 // If the successor of the exit block had PHI nodes, add an entry for
1107 // NewExit.
Jakub Staszak27da1232013-08-06 17:03:42 +00001108 for (BasicBlock::iterator I = ExitSucc->begin();
1109 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerf1b15162006-02-10 23:26:14 +00001110 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
Rafael Espindola229e38f2010-10-13 01:36:30 +00001111 ValueToValueMapTy::iterator It = VMap.find(V);
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001112 if (It != VMap.end()) V = It->second;
Chris Lattnerf1b15162006-02-10 23:26:14 +00001113 PN->addIncoming(V, NewExit);
1114 }
Bill Wendling90f90da2011-09-27 00:59:31 +00001115
1116 if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
Jakub Staszak27da1232013-08-06 17:03:42 +00001117 PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001118 &*ExitSucc->getFirstInsertionPt());
Bill Wendling90f90da2011-09-27 00:59:31 +00001119
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001120 for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
1121 I != E; ++I) {
1122 BasicBlock *BB = *I;
Bill Wendling90f90da2011-09-27 00:59:31 +00001123 LandingPadInst *LPI = BB->getLandingPadInst();
1124 LPI->replaceAllUsesWith(PN);
1125 PN->addIncoming(LPI, BB);
1126 }
1127 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001128 }
1129
1130 // Rewrite the code to refer to itself.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001131 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1132 for (Instruction &I : *NewBlocks[i]) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001133 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001134 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001135 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1136 if (II->getIntrinsicID() == Intrinsic::assume)
1137 AC->registerAssumption(II);
1138 }
1139 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001140
Chris Lattnerf48f7772004-04-19 18:07:02 +00001141 // Rewrite the original preheader to select between versions of the loop.
Devang Patele149d4e2008-07-02 01:18:13 +00001142 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001143 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattnerf48f7772004-04-19 18:07:02 +00001144 "Preheader splitting did not work correctly!");
Chris Lattnerf48f7772004-04-19 18:07:02 +00001145
Chris Lattnerb0cbe712006-02-15 00:07:43 +00001146 // Emit the new branch that selects between the two versions of this loop.
Weiming Zhaof1abad52015-06-23 05:31:09 +00001147 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1148 TI);
Devang Pateld4911982007-07-31 08:03:26 +00001149 LPM->deleteSimpleAnalysisValue(OldBR, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001150 OldBR->eraseFromParent();
Devang Patela8823282007-08-02 15:25:57 +00001151
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001152 LoopProcessWorklist.push_back(NewLoop);
Devang Patel7d165e12007-07-30 23:07:10 +00001153 redoLoop = true;
Chris Lattnerf48f7772004-04-19 18:07:02 +00001154
Chris Lattner5814d9d92010-04-20 05:09:16 +00001155 // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
1156 // deletes the instruction (for example by simplifying a PHI that feeds into
1157 // the condition that we're unswitching on), we don't rewrite the second
1158 // iteration.
1159 WeakVH LICHandle(LIC);
Andrew Trick4104ed92012-04-10 05:14:37 +00001160
Chris Lattnerf48f7772004-04-19 18:07:02 +00001161 // Now we rewrite the original code to know that the condition is true and the
1162 // new code to know that the condition is false.
Evan Chengba930442010-04-05 21:16:25 +00001163 RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
Devang Pateleb611dd2008-07-03 17:37:52 +00001164
Chris Lattner5814d9d92010-04-20 05:09:16 +00001165 // It's possible that simplifying one loop could cause the other to be
1166 // changed to another value or a constant. If its a constant, don't simplify
1167 // it.
1168 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1169 LICHandle && !isa<Constant>(LICHandle))
1170 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
Chris Lattnerf48f7772004-04-19 18:07:02 +00001171}
1172
Sanjay Patel956e29c2015-08-11 21:24:04 +00001173/// Remove all instances of I from the worklist vector specified.
Andrew Trick4104ed92012-04-10 05:14:37 +00001174static void RemoveFromWorklist(Instruction *I,
Chris Lattner6fd13622006-02-17 00:31:07 +00001175 std::vector<Instruction*> &Worklist) {
Jakub Staszak8f46e912012-10-16 19:52:32 +00001176
1177 Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1178 Worklist.end());
Chris Lattner6fd13622006-02-17 00:31:07 +00001179}
1180
Sanjay Patel956e29c2015-08-11 21:24:04 +00001181/// When we find that I really equals V, remove I from the
Chris Lattner6fd13622006-02-17 00:31:07 +00001182/// program, replacing all uses with V and update the worklist.
Andrew Trick4104ed92012-04-10 05:14:37 +00001183static void ReplaceUsesOfWith(Instruction *I, Value *V,
Devang Pateld4911982007-07-31 08:03:26 +00001184 std::vector<Instruction*> &Worklist,
1185 Loop *L, LPPassManager *LPM) {
David Greened9c355d2010-01-05 01:27:04 +00001186 DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
Chris Lattner6fd13622006-02-17 00:31:07 +00001187
1188 // Add uses to the worklist, which may be dead now.
1189 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1190 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1191 Worklist.push_back(Use);
1192
1193 // Add users to the worklist which may be simplified now.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001194 for (User *U : I->users())
1195 Worklist.push_back(cast<Instruction>(U));
Devang Pateld4911982007-07-31 08:03:26 +00001196 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001197 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001198 I->replaceAllUsesWith(V);
1199 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001200 ++NumSimplify;
1201}
1202
Sanjay Patel956e29c2015-08-11 21:24:04 +00001203/// We know either that the value LIC has the value specified by Val in the
1204/// specified loop, or we know it does NOT have that value.
1205/// Rewrite any uses of LIC or of properties correlated to it.
Chris Lattnerf48f7772004-04-19 18:07:02 +00001206void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerfbadd7e2006-02-11 00:43:37 +00001207 Constant *Val,
1208 bool IsEqual) {
Chris Lattnered7a67b2006-02-10 01:24:09 +00001209 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Andrew Trick4104ed92012-04-10 05:14:37 +00001210
Chris Lattnerf48f7772004-04-19 18:07:02 +00001211 // FIXME: Support correlated properties, like:
1212 // for (...)
1213 // if (li1 < li2)
1214 // ...
1215 // if (li1 > li2)
1216 // ...
Andrew Trick4104ed92012-04-10 05:14:37 +00001217
Chris Lattner6e263152006-02-10 02:30:37 +00001218 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
1219 // selects, switches.
Chris Lattner6fd13622006-02-17 00:31:07 +00001220 std::vector<Instruction*> Worklist;
Owen Anderson47db9412009-07-22 00:24:57 +00001221 LLVMContext &Context = Val->getContext();
1222
Chris Lattner6fd13622006-02-17 00:31:07 +00001223 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1224 // in the loop with the appropriate one directly.
Owen Anderson55f1c092009-08-13 21:58:54 +00001225 if (IsEqual || (isa<ConstantInt>(Val) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +00001226 Val->getType()->isIntegerTy(1))) {
Chris Lattner8a5a3242006-02-22 06:37:14 +00001227 Value *Replacement;
1228 if (IsEqual)
1229 Replacement = Val;
1230 else
Andrew Trick4104ed92012-04-10 05:14:37 +00001231 Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
Reid Spencercddc9df2007-01-12 04:24:46 +00001232 !cast<ConstantInt>(Val)->getZExtValue());
Andrew Trick4104ed92012-04-10 05:14:37 +00001233
Chandler Carruthcdf47882014-03-09 03:16:01 +00001234 for (User *U : LIC->users()) {
1235 Instruction *UI = dyn_cast<Instruction>(U);
1236 if (!UI || !L->contains(UI))
Evan Cheng1b55f562011-05-24 23:12:57 +00001237 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001238 Worklist.push_back(UI);
Evan Cheng1b55f562011-05-24 23:12:57 +00001239 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001240
Benjamin Kramer135f7352016-06-26 12:28:59 +00001241 for (Instruction *UI : Worklist)
1242 UI->replaceUsesOfWith(LIC, Replacement);
Andrew Trick4104ed92012-04-10 05:14:37 +00001243
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001244 SimplifyCode(Worklist, L);
1245 return;
1246 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001247
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001248 // Otherwise, we don't know the precise value of LIC, but we do know that it
1249 // is certainly NOT "Val". As such, simplify any uses in the loop that we
1250 // can. This case occurs when we unswitch switch statements.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001251 for (User *U : LIC->users()) {
1252 Instruction *UI = dyn_cast<Instruction>(U);
1253 if (!UI || !L->contains(UI))
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001254 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001255
Chandler Carruthcdf47882014-03-09 03:16:01 +00001256 Worklist.push_back(UI);
Chris Lattner6fd13622006-02-17 00:31:07 +00001257
Andrew Trick4104ed92012-04-10 05:14:37 +00001258 // TODO: We could do other simplifications, for example, turning
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001259 // 'icmp eq LIC, Val' -> false.
1260
1261 // If we know that LIC is not Val, use this info to simplify code.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001262 SwitchInst *SI = dyn_cast<SwitchInst>(UI);
Craig Topperf40110f2014-04-25 05:29:35 +00001263 if (!SI || !isa<ConstantInt>(Val)) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001264
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001265 SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001266 // Default case is live for multiple values.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001267 if (DeadCase == SI->case_default()) continue;
Andrew Trick4104ed92012-04-10 05:14:37 +00001268
1269 // Found a dead case value. Don't remove PHI nodes in the
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001270 // successor if they become single-entry, those PHI nodes may
1271 // be in the Users list.
Nick Lewycky61158242011-06-03 06:27:15 +00001272
Evan Cheng1b55f562011-05-24 23:12:57 +00001273 BasicBlock *Switch = SI->getParent();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001274 BasicBlock *SISucc = DeadCase.getCaseSuccessor();
Evan Cheng1b55f562011-05-24 23:12:57 +00001275 BasicBlock *Latch = L->getLoopLatch();
Andrew Trick4104ed92012-04-10 05:14:37 +00001276
Stepan Dyatkovskiycb2adbac2012-01-15 09:44:07 +00001277 BranchesInfo.setUnswitched(SI, Val);
Andrew Trick4104ed92012-04-10 05:14:37 +00001278
Nick Lewycky61158242011-06-03 06:27:15 +00001279 if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
Evan Cheng9605a692011-05-25 18:17:13 +00001280 // If the DeadCase successor dominates the loop latch, then the
1281 // transformation isn't safe since it will delete the sole predecessor edge
1282 // to the latch.
1283 if (Latch && DT->dominates(SISucc, Latch))
1284 continue;
Evan Cheng1b55f562011-05-24 23:12:57 +00001285
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001286 // FIXME: This is a hack. We need to keep the successor around
1287 // and hooked up so as to preserve the loop structure, because
1288 // trying to update it is complicated. So instead we preserve the
1289 // loop structure and put the block on a dead code path.
Chandler Carruthd4500562015-01-19 12:36:53 +00001290 SplitEdge(Switch, SISucc, DT, LI);
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001291 // Compute the successors instead of relying on the return value
1292 // of SplitEdge, since it may have split the switch successor
1293 // after PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001294 BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001295 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1296 // Create an "unreachable" destination.
1297 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1298 Switch->getParent(),
1299 OldSISucc);
1300 new UnreachableInst(Context, Abort);
1301 // Force the new case destination to branch to the "unreachable"
1302 // block while maintaining a (dead) CFG edge to the old block.
1303 NewSISucc->getTerminator()->eraseFromParent();
1304 BranchInst::Create(Abort, OldSISucc,
1305 ConstantInt::getTrue(Context), NewSISucc);
1306 // Release the PHI operands for this edge.
1307 for (BasicBlock::iterator II = NewSISucc->begin();
1308 PHINode *PN = dyn_cast<PHINode>(II); ++II)
1309 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1310 UndefValue::get(PN->getType()));
1311 // Tell the domtree about the new block. We don't fully update the
1312 // domtree here -- instead we force it to do a full recomputation
1313 // after the pass is complete -- but we do need to inform it of
1314 // new blocks.
Michael Zolotukhin9f3aea62015-09-22 00:22:47 +00001315 DT->addNewBlock(Abort, NewSISucc);
Chris Lattner6fd13622006-02-17 00:31:07 +00001316 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001317
Devang Pateld4911982007-07-31 08:03:26 +00001318 SimplifyCode(Worklist, L);
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001319}
1320
Sanjay Patel956e29c2015-08-11 21:24:04 +00001321/// Now that we have simplified some instructions in the loop, walk over it and
1322/// constant prop, dce, and fold control flow where possible. Note that this is
1323/// effectively a very simple loop-structure-aware optimizer. During processing
1324/// of this loop, L could very well be deleted, so it must not be used.
Chris Lattnerc2e3a7a2006-02-18 07:57:38 +00001325///
1326/// FIXME: When the loop optimizer is more mature, separate this out to a new
1327/// pass.
1328///
Devang Pateld4911982007-07-31 08:03:26 +00001329void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001330 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Chris Lattner6fd13622006-02-17 00:31:07 +00001331 while (!Worklist.empty()) {
1332 Instruction *I = Worklist.back();
1333 Worklist.pop_back();
Duncan Sandsbb2cd022010-11-23 20:24:21 +00001334
Chris Lattner6fd13622006-02-17 00:31:07 +00001335 // Simple DCE.
1336 if (isInstructionTriviallyDead(I)) {
David Greened9c355d2010-01-05 01:27:04 +00001337 DEBUG(dbgs() << "Remove dead instruction '" << *I);
Andrew Trick4104ed92012-04-10 05:14:37 +00001338
Chris Lattner6fd13622006-02-17 00:31:07 +00001339 // Add uses to the worklist, which may be dead now.
1340 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1341 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1342 Worklist.push_back(Use);
Devang Pateld4911982007-07-31 08:03:26 +00001343 LPM->deleteSimpleAnalysisValue(I, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001344 RemoveFromWorklist(I, Worklist);
Devang Patel83cc3f82007-09-20 23:45:50 +00001345 I->eraseFromParent();
Chris Lattner6fd13622006-02-17 00:31:07 +00001346 ++NumSimplify;
1347 continue;
1348 }
Duncan Sandsaef146b2010-11-18 19:59:41 +00001349
Chris Lattner66e809a2010-04-20 05:33:18 +00001350 // See if instruction simplification can hack this up. This is common for
1351 // things like "select false, X, Y" after unswitching made the condition be
Peter Collingbourne9a03c732012-05-20 01:32:09 +00001352 // 'false'. TODO: update the domtree properly so we can pass it here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001353 if (Value *V = SimplifyInstruction(I, DL))
Duncan Sandsaef146b2010-11-18 19:59:41 +00001354 if (LI->replacementPreservesLCSSAForm(I, V)) {
1355 ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1356 continue;
1357 }
1358
Chris Lattner6fd13622006-02-17 00:31:07 +00001359 // Special case hacks that appear commonly in unswitched code.
Chris Lattner66e809a2010-04-20 05:33:18 +00001360 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Chris Lattner6fd13622006-02-17 00:31:07 +00001361 if (BI->isUnconditional()) {
1362 // If BI's parent is the only pred of the successor, fold the two blocks
1363 // together.
1364 BasicBlock *Pred = BI->getParent();
1365 BasicBlock *Succ = BI->getSuccessor(0);
1366 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1367 if (!SinglePred) continue; // Nothing to do.
1368 assert(SinglePred == Pred && "CFG broken");
1369
Andrew Trick4104ed92012-04-10 05:14:37 +00001370 DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001371 << Succ->getName() << "\n");
Andrew Trick4104ed92012-04-10 05:14:37 +00001372
Chris Lattner6fd13622006-02-17 00:31:07 +00001373 // Resolve any single entry PHI nodes in Succ.
1374 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
Devang Pateld4911982007-07-31 08:03:26 +00001375 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
Andrew Trick4104ed92012-04-10 05:14:37 +00001376
Jay Foad61ea0e42011-06-23 09:09:15 +00001377 // If Succ has any successors with PHI nodes, update them to have
1378 // entries coming from Pred instead of Succ.
1379 Succ->replaceAllUsesWith(Pred);
Andrew Trick4104ed92012-04-10 05:14:37 +00001380
Chris Lattner6fd13622006-02-17 00:31:07 +00001381 // Move all of the successor contents from Succ to Pred.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001382 Pred->getInstList().splice(BI->getIterator(), Succ->getInstList(),
1383 Succ->begin(), Succ->end());
Devang Pateld4911982007-07-31 08:03:26 +00001384 LPM->deleteSimpleAnalysisValue(BI, L);
Chris Lattner6fd13622006-02-17 00:31:07 +00001385 RemoveFromWorklist(BI, Worklist);
Xin Tong3caaa362017-01-06 21:49:08 +00001386 BI->eraseFromParent();
Andrew Trick4104ed92012-04-10 05:14:37 +00001387
Chris Lattner6fd13622006-02-17 00:31:07 +00001388 // Remove Succ from the loop tree.
1389 LI->removeBlock(Succ);
Devang Pateld4911982007-07-31 08:03:26 +00001390 LPM->deleteSimpleAnalysisValue(Succ, L);
Devang Patel83cc3f82007-09-20 23:45:50 +00001391 Succ->eraseFromParent();
Chris Lattner29f771b2006-02-18 01:27:45 +00001392 ++NumSimplify;
Chris Lattner66e809a2010-04-20 05:33:18 +00001393 continue;
Chris Lattnerc832c1b2010-04-05 21:18:32 +00001394 }
Andrew Trick4104ed92012-04-10 05:14:37 +00001395
Chris Lattner66e809a2010-04-20 05:33:18 +00001396 continue;
Chris Lattner6fd13622006-02-17 00:31:07 +00001397 }
1398 }
Chris Lattnerf48f7772004-04-19 18:07:02 +00001399}