blob: 770afbecbd37ec9e77e9b429f482c6a3a4b0c361 [file] [log] [blame]
Hal Finkel96c2d4d2012-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 Finkel96c2d4d2012-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 Finkel96c2d4d2012-06-08 15:38:21 +000017//
18// Criteria for CTR loops:
19// - Countable loops (w/ ind. var for a trip count)
Hal Finkel96c2d4d2012-06-08 15:38:21 +000020// - Try inner-most loops first
21// - No nested CTR loops.
22// - No function calls in loops.
23//
Hal Finkel96c2d4d2012-06-08 15:38:21 +000024//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "ctrloops"
Hal Finkel25c19922013-05-15 21:37:41 +000027
28#include "llvm/Transforms/Scalar.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000029#include "PPC.h"
30#include "PPCTargetMachine.h"
Hal Finkel25c19922013-05-15 21:37:41 +000031#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000032#include "llvm/ADT/Statistic.h"
Hal Finkel25c19922013-05-15 21:37:41 +000033#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Constants.h"
Hal Finkel25c19922013-05-15 21:37:41 +000036#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000037#include "llvm/IR/Dominators.h"
Hal Finkel2f474f02013-05-18 09:20:39 +000038#include "llvm/IR/InlineAsm.h"
Hal Finkel25c19922013-05-15 21:37:41 +000039#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
41#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/PassSupport.h"
Hal Finkel25c19922013-05-15 21:37:41 +000043#include "llvm/Support/CommandLine.h"
Hal Finkel96c2d4d2012-06-08 15:38:21 +000044#include "llvm/Support/Debug.h"
Hal Finkel25c19922013-05-15 21:37:41 +000045#include "llvm/Support/ValueHandle.h"
Hal Finkel96c2d4d2012-06-08 15:38:21 +000046#include "llvm/Support/raw_ostream.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000047#include "llvm/Target/TargetLibraryInfo.h"
Hal Finkel25c19922013-05-15 21:37:41 +000048#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Hal Finkela969df82013-05-20 20:46:30 +000050#include "llvm/Transforms/Utils/LoopUtils.h"
Hal Finkel25c19922013-05-15 21:37:41 +000051
Hal Finkel8ca38842013-05-20 16:08:17 +000052#ifndef NDEBUG
53#include "llvm/CodeGen/MachineDominators.h"
54#include "llvm/CodeGen/MachineFunction.h"
55#include "llvm/CodeGen/MachineFunctionPass.h"
56#include "llvm/CodeGen/MachineRegisterInfo.h"
57#endif
58
Hal Finkel96c2d4d2012-06-08 15:38:21 +000059#include <algorithm>
Hal Finkel25c19922013-05-15 21:37:41 +000060#include <vector>
Hal Finkel96c2d4d2012-06-08 15:38:21 +000061
62using namespace llvm;
63
Hal Finkel25c19922013-05-15 21:37:41 +000064#ifndef NDEBUG
65static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
66#endif
67
Hal Finkel96c2d4d2012-06-08 15:38:21 +000068STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
69
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000070namespace llvm {
71 void initializePPCCTRLoopsPass(PassRegistry&);
Hal Finkel8ca38842013-05-20 16:08:17 +000072#ifndef NDEBUG
73 void initializePPCCTRLoopsVerifyPass(PassRegistry&);
74#endif
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000075}
76
Hal Finkel96c2d4d2012-06-08 15:38:21 +000077namespace {
Hal Finkel25c19922013-05-15 21:37:41 +000078 struct PPCCTRLoops : public FunctionPass {
79
80#ifndef NDEBUG
81 static int Counter;
82#endif
Hal Finkel96c2d4d2012-06-08 15:38:21 +000083
84 public:
Hal Finkel25c19922013-05-15 21:37:41 +000085 static char ID;
Hal Finkel96c2d4d2012-06-08 15:38:21 +000086
Hal Finkel25c19922013-05-15 21:37:41 +000087 PPCCTRLoops() : FunctionPass(ID), TM(0) {
88 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
89 }
90 PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000091 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
92 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +000093
Hal Finkel25c19922013-05-15 21:37:41 +000094 virtual bool runOnFunction(Function &F);
Hal Finkel96c2d4d2012-06-08 15:38:21 +000095
96 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Hal Finkel25c19922013-05-15 21:37:41 +000097 AU.addRequired<LoopInfo>();
98 AU.addPreserved<LoopInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +000099 AU.addRequired<DominatorTreeWrapperPass>();
100 AU.addPreserved<DominatorTreeWrapperPass>();
Hal Finkel25c19922013-05-15 21:37:41 +0000101 AU.addRequired<ScalarEvolution>();
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000102 }
103
104 private:
Hal Finkel5f587c52013-05-16 19:58:38 +0000105 bool mightUseCTR(const Triple &TT, BasicBlock *BB);
Hal Finkel25c19922013-05-15 21:37:41 +0000106 bool convertToCTRLoop(Loop *L);
Hal Finkele6d7c282013-05-20 16:47:10 +0000107
Hal Finkel25c19922013-05-15 21:37:41 +0000108 private:
109 PPCTargetMachine *TM;
110 LoopInfo *LI;
111 ScalarEvolution *SE;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000112 const DataLayout *DL;
Hal Finkel25c19922013-05-15 21:37:41 +0000113 DominatorTree *DT;
114 const TargetLibraryInfo *LibInfo;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000115 };
116
117 char PPCCTRLoops::ID = 0;
Hal Finkel25c19922013-05-15 21:37:41 +0000118#ifndef NDEBUG
119 int PPCCTRLoops::Counter = 0;
120#endif
Hal Finkel8ca38842013-05-20 16:08:17 +0000121
122#ifndef NDEBUG
123 struct PPCCTRLoopsVerify : public MachineFunctionPass {
124 public:
125 static char ID;
126
127 PPCCTRLoopsVerify() : MachineFunctionPass(ID) {
128 initializePPCCTRLoopsVerifyPass(*PassRegistry::getPassRegistry());
129 }
130
131 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
132 AU.addRequired<MachineDominatorTree>();
133 MachineFunctionPass::getAnalysisUsage(AU);
134 }
135
136 virtual bool runOnMachineFunction(MachineFunction &MF);
137
138 private:
139 MachineDominatorTree *MDT;
140 };
141
142 char PPCCTRLoopsVerify::ID = 0;
143#endif // NDEBUG
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000144} // end anonymous namespace
145
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +0000146INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
147 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000148INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Hal Finkel25c19922013-05-15 21:37:41 +0000149INITIALIZE_PASS_DEPENDENCY(LoopInfo)
150INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +0000151INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
152 false, false)
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000153
Hal Finkel25c19922013-05-15 21:37:41 +0000154FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
155 return new PPCCTRLoops(TM);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000156}
157
Hal Finkel8ca38842013-05-20 16:08:17 +0000158#ifndef NDEBUG
159INITIALIZE_PASS_BEGIN(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
160 "PowerPC CTR Loops Verify", false, false)
161INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
162INITIALIZE_PASS_END(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
163 "PowerPC CTR Loops Verify", false, false)
164
165FunctionPass *llvm::createPPCCTRLoopsVerify() {
166 return new PPCCTRLoopsVerify();
167}
168#endif // NDEBUG
169
Hal Finkel25c19922013-05-15 21:37:41 +0000170bool PPCCTRLoops::runOnFunction(Function &F) {
171 LI = &getAnalysis<LoopInfo>();
172 SE = &getAnalysis<ScalarEvolution>();
Chandler Carruth73523022014-01-13 13:07:17 +0000173 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Rafael Espindola93512512014-02-25 17:30:31 +0000174 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
175 DL = DLP ? &DLP->getDataLayout() : 0;
Hal Finkel25c19922013-05-15 21:37:41 +0000176 LibInfo = getAnalysisIfAvailable<TargetLibraryInfo>();
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000177
Hal Finkel25c19922013-05-15 21:37:41 +0000178 bool MadeChange = false;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000179
Hal Finkel25c19922013-05-15 21:37:41 +0000180 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000181 I != E; ++I) {
Hal Finkel25c19922013-05-15 21:37:41 +0000182 Loop *L = *I;
183 if (!L->getParentLoop())
184 MadeChange |= convertToCTRLoop(L);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000185 }
186
Hal Finkel25c19922013-05-15 21:37:41 +0000187 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000188}
189
Hal Finkel5f587c52013-05-16 19:58:38 +0000190bool PPCCTRLoops::mightUseCTR(const Triple &TT, BasicBlock *BB) {
191 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
192 J != JE; ++J) {
193 if (CallInst *CI = dyn_cast<CallInst>(J)) {
Hal Finkel2f474f02013-05-18 09:20:39 +0000194 if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
195 // Inline ASM is okay, unless it clobbers the ctr register.
196 InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
197 for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
198 InlineAsm::ConstraintInfo &C = CIV[i];
199 if (C.Type != InlineAsm::isInput)
200 for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
201 if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
202 return true;
203 }
204
205 continue;
206 }
207
Hal Finkel5f587c52013-05-16 19:58:38 +0000208 if (!TM)
209 return true;
210 const TargetLowering *TLI = TM->getTargetLowering();
211
212 if (Function *F = CI->getCalledFunction()) {
213 // Most intrinsics don't become function calls, but some might.
214 // sin, cos, exp and log are always calls.
215 unsigned Opcode;
216 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
217 switch (F->getIntrinsicID()) {
218 default: continue;
219
220// VisualStudio defines setjmp as _setjmp
221#if defined(_MSC_VER) && defined(setjmp) && \
222 !defined(setjmp_undefined_for_msvc)
223# pragma push_macro("setjmp")
224# undef setjmp
225# define setjmp_undefined_for_msvc
226#endif
227
228 case Intrinsic::setjmp:
229
230#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
231 // let's return it to _setjmp state
232# pragma pop_macro("setjmp")
233# undef setjmp_undefined_for_msvc
234#endif
235
236 case Intrinsic::longjmp:
Hal Finkel40f76d52013-07-17 05:35:44 +0000237
238 // Exclude eh_sjlj_setjmp; we don't need to exclude eh_sjlj_longjmp
239 // because, although it does clobber the counter register, the
240 // control can't then return to inside the loop unless there is also
241 // an eh_sjlj_setjmp.
242 case Intrinsic::eh_sjlj_setjmp:
243
Hal Finkel5f587c52013-05-16 19:58:38 +0000244 case Intrinsic::memcpy:
245 case Intrinsic::memmove:
246 case Intrinsic::memset:
247 case Intrinsic::powi:
248 case Intrinsic::log:
249 case Intrinsic::log2:
250 case Intrinsic::log10:
251 case Intrinsic::exp:
252 case Intrinsic::exp2:
253 case Intrinsic::pow:
254 case Intrinsic::sin:
255 case Intrinsic::cos:
256 return true;
Hal Finkel0c5c01aa2013-08-19 23:35:46 +0000257 case Intrinsic::copysign:
258 if (CI->getArgOperand(0)->getType()->getScalarType()->
259 isPPC_FP128Ty())
260 return true;
261 else
262 continue; // ISD::FCOPYSIGN is never a library call.
Hal Finkel5f587c52013-05-16 19:58:38 +0000263 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
264 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
265 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
266 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
267 case Intrinsic::rint: Opcode = ISD::FRINT; break;
268 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
Hal Finkel171817e2013-08-07 22:49:12 +0000269 case Intrinsic::round: Opcode = ISD::FROUND; break;
Hal Finkel5f587c52013-05-16 19:58:38 +0000270 }
271 }
272
273 // PowerPC does not use [US]DIVREM or other library calls for
274 // operations on regular types which are not otherwise library calls
275 // (i.e. soft float or atomics). If adapting for targets that do,
276 // additional care is required here.
277
278 LibFunc::Func Func;
279 if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
280 LibInfo->getLibFunc(F->getName(), Func) &&
281 LibInfo->hasOptimizedCodeGen(Func)) {
282 // Non-read-only functions are never treated as intrinsics.
283 if (!CI->onlyReadsMemory())
284 return true;
285
286 // Conversion happens only for FP calls.
287 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
288 return true;
289
290 switch (Func) {
291 default: return true;
292 case LibFunc::copysign:
293 case LibFunc::copysignf:
Hal Finkel5f587c52013-05-16 19:58:38 +0000294 continue; // ISD::FCOPYSIGN is never a library call.
Hal Finkel1cf48ab2013-08-19 23:35:24 +0000295 case LibFunc::copysignl:
296 return true;
Hal Finkel5f587c52013-05-16 19:58:38 +0000297 case LibFunc::fabs:
298 case LibFunc::fabsf:
299 case LibFunc::fabsl:
300 continue; // ISD::FABS is never a library call.
301 case LibFunc::sqrt:
302 case LibFunc::sqrtf:
303 case LibFunc::sqrtl:
304 Opcode = ISD::FSQRT; break;
305 case LibFunc::floor:
306 case LibFunc::floorf:
307 case LibFunc::floorl:
308 Opcode = ISD::FFLOOR; break;
309 case LibFunc::nearbyint:
310 case LibFunc::nearbyintf:
311 case LibFunc::nearbyintl:
312 Opcode = ISD::FNEARBYINT; break;
313 case LibFunc::ceil:
314 case LibFunc::ceilf:
315 case LibFunc::ceill:
316 Opcode = ISD::FCEIL; break;
317 case LibFunc::rint:
318 case LibFunc::rintf:
319 case LibFunc::rintl:
320 Opcode = ISD::FRINT; break;
Hal Finkel171817e2013-08-07 22:49:12 +0000321 case LibFunc::round:
322 case LibFunc::roundf:
323 case LibFunc::roundl:
324 Opcode = ISD::FROUND; break;
Hal Finkel5f587c52013-05-16 19:58:38 +0000325 case LibFunc::trunc:
326 case LibFunc::truncf:
327 case LibFunc::truncl:
328 Opcode = ISD::FTRUNC; break;
329 }
330
331 MVT VTy =
332 TLI->getSimpleValueType(CI->getArgOperand(0)->getType(), true);
333 if (VTy == MVT::Other)
334 return true;
335
336 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
337 continue;
338 else if (VTy.isVector() &&
339 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
340 continue;
341
342 return true;
343 }
344 }
345
346 return true;
347 } else if (isa<BinaryOperator>(J) &&
348 J->getType()->getScalarType()->isPPC_FP128Ty()) {
349 // Most operations on ppc_f128 values become calls.
350 return true;
351 } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
352 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
353 CastInst *CI = cast<CastInst>(J);
354 if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
355 CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
356 (TT.isArch32Bit() &&
357 (CI->getSrcTy()->getScalarType()->isIntegerTy(64) ||
358 CI->getDestTy()->getScalarType()->isIntegerTy(64))
359 ))
360 return true;
Hal Finkelfa5f6f72013-06-07 22:16:19 +0000361 } else if (TT.isArch32Bit() &&
362 J->getType()->getScalarType()->isIntegerTy(64) &&
363 (J->getOpcode() == Instruction::UDiv ||
364 J->getOpcode() == Instruction::SDiv ||
365 J->getOpcode() == Instruction::URem ||
366 J->getOpcode() == Instruction::SRem)) {
367 return true;
Hal Finkel5f587c52013-05-16 19:58:38 +0000368 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
369 // On PowerPC, indirect jumps use the counter register.
370 return true;
371 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
372 if (!TM)
373 return true;
374 const TargetLowering *TLI = TM->getTargetLowering();
375
376 if (TLI->supportJumpTables() &&
377 SI->getNumCases()+1 >= (unsigned) TLI->getMinimumJumpTableEntries())
378 return true;
379 }
380 }
381
382 return false;
383}
384
Hal Finkel25c19922013-05-15 21:37:41 +0000385bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
386 bool MadeChange = false;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000387
Hal Finkel25c19922013-05-15 21:37:41 +0000388 Triple TT = Triple(L->getHeader()->getParent()->getParent()->
389 getTargetTriple());
390 if (!TT.isArch32Bit() && !TT.isArch64Bit())
391 return MadeChange; // Unknown arch. type.
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000392
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000393 // Process nested loops first.
Hal Finkel25c19922013-05-15 21:37:41 +0000394 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
395 MadeChange |= convertToCTRLoop(*I);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000396 }
Hal Finkel25c19922013-05-15 21:37:41 +0000397
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000398 // If a nested loop has been converted, then we can't convert this loop.
Hal Finkel25c19922013-05-15 21:37:41 +0000399 if (MadeChange)
400 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000401
Hal Finkel25c19922013-05-15 21:37:41 +0000402#ifndef NDEBUG
403 // Stop trying after reaching the limit (if any).
404 int Limit = CTRLoopLimit;
405 if (Limit >= 0) {
406 if (Counter >= CTRLoopLimit)
Hal Finkel21f2a432013-03-18 17:40:44 +0000407 return false;
Hal Finkel25c19922013-05-15 21:37:41 +0000408 Counter++;
Hal Finkel21f2a432013-03-18 17:40:44 +0000409 }
Hal Finkel25c19922013-05-15 21:37:41 +0000410#endif
Hal Finkel21f2a432013-03-18 17:40:44 +0000411
Hal Finkel25c19922013-05-15 21:37:41 +0000412 // We don't want to spill/restore the counter register, and so we don't
413 // want to use the counter register if the loop contains calls.
414 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
Hal Finkel5f587c52013-05-16 19:58:38 +0000415 I != IE; ++I)
416 if (mightUseCTR(TT, *I))
417 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000418
Hal Finkel25c19922013-05-15 21:37:41 +0000419 SmallVector<BasicBlock*, 4> ExitingBlocks;
420 L->getExitingBlocks(ExitingBlocks);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000421
Hal Finkel25c19922013-05-15 21:37:41 +0000422 BasicBlock *CountedExitBlock = 0;
423 const SCEV *ExitCount = 0;
424 BranchInst *CountedExitBranch = 0;
Craig Topperaf0dea12013-07-04 01:31:24 +0000425 for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
Hal Finkel25c19922013-05-15 21:37:41 +0000426 IE = ExitingBlocks.end(); I != IE; ++I) {
427 const SCEV *EC = SE->getExitCount(L, *I);
428 DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
429 (*I)->getName() << ": " << *EC << "\n");
430 if (isa<SCEVCouldNotCompute>(EC))
431 continue;
432 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
433 if (ConstEC->getValue()->isZero())
434 continue;
435 } else if (!SE->isLoopInvariant(EC, L))
436 continue;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000437
Hal Finkel25e4a0d2013-07-01 19:34:59 +0000438 if (SE->getTypeSizeInBits(EC->getType()) > (TT.isArch64Bit() ? 64 : 32))
439 continue;
440
Hal Finkel25c19922013-05-15 21:37:41 +0000441 // We now have a loop-invariant count of loop iterations (which is not the
442 // constant zero) for which we know that this loop will not exit via this
443 // exisiting block.
Hal Finkel6261c2d2012-06-16 20:34:07 +0000444
Hal Finkel25c19922013-05-15 21:37:41 +0000445 // We need to make sure that this block will run on every loop iteration.
446 // For this to be true, we must dominate all blocks with backedges. Such
447 // blocks are in-loop predecessors to the header block.
448 bool NotAlways = false;
449 for (pred_iterator PI = pred_begin(L->getHeader()),
450 PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
451 if (!L->contains(*PI))
452 continue;
453
454 if (!DT->dominates(*I, *PI)) {
455 NotAlways = true;
456 break;
457 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000458 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000459
Hal Finkel25c19922013-05-15 21:37:41 +0000460 if (NotAlways)
461 continue;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000462
Hal Finkel25c19922013-05-15 21:37:41 +0000463 // Make sure this blocks ends with a conditional branch.
464 Instruction *TI = (*I)->getTerminator();
465 if (!TI)
466 continue;
467
468 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
469 if (!BI->isConditional())
470 continue;
471
472 CountedExitBranch = BI;
473 } else
474 continue;
475
476 // Note that this block may not be the loop latch block, even if the loop
477 // has a latch block.
478 CountedExitBlock = *I;
479 ExitCount = EC;
480 break;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000481 }
482
Hal Finkel25c19922013-05-15 21:37:41 +0000483 if (!CountedExitBlock)
484 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000485
Hal Finkel25c19922013-05-15 21:37:41 +0000486 BasicBlock *Preheader = L->getLoopPreheader();
Hal Finkel5f587c52013-05-16 19:58:38 +0000487
488 // If we don't have a preheader, then insert one. If we already have a
489 // preheader, then we can use it (except if the preheader contains a use of
490 // the CTR register because some such uses might be reordered by the
491 // selection DAG after the mtctr instruction).
492 if (!Preheader || mightUseCTR(TT, Preheader))
Hal Finkele6d7c282013-05-20 16:47:10 +0000493 Preheader = InsertPreheaderForLoop(L, this);
Hal Finkel25c19922013-05-15 21:37:41 +0000494 if (!Preheader)
495 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000496
Hal Finkel25c19922013-05-15 21:37:41 +0000497 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000498
Hal Finkel25c19922013-05-15 21:37:41 +0000499 // Insert the count into the preheader and replace the condition used by the
500 // selected branch.
501 MadeChange = true;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000502
Hal Finkel25c19922013-05-15 21:37:41 +0000503 SCEVExpander SCEVE(*SE, "loopcnt");
504 LLVMContext &C = SE->getContext();
505 Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(C) :
506 Type::getInt32Ty(C);
507 if (!ExitCount->getType()->isPointerTy() &&
508 ExitCount->getType() != CountType)
509 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
510 ExitCount = SE->getAddExpr(ExitCount,
511 SE->getConstant(CountType, 1));
512 Value *ECValue = SCEVE.expandCodeFor(ExitCount, CountType,
513 Preheader->getTerminator());
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000514
Hal Finkel25c19922013-05-15 21:37:41 +0000515 IRBuilder<> CountBuilder(Preheader->getTerminator());
516 Module *M = Preheader->getParent()->getParent();
517 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
518 CountType);
519 CountBuilder.CreateCall(MTCTRFunc, ECValue);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000520
Hal Finkel25c19922013-05-15 21:37:41 +0000521 IRBuilder<> CondBuilder(CountedExitBranch);
522 Value *DecFunc =
523 Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
524 Value *NewCond = CondBuilder.CreateCall(DecFunc);
525 Value *OldCond = CountedExitBranch->getCondition();
526 CountedExitBranch->setCondition(NewCond);
527
528 // The false branch must exit the loop.
529 if (!L->contains(CountedExitBranch->getSuccessor(0)))
530 CountedExitBranch->swapSuccessors();
531
532 // The old condition may be dead now, and may have even created a dead PHI
533 // (the original induction variable).
534 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
535 DeleteDeadPHIs(CountedExitBlock);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000536
537 ++NumCTRLoops;
Hal Finkel25c19922013-05-15 21:37:41 +0000538 return MadeChange;
539}
540
Hal Finkel8ca38842013-05-20 16:08:17 +0000541#ifndef NDEBUG
542static bool clobbersCTR(const MachineInstr *MI) {
543 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
544 const MachineOperand &MO = MI->getOperand(i);
545 if (MO.isReg()) {
546 if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
547 return true;
548 } else if (MO.isRegMask()) {
549 if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
550 return true;
551 }
552 }
553
554 return false;
555}
556
557static bool verifyCTRBranch(MachineBasicBlock *MBB,
558 MachineBasicBlock::iterator I) {
559 MachineBasicBlock::iterator BI = I;
560 SmallSet<MachineBasicBlock *, 16> Visited;
561 SmallVector<MachineBasicBlock *, 8> Preds;
562 bool CheckPreds;
563
564 if (I == MBB->begin()) {
565 Visited.insert(MBB);
566 goto queue_preds;
567 } else
568 --I;
569
570check_block:
571 Visited.insert(MBB);
572 if (I == MBB->end())
573 goto queue_preds;
574
575 CheckPreds = true;
576 for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
577 unsigned Opc = I->getOpcode();
Hal Finkel0859ef22013-05-20 16:08:37 +0000578 if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
Hal Finkel8ca38842013-05-20 16:08:17 +0000579 CheckPreds = false;
580 break;
581 }
582
583 if (I != BI && clobbersCTR(I)) {
584 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " (" <<
585 MBB->getFullName() << ") instruction " << *I <<
586 " clobbers CTR, invalidating " << "BB#" <<
587 BI->getParent()->getNumber() << " (" <<
588 BI->getParent()->getFullName() << ") instruction " <<
589 *BI << "\n");
590 return false;
591 }
592
593 if (I == IE)
594 break;
595 }
596
597 if (!CheckPreds && Preds.empty())
598 return true;
599
600 if (CheckPreds) {
601queue_preds:
602 if (MachineFunction::iterator(MBB) == MBB->getParent()->begin()) {
603 DEBUG(dbgs() << "Unable to find a MTCTR instruction for BB#" <<
604 BI->getParent()->getNumber() << " (" <<
605 BI->getParent()->getFullName() << ") instruction " <<
606 *BI << "\n");
607 return false;
608 }
609
610 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
611 PIE = MBB->pred_end(); PI != PIE; ++PI)
612 Preds.push_back(*PI);
613 }
614
615 do {
616 MBB = Preds.pop_back_val();
617 if (!Visited.count(MBB)) {
618 I = MBB->getLastNonDebugInstr();
619 goto check_block;
620 }
621 } while (!Preds.empty());
622
623 return true;
624}
625
626bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
627 MDT = &getAnalysis<MachineDominatorTree>();
628
629 // Verify that all bdnz/bdz instructions are dominated by a loop mtctr before
630 // any other instructions that might clobber the ctr register.
631 for (MachineFunction::iterator I = MF.begin(), IE = MF.end();
632 I != IE; ++I) {
633 MachineBasicBlock *MBB = I;
634 if (!MDT->isReachableFromEntry(MBB))
635 continue;
636
637 for (MachineBasicBlock::iterator MII = MBB->getFirstTerminator(),
638 MIIE = MBB->end(); MII != MIIE; ++MII) {
639 unsigned Opc = MII->getOpcode();
640 if (Opc == PPC::BDNZ8 || Opc == PPC::BDNZ ||
641 Opc == PPC::BDZ8 || Opc == PPC::BDZ)
642 if (!verifyCTRBranch(MBB, MII))
643 llvm_unreachable("Invalid PPC CTR loop!");
644 }
645 }
646
647 return false;
648}
649#endif // NDEBUG
650