blob: 6bbd571894d907596b8233aa0e5b2bf87d61541c [file] [log] [blame]
Hal Finkel99f823f2012-06-08 15:38:21 +00001//===-- PPCCTRLoops.cpp - Identify and generate CTR loops -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass identifies loops where we can generate the PPC branch instructions
11// that decrement and test the count register (CTR) (bdnz and friends).
Hal Finkel99f823f2012-06-08 15:38:21 +000012//
13// The pattern that defines the induction variable can changed depending on
14// prior optimizations. For example, the IndVarSimplify phase run by 'opt'
15// normalizes induction variables, and the Loop Strength Reduction pass
16// run by 'llc' may also make changes to the induction variable.
Hal Finkel99f823f2012-06-08 15:38:21 +000017//
18// Criteria for CTR loops:
19// - Countable loops (w/ ind. var for a trip count)
Hal Finkel99f823f2012-06-08 15:38:21 +000020// - Try inner-most loops first
21// - No nested CTR loops.
22// - No function calls in loops.
23//
Hal Finkel99f823f2012-06-08 15:38:21 +000024//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "ctrloops"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000027
28#include "llvm/Transforms/Scalar.h"
Hal Finkel99f823f2012-06-08 15:38:21 +000029#include "llvm/ADT/Statistic.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Analysis/LoopInfo.h"
33#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000034#include "llvm/IR/Constants.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000035#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/IntrinsicInst.h"
38#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000039#include "llvm/PassSupport.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000040#include "llvm/Support/CommandLine.h"
Hal Finkel99f823f2012-06-08 15:38:21 +000041#include "llvm/Support/Debug.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000042#include "llvm/Support/ValueHandle.h"
Hal Finkel99f823f2012-06-08 15:38:21 +000043#include "llvm/Support/raw_ostream.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
46#include "llvm/Target/TargetLibraryInfo.h"
47#include "PPCTargetMachine.h"
48#include "PPC.h"
49
Hal Finkel99f823f2012-06-08 15:38:21 +000050#include <algorithm>
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000051#include <vector>
Hal Finkel99f823f2012-06-08 15:38:21 +000052
53using namespace llvm;
54
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000055#ifndef NDEBUG
56static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
57#endif
58
Hal Finkel99f823f2012-06-08 15:38:21 +000059STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
60
Krzysztof Parzyszek96848df2013-02-13 17:40:07 +000061namespace llvm {
62 void initializePPCCTRLoopsPass(PassRegistry&);
63}
64
Hal Finkel99f823f2012-06-08 15:38:21 +000065namespace {
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000066 struct PPCCTRLoops : public FunctionPass {
67
68#ifndef NDEBUG
69 static int Counter;
70#endif
Hal Finkel99f823f2012-06-08 15:38:21 +000071
72 public:
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000073 static char ID;
Hal Finkel99f823f2012-06-08 15:38:21 +000074
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000075 PPCCTRLoops() : FunctionPass(ID), TM(0) {
76 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
77 }
78 PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
Krzysztof Parzyszek96848df2013-02-13 17:40:07 +000079 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
80 }
Hal Finkel99f823f2012-06-08 15:38:21 +000081
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000082 virtual bool runOnFunction(Function &F);
Hal Finkel99f823f2012-06-08 15:38:21 +000083
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000085 AU.addRequired<LoopInfo>();
86 AU.addPreserved<LoopInfo>();
87 AU.addRequired<DominatorTree>();
88 AU.addPreserved<DominatorTree>();
89 AU.addRequired<ScalarEvolution>();
Hal Finkel99f823f2012-06-08 15:38:21 +000090 }
91
92 private:
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000093 // FIXME: Copied from LoopSimplify.
94 BasicBlock *InsertPreheaderForLoop(Loop *L);
95 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
96 SmallVectorImpl<BasicBlock*> &SplitPreds,
97 Loop *L);
Hal Finkel99f823f2012-06-08 15:38:21 +000098
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000099 bool convertToCTRLoop(Loop *L);
100 private:
101 PPCTargetMachine *TM;
102 LoopInfo *LI;
103 ScalarEvolution *SE;
104 DataLayout *TD;
105 DominatorTree *DT;
106 const TargetLibraryInfo *LibInfo;
Hal Finkel99f823f2012-06-08 15:38:21 +0000107 };
108
109 char PPCCTRLoops::ID = 0;
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000110#ifndef NDEBUG
111 int PPCCTRLoops::Counter = 0;
112#endif
Hal Finkel99f823f2012-06-08 15:38:21 +0000113} // end anonymous namespace
114
Krzysztof Parzyszek96848df2013-02-13 17:40:07 +0000115INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
116 false, false)
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000117INITIALIZE_PASS_DEPENDENCY(DominatorTree)
118INITIALIZE_PASS_DEPENDENCY(LoopInfo)
119INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Krzysztof Parzyszek96848df2013-02-13 17:40:07 +0000120INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
121 false, false)
Hal Finkel99f823f2012-06-08 15:38:21 +0000122
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000123FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
124 return new PPCCTRLoops(TM);
Hal Finkel99f823f2012-06-08 15:38:21 +0000125}
126
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000127bool PPCCTRLoops::runOnFunction(Function &F) {
128 LI = &getAnalysis<LoopInfo>();
129 SE = &getAnalysis<ScalarEvolution>();
130 DT = &getAnalysis<DominatorTree>();
131 TD = getAnalysisIfAvailable<DataLayout>();
132 LibInfo = getAnalysisIfAvailable<TargetLibraryInfo>();
Hal Finkel99f823f2012-06-08 15:38:21 +0000133
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000134 bool MadeChange = false;
Hal Finkel99f823f2012-06-08 15:38:21 +0000135
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000136 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
Hal Finkel99f823f2012-06-08 15:38:21 +0000137 I != E; ++I) {
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000138 Loop *L = *I;
139 if (!L->getParentLoop())
140 MadeChange |= convertToCTRLoop(L);
Hal Finkel99f823f2012-06-08 15:38:21 +0000141 }
142
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000143 return MadeChange;
Hal Finkel99f823f2012-06-08 15:38:21 +0000144}
145
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000146bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
147 bool MadeChange = false;
Hal Finkel99f823f2012-06-08 15:38:21 +0000148
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000149 Triple TT = Triple(L->getHeader()->getParent()->getParent()->
150 getTargetTriple());
151 if (!TT.isArch32Bit() && !TT.isArch64Bit())
152 return MadeChange; // Unknown arch. type.
Hal Finkel99f823f2012-06-08 15:38:21 +0000153
Hal Finkel99f823f2012-06-08 15:38:21 +0000154 // Process nested loops first.
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000155 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
156 MadeChange |= convertToCTRLoop(*I);
Hal Finkel99f823f2012-06-08 15:38:21 +0000157 }
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000158
Hal Finkel99f823f2012-06-08 15:38:21 +0000159 // If a nested loop has been converted, then we can't convert this loop.
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000160 if (MadeChange)
161 return MadeChange;
Hal Finkel99f823f2012-06-08 15:38:21 +0000162
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000163#ifndef NDEBUG
164 // Stop trying after reaching the limit (if any).
165 int Limit = CTRLoopLimit;
166 if (Limit >= 0) {
167 if (Counter >= CTRLoopLimit)
Hal Finkel9887ec32013-03-18 17:40:44 +0000168 return false;
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000169 Counter++;
Hal Finkel9887ec32013-03-18 17:40:44 +0000170 }
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000171#endif
Hal Finkel9887ec32013-03-18 17:40:44 +0000172
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000173 // We don't want to spill/restore the counter register, and so we don't
174 // want to use the counter register if the loop contains calls.
175 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
176 I != IE; ++I) {
177 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
178 J != JE; ++J) {
179 if (CallInst *CI = dyn_cast<CallInst>(J)) {
180 if (!TM)
181 return MadeChange;
182 const TargetLowering *TLI = TM->getTargetLowering();
Hal Finkel99f823f2012-06-08 15:38:21 +0000183
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000184 if (Function *F = CI->getCalledFunction()) {
185 // Most intrinsics don't become function calls, but some might.
186 // sin, cos, exp and log are always calls.
187 unsigned Opcode;
188 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
189 switch (F->getIntrinsicID()) {
190 default: continue;
Hal Finkelf1e7ea42013-05-15 22:20:24 +0000191
192// VisualStudio defines setjmp as _setjmp
193#if defined(_MSC_VER) && defined(setjmp) && \
194 !defined(setjmp_undefined_for_msvc)
195# pragma push_macro("setjmp")
196# undef setjmp
197# define setjmp_undefined_for_msvc
198#endif
199
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000200 case Intrinsic::setjmp:
Hal Finkelf1e7ea42013-05-15 22:20:24 +0000201
202#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
203 // let's return it to _setjmp state
204# pragma pop_macro("setjmp")
205# undef setjmp_undefined_for_msvc
206#endif
207
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000208 case Intrinsic::longjmp:
209 case Intrinsic::memcpy:
210 case Intrinsic::memmove:
211 case Intrinsic::memset:
212 case Intrinsic::powi:
213 case Intrinsic::log:
214 case Intrinsic::log2:
215 case Intrinsic::log10:
216 case Intrinsic::exp:
217 case Intrinsic::exp2:
218 case Intrinsic::pow:
219 case Intrinsic::sin:
220 case Intrinsic::cos:
221 return MadeChange;
222 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
223 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
224 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
225 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
226 case Intrinsic::rint: Opcode = ISD::FRINT; break;
227 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
228 }
229 }
Hal Finkel99f823f2012-06-08 15:38:21 +0000230
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000231 // PowerPC does not use [US]DIVREM or other library calls for
232 // operations on regular types which are not otherwise library calls
233 // (i.e. soft float or atomics). If adapting for targets that do,
234 // additional care is required here.
Hal Finkel99f823f2012-06-08 15:38:21 +0000235
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000236 LibFunc::Func Func;
237 if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
238 LibInfo->getLibFunc(F->getName(), Func) &&
239 LibInfo->hasOptimizedCodeGen(Func)) {
240 // Non-read-only functions are never treated as intrinsics.
241 if (!CI->onlyReadsMemory())
242 return MadeChange;
243
244 // Conversion happens only for FP calls.
245 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
246 return MadeChange;
247
248 switch (Func) {
249 default: return MadeChange;
250 case LibFunc::copysign:
251 case LibFunc::copysignf:
252 case LibFunc::copysignl:
253 continue; // ISD::FCOPYSIGN is never a library call.
254 case LibFunc::fabs:
255 case LibFunc::fabsf:
256 case LibFunc::fabsl:
257 continue; // ISD::FABS is never a library call.
258 case LibFunc::sqrt:
259 case LibFunc::sqrtf:
260 case LibFunc::sqrtl:
261 Opcode = ISD::FSQRT; break;
262 case LibFunc::floor:
263 case LibFunc::floorf:
264 case LibFunc::floorl:
265 Opcode = ISD::FFLOOR; break;
266 case LibFunc::nearbyint:
267 case LibFunc::nearbyintf:
268 case LibFunc::nearbyintl:
269 Opcode = ISD::FNEARBYINT; break;
270 case LibFunc::ceil:
271 case LibFunc::ceilf:
272 case LibFunc::ceill:
273 Opcode = ISD::FCEIL; break;
274 case LibFunc::rint:
275 case LibFunc::rintf:
276 case LibFunc::rintl:
277 Opcode = ISD::FRINT; break;
278 case LibFunc::trunc:
279 case LibFunc::truncf:
280 case LibFunc::truncl:
281 Opcode = ISD::FTRUNC; break;
282 }
283
284 MVT VTy =
285 TLI->getSimpleValueType(CI->getArgOperand(0)->getType(), true);
286 if (VTy == MVT::Other)
287 return MadeChange;
288
289 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
290 continue;
291 else if (VTy.isVector() &&
292 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
293 continue;
294
295 return MadeChange;
296 }
297 }
298
299 return MadeChange;
300 } else if (isa<BinaryOperator>(J) &&
301 J->getType()->getScalarType()->isPPC_FP128Ty()) {
302 // Most operations on ppc_f128 values become calls.
303 return MadeChange;
304 } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
305 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
306 CastInst *CI = cast<CastInst>(J);
307 if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
Hal Finkel2a5e8c32013-05-16 16:52:41 +0000308 CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
309 (TT.isArch32Bit() &&
310 (CI->getSrcTy()->getScalarType()->isIntegerTy(64) ||
311 CI->getDestTy()->getScalarType()->isIntegerTy(64))
312 ))
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000313 return MadeChange;
314 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
315 // On PowerPC, indirect jumps use the counter register.
316 return MadeChange;
317 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
318 if (!TM)
319 return MadeChange;
320 const TargetLowering *TLI = TM->getTargetLowering();
321
322 if (TLI->supportJumpTables() &&
323 SI->getNumCases()+1 >= (unsigned) TLI->getMinimumJumpTableEntries())
324 return MadeChange;
325 }
Hal Finkel99f823f2012-06-08 15:38:21 +0000326 }
327 }
328
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000329 SmallVector<BasicBlock*, 4> ExitingBlocks;
330 L->getExitingBlocks(ExitingBlocks);
Hal Finkel99f823f2012-06-08 15:38:21 +0000331
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000332 BasicBlock *CountedExitBlock = 0;
333 const SCEV *ExitCount = 0;
334 BranchInst *CountedExitBranch = 0;
335 for (SmallVector<BasicBlock*, 4>::iterator I = ExitingBlocks.begin(),
336 IE = ExitingBlocks.end(); I != IE; ++I) {
337 const SCEV *EC = SE->getExitCount(L, *I);
338 DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
339 (*I)->getName() << ": " << *EC << "\n");
340 if (isa<SCEVCouldNotCompute>(EC))
341 continue;
342 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
343 if (ConstEC->getValue()->isZero())
344 continue;
345 } else if (!SE->isLoopInvariant(EC, L))
346 continue;
Hal Finkel99f823f2012-06-08 15:38:21 +0000347
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000348 // We now have a loop-invariant count of loop iterations (which is not the
349 // constant zero) for which we know that this loop will not exit via this
350 // exisiting block.
Hal Finkel2741d2c2012-06-16 20:34:07 +0000351
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000352 // We need to make sure that this block will run on every loop iteration.
353 // For this to be true, we must dominate all blocks with backedges. Such
354 // blocks are in-loop predecessors to the header block.
355 bool NotAlways = false;
356 for (pred_iterator PI = pred_begin(L->getHeader()),
357 PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
358 if (!L->contains(*PI))
359 continue;
360
361 if (!DT->dominates(*I, *PI)) {
362 NotAlways = true;
363 break;
364 }
Hal Finkel99f823f2012-06-08 15:38:21 +0000365 }
Hal Finkel99f823f2012-06-08 15:38:21 +0000366
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000367 if (NotAlways)
368 continue;
Hal Finkel99f823f2012-06-08 15:38:21 +0000369
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000370 // Make sure this blocks ends with a conditional branch.
371 Instruction *TI = (*I)->getTerminator();
372 if (!TI)
373 continue;
374
375 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
376 if (!BI->isConditional())
377 continue;
378
379 CountedExitBranch = BI;
380 } else
381 continue;
382
383 // Note that this block may not be the loop latch block, even if the loop
384 // has a latch block.
385 CountedExitBlock = *I;
386 ExitCount = EC;
387 break;
Hal Finkel99f823f2012-06-08 15:38:21 +0000388 }
389
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000390 if (!CountedExitBlock)
391 return MadeChange;
Hal Finkel99f823f2012-06-08 15:38:21 +0000392
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000393 BasicBlock *Preheader = L->getLoopPreheader();
394 if (!Preheader)
395 Preheader = InsertPreheaderForLoop(L);
396 if (!Preheader)
397 return MadeChange;
Hal Finkel99f823f2012-06-08 15:38:21 +0000398
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000399 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
Hal Finkel99f823f2012-06-08 15:38:21 +0000400
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000401 // Insert the count into the preheader and replace the condition used by the
402 // selected branch.
403 MadeChange = true;
Hal Finkel99f823f2012-06-08 15:38:21 +0000404
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000405 SCEVExpander SCEVE(*SE, "loopcnt");
406 LLVMContext &C = SE->getContext();
407 Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(C) :
408 Type::getInt32Ty(C);
409 if (!ExitCount->getType()->isPointerTy() &&
410 ExitCount->getType() != CountType)
411 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
412 ExitCount = SE->getAddExpr(ExitCount,
413 SE->getConstant(CountType, 1));
414 Value *ECValue = SCEVE.expandCodeFor(ExitCount, CountType,
415 Preheader->getTerminator());
Hal Finkel99f823f2012-06-08 15:38:21 +0000416
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000417 IRBuilder<> CountBuilder(Preheader->getTerminator());
418 Module *M = Preheader->getParent()->getParent();
419 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
420 CountType);
421 CountBuilder.CreateCall(MTCTRFunc, ECValue);
Hal Finkel99f823f2012-06-08 15:38:21 +0000422
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000423 IRBuilder<> CondBuilder(CountedExitBranch);
424 Value *DecFunc =
425 Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
426 Value *NewCond = CondBuilder.CreateCall(DecFunc);
427 Value *OldCond = CountedExitBranch->getCondition();
428 CountedExitBranch->setCondition(NewCond);
429
430 // The false branch must exit the loop.
431 if (!L->contains(CountedExitBranch->getSuccessor(0)))
432 CountedExitBranch->swapSuccessors();
433
434 // The old condition may be dead now, and may have even created a dead PHI
435 // (the original induction variable).
436 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
437 DeleteDeadPHIs(CountedExitBlock);
Hal Finkel99f823f2012-06-08 15:38:21 +0000438
439 ++NumCTRLoops;
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000440 return MadeChange;
441}
442
443// FIXME: Copied from LoopSimplify.
444BasicBlock *PPCCTRLoops::InsertPreheaderForLoop(Loop *L) {
445 BasicBlock *Header = L->getHeader();
446
447 // Compute the set of predecessors of the loop that are not in the loop.
448 SmallVector<BasicBlock*, 8> OutsideBlocks;
449 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
450 PI != PE; ++PI) {
451 BasicBlock *P = *PI;
452 if (!L->contains(P)) { // Coming in from outside the loop?
453 // If the loop is branched to from an indirect branch, we won't
454 // be able to fully transform the loop, because it prohibits
455 // edge splitting.
456 if (isa<IndirectBrInst>(P->getTerminator())) return 0;
457
458 // Keep track of it.
459 OutsideBlocks.push_back(P);
460 }
461 }
462
463 // Split out the loop pre-header.
464 BasicBlock *PreheaderBB;
465 if (!Header->isLandingPad()) {
466 PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
467 this);
468 } else {
469 SmallVector<BasicBlock*, 2> NewBBs;
470 SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader",
471 ".split-lp", this, NewBBs);
472 PreheaderBB = NewBBs[0];
473 }
474
475 PreheaderBB->getTerminator()->setDebugLoc(
476 Header->getFirstNonPHI()->getDebugLoc());
477 DEBUG(dbgs() << "Creating pre-header "
478 << PreheaderBB->getName() << "\n");
479
480 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
481 // code layout too horribly.
482 PlaceSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
483
484 return PreheaderBB;
485}
486
487void PPCCTRLoops::PlaceSplitBlockCarefully(BasicBlock *NewBB,
488 SmallVectorImpl<BasicBlock*> &SplitPreds,
489 Loop *L) {
490 // Check to see if NewBB is already well placed.
491 Function::iterator BBI = NewBB; --BBI;
492 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
493 if (&*BBI == SplitPreds[i])
494 return;
495 }
496
497 // If it isn't already after an outside block, move it after one. This is
498 // always good as it makes the uncond branch from the outside block into a
499 // fall-through.
500
501 // Figure out *which* outside block to put this after. Prefer an outside
502 // block that neighbors a BB actually in the loop.
503 BasicBlock *FoundBB = 0;
504 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
505 Function::iterator BBI = SplitPreds[i];
506 if (++BBI != NewBB->getParent()->end() &&
507 L->contains(BBI)) {
508 FoundBB = SplitPreds[i];
509 break;
510 }
511 }
512
513 // If our heuristic for a *good* bb to place this after doesn't find
514 // anything, just pick something. It's likely better than leaving it within
515 // the loop.
516 if (!FoundBB)
517 FoundBB = SplitPreds[0];
518 NewBB->moveAfter(FoundBB);
Hal Finkel99f823f2012-06-08 15:38:21 +0000519}
520