blob: 8d61e81b1fc7ca2934040c2e119bf8cd854b863d [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
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000026#include "PPC.h"
Eric Christopherb16eacf2017-06-29 23:28:45 +000027#include "PPCSubtarget.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000028#include "PPCTargetMachine.h"
Hal Finkel25c19922013-05-15 21:37:41 +000029#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000030#include "llvm/ADT/Statistic.h"
Hal Finkel25c19922013-05-15 21:37:41 +000031#include "llvm/Analysis/LoopInfo.h"
32#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000033#include "llvm/Analysis/TargetLibraryInfo.h"
Eric Christopherb16eacf2017-06-29 23:28:45 +000034#include "llvm/CodeGen/TargetPassConfig.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 Carruth4220e9c2014-03-04 11:17:44 +000042#include "llvm/IR/ValueHandle.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/PassSupport.h"
Hal Finkel25c19922013-05-15 21:37:41 +000044#include "llvm/Support/CommandLine.h"
Hal Finkel96c2d4d2012-06-08 15:38:21 +000045#include "llvm/Support/Debug.h"
46#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000047#include "llvm/Transforms/Scalar.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 +000059using namespace llvm;
60
Chandler Carruth84e68b22014-04-22 02:41:26 +000061#define DEBUG_TYPE "ctrloops"
62
Hal Finkel25c19922013-05-15 21:37:41 +000063#ifndef NDEBUG
64static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
65#endif
66
Hal Finkel96c2d4d2012-06-08 15:38:21 +000067STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
68
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000069namespace llvm {
70 void initializePPCCTRLoopsPass(PassRegistry&);
Hal Finkel8ca38842013-05-20 16:08:17 +000071#ifndef NDEBUG
72 void initializePPCCTRLoopsVerifyPass(PassRegistry&);
73#endif
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000074}
75
Hal Finkel96c2d4d2012-06-08 15:38:21 +000076namespace {
Hal Finkel25c19922013-05-15 21:37:41 +000077 struct PPCCTRLoops : public FunctionPass {
78
79#ifndef NDEBUG
80 static int Counter;
81#endif
Hal Finkel96c2d4d2012-06-08 15:38:21 +000082
83 public:
Hal Finkel25c19922013-05-15 21:37:41 +000084 static char ID;
Hal Finkel96c2d4d2012-06-08 15:38:21 +000085
Eric Christopherb16eacf2017-06-29 23:28:45 +000086 PPCCTRLoops() : FunctionPass(ID) {
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000087 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
88 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +000089
Craig Topper0d3fa922014-04-29 07:57:37 +000090 bool runOnFunction(Function &F) override;
Hal Finkel96c2d4d2012-06-08 15:38:21 +000091
Craig Topper0d3fa922014-04-29 07:57:37 +000092 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth4f8f3072015-01-17 14:16:18 +000093 AU.addRequired<LoopInfoWrapperPass>();
94 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +000095 AU.addRequired<DominatorTreeWrapperPass>();
96 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000097 AU.addRequired<ScalarEvolutionWrapperPass>();
Hal Finkel96c2d4d2012-06-08 15:38:21 +000098 }
99
100 private:
Eric Christopherb16eacf2017-06-29 23:28:45 +0000101 bool mightUseCTR(BasicBlock *BB);
Hal Finkel25c19922013-05-15 21:37:41 +0000102 bool convertToCTRLoop(Loop *L);
Hal Finkele6d7c282013-05-20 16:47:10 +0000103
Hal Finkel25c19922013-05-15 21:37:41 +0000104 private:
Eric Christopherb16eacf2017-06-29 23:28:45 +0000105 const PPCTargetMachine *TM;
106 const PPCSubtarget *STI;
107 const PPCTargetLowering *TLI;
108 const DataLayout *DL;
109 const TargetLibraryInfo *LibInfo;
Hal Finkel25c19922013-05-15 21:37:41 +0000110 LoopInfo *LI;
111 ScalarEvolution *SE;
Hal Finkel25c19922013-05-15 21:37:41 +0000112 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000113 bool PreserveLCSSA;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000114 };
115
116 char PPCCTRLoops::ID = 0;
Hal Finkel25c19922013-05-15 21:37:41 +0000117#ifndef NDEBUG
118 int PPCCTRLoops::Counter = 0;
119#endif
Hal Finkel8ca38842013-05-20 16:08:17 +0000120
121#ifndef NDEBUG
122 struct PPCCTRLoopsVerify : public MachineFunctionPass {
123 public:
124 static char ID;
125
126 PPCCTRLoopsVerify() : MachineFunctionPass(ID) {
127 initializePPCCTRLoopsVerifyPass(*PassRegistry::getPassRegistry());
128 }
129
Craig Topper0d3fa922014-04-29 07:57:37 +0000130 void getAnalysisUsage(AnalysisUsage &AU) const override {
Hal Finkel8ca38842013-05-20 16:08:17 +0000131 AU.addRequired<MachineDominatorTree>();
132 MachineFunctionPass::getAnalysisUsage(AU);
133 }
134
Craig Topper0d3fa922014-04-29 07:57:37 +0000135 bool runOnMachineFunction(MachineFunction &MF) override;
Hal Finkel8ca38842013-05-20 16:08:17 +0000136
137 private:
138 MachineDominatorTree *MDT;
139 };
140
141 char PPCCTRLoopsVerify::ID = 0;
142#endif // NDEBUG
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000143} // end anonymous namespace
144
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +0000145INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
146 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000147INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000148INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000149INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +0000150INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
151 false, false)
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000152
Eric Christopherb16eacf2017-06-29 23:28:45 +0000153FunctionPass *llvm::createPPCCTRLoops() { return new PPCCTRLoops(); }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000154
Hal Finkel8ca38842013-05-20 16:08:17 +0000155#ifndef NDEBUG
156INITIALIZE_PASS_BEGIN(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
157 "PowerPC CTR Loops Verify", false, false)
158INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
159INITIALIZE_PASS_END(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
160 "PowerPC CTR Loops Verify", false, false)
161
162FunctionPass *llvm::createPPCCTRLoopsVerify() {
163 return new PPCCTRLoopsVerify();
164}
165#endif // NDEBUG
166
Hal Finkel25c19922013-05-15 21:37:41 +0000167bool PPCCTRLoops::runOnFunction(Function &F) {
Andrew Kaylor289bd5f2016-04-27 19:39:32 +0000168 if (skipFunction(F))
169 return false;
170
Eric Christopherb16eacf2017-06-29 23:28:45 +0000171 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
172 if (!TPC)
173 return false;
174
175 TM = &TPC->getTM<PPCTargetMachine>();
176 STI = TM->getSubtargetImpl(F);
177 TLI = STI->getTargetLowering();
178
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000179 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000180 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruth73523022014-01-13 13:07:17 +0000181 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Mehdi Amini46a43552015-03-04 18:43:29 +0000182 DL = &F.getParent()->getDataLayout();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000183 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
184 LibInfo = TLIP ? &TLIP->getTLI() : nullptr;
Justin Bogner843fb202015-12-15 19:40:57 +0000185 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000186
Hal Finkel25c19922013-05-15 21:37:41 +0000187 bool MadeChange = false;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000188
Hal Finkel25c19922013-05-15 21:37:41 +0000189 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000190 I != E; ++I) {
Hal Finkel25c19922013-05-15 21:37:41 +0000191 Loop *L = *I;
192 if (!L->getParentLoop())
193 MadeChange |= convertToCTRLoop(L);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000194 }
195
Hal Finkel25c19922013-05-15 21:37:41 +0000196 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000197}
198
Hal Finkel22304042014-02-25 20:51:50 +0000199static bool isLargeIntegerTy(bool Is32Bit, Type *Ty) {
200 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Aaron Ballman3d69c5c2014-02-26 20:22:20 +0000201 return ITy->getBitWidth() > (Is32Bit ? 32U : 64U);
Hal Finkel22304042014-02-25 20:51:50 +0000202
203 return false;
204}
205
David Majnemerd0bcef22014-12-27 19:45:38 +0000206// Determining the address of a TLS variable results in a function call in
207// certain TLS models.
Eric Christopherb16eacf2017-06-29 23:28:45 +0000208static bool memAddrUsesCTR(const PPCTargetMachine &TM, const Value *MemAddr) {
David Majnemerd0bcef22014-12-27 19:45:38 +0000209 const auto *GV = dyn_cast<GlobalValue>(MemAddr);
Hal Finkel7d0e34e2015-10-28 23:43:00 +0000210 if (!GV) {
211 // Recurse to check for constants that refer to TLS global variables.
212 if (const auto *CV = dyn_cast<Constant>(MemAddr))
213 for (const auto &CO : CV->operands())
214 if (memAddrUsesCTR(TM, CO))
215 return true;
216
David Majnemerd0bcef22014-12-27 19:45:38 +0000217 return false;
Hal Finkel7d0e34e2015-10-28 23:43:00 +0000218 }
219
David Majnemerd0bcef22014-12-27 19:45:38 +0000220 if (!GV->isThreadLocal())
221 return false;
Eric Christopherb16eacf2017-06-29 23:28:45 +0000222 TLSModel::Model Model = TM.getTLSModel(GV);
David Majnemerd0bcef22014-12-27 19:45:38 +0000223 return Model == TLSModel::GeneralDynamic || Model == TLSModel::LocalDynamic;
224}
225
Eric Christopher56f481b2017-06-29 23:28:47 +0000226// Loop through the inline asm constraints and look for something that clobbers
227// ctr.
228static bool asmClobbersCTR(InlineAsm *IA) {
229 InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
230 for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
231 InlineAsm::ConstraintInfo &C = CIV[i];
232 if (C.Type != InlineAsm::isInput)
233 for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
234 if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
235 return true;
236 }
237 return false;
238}
239
Eric Christopherb16eacf2017-06-29 23:28:45 +0000240bool PPCCTRLoops::mightUseCTR(BasicBlock *BB) {
Hal Finkel5f587c52013-05-16 19:58:38 +0000241 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
242 J != JE; ++J) {
243 if (CallInst *CI = dyn_cast<CallInst>(J)) {
Eric Christopher56f481b2017-06-29 23:28:47 +0000244 // Inline ASM is okay, unless it clobbers the ctr register.
Hal Finkel2f474f02013-05-18 09:20:39 +0000245 if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000246 if (asmClobbersCTR(IA))
247 return true;
Hal Finkel2f474f02013-05-18 09:20:39 +0000248 continue;
249 }
250
Hal Finkel5f587c52013-05-16 19:58:38 +0000251 if (Function *F = CI->getCalledFunction()) {
252 // Most intrinsics don't become function calls, but some might.
253 // sin, cos, exp and log are always calls.
Hal Finkel0b371752016-03-27 05:40:56 +0000254 unsigned Opcode = 0;
Hal Finkel5f587c52013-05-16 19:58:38 +0000255 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
256 switch (F->getIntrinsicID()) {
257 default: continue;
Eric Christopher71f6e2f2015-09-08 22:14:58 +0000258 // If we have a call to ppc_is_decremented_ctr_nonzero, or ppc_mtctr
259 // we're definitely using CTR.
260 case Intrinsic::ppc_is_decremented_ctr_nonzero:
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000261 case Intrinsic::ppc_mtctr:
262 return true;
Hal Finkel5f587c52013-05-16 19:58:38 +0000263
264// VisualStudio defines setjmp as _setjmp
265#if defined(_MSC_VER) && defined(setjmp) && \
266 !defined(setjmp_undefined_for_msvc)
267# pragma push_macro("setjmp")
268# undef setjmp
269# define setjmp_undefined_for_msvc
270#endif
271
272 case Intrinsic::setjmp:
273
274#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
275 // let's return it to _setjmp state
276# pragma pop_macro("setjmp")
277# undef setjmp_undefined_for_msvc
278#endif
279
280 case Intrinsic::longjmp:
Hal Finkel40f76d52013-07-17 05:35:44 +0000281
282 // Exclude eh_sjlj_setjmp; we don't need to exclude eh_sjlj_longjmp
283 // because, although it does clobber the counter register, the
284 // control can't then return to inside the loop unless there is also
285 // an eh_sjlj_setjmp.
286 case Intrinsic::eh_sjlj_setjmp:
287
Hal Finkel5f587c52013-05-16 19:58:38 +0000288 case Intrinsic::memcpy:
289 case Intrinsic::memmove:
290 case Intrinsic::memset:
291 case Intrinsic::powi:
292 case Intrinsic::log:
293 case Intrinsic::log2:
294 case Intrinsic::log10:
295 case Intrinsic::exp:
296 case Intrinsic::exp2:
297 case Intrinsic::pow:
298 case Intrinsic::sin:
299 case Intrinsic::cos:
300 return true;
Hal Finkel0c5c01aa2013-08-19 23:35:46 +0000301 case Intrinsic::copysign:
302 if (CI->getArgOperand(0)->getType()->getScalarType()->
303 isPPC_FP128Ty())
304 return true;
305 else
306 continue; // ISD::FCOPYSIGN is never a library call.
Hal Finkelcef9e522017-04-11 02:03:17 +0000307 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
308 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
309 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
310 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
311 case Intrinsic::rint: Opcode = ISD::FRINT; break;
312 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
313 case Intrinsic::round: Opcode = ISD::FROUND; break;
314 case Intrinsic::minnum: Opcode = ISD::FMINNUM; break;
315 case Intrinsic::maxnum: Opcode = ISD::FMAXNUM; break;
316 case Intrinsic::umul_with_overflow: Opcode = ISD::UMULO; break;
317 case Intrinsic::smul_with_overflow: Opcode = ISD::SMULO; break;
Hal Finkel5f587c52013-05-16 19:58:38 +0000318 }
319 }
320
321 // PowerPC does not use [US]DIVREM or other library calls for
322 // operations on regular types which are not otherwise library calls
323 // (i.e. soft float or atomics). If adapting for targets that do,
324 // additional care is required here.
325
David L. Jonesd21529f2017-01-23 23:16:46 +0000326 LibFunc Func;
Hal Finkel5f587c52013-05-16 19:58:38 +0000327 if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
328 LibInfo->getLibFunc(F->getName(), Func) &&
329 LibInfo->hasOptimizedCodeGen(Func)) {
330 // Non-read-only functions are never treated as intrinsics.
331 if (!CI->onlyReadsMemory())
332 return true;
333
334 // Conversion happens only for FP calls.
335 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
336 return true;
337
338 switch (Func) {
339 default: return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000340 case LibFunc_copysign:
341 case LibFunc_copysignf:
Hal Finkel5f587c52013-05-16 19:58:38 +0000342 continue; // ISD::FCOPYSIGN is never a library call.
David L. Jonesd21529f2017-01-23 23:16:46 +0000343 case LibFunc_copysignl:
Hal Finkel1cf48ab2013-08-19 23:35:24 +0000344 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000345 case LibFunc_fabs:
346 case LibFunc_fabsf:
347 case LibFunc_fabsl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000348 continue; // ISD::FABS is never a library call.
David L. Jonesd21529f2017-01-23 23:16:46 +0000349 case LibFunc_sqrt:
350 case LibFunc_sqrtf:
351 case LibFunc_sqrtl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000352 Opcode = ISD::FSQRT; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000353 case LibFunc_floor:
354 case LibFunc_floorf:
355 case LibFunc_floorl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000356 Opcode = ISD::FFLOOR; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000357 case LibFunc_nearbyint:
358 case LibFunc_nearbyintf:
359 case LibFunc_nearbyintl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000360 Opcode = ISD::FNEARBYINT; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000361 case LibFunc_ceil:
362 case LibFunc_ceilf:
363 case LibFunc_ceill:
Hal Finkel5f587c52013-05-16 19:58:38 +0000364 Opcode = ISD::FCEIL; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000365 case LibFunc_rint:
366 case LibFunc_rintf:
367 case LibFunc_rintl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000368 Opcode = ISD::FRINT; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000369 case LibFunc_round:
370 case LibFunc_roundf:
371 case LibFunc_roundl:
Hal Finkel171817e2013-08-07 22:49:12 +0000372 Opcode = ISD::FROUND; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000373 case LibFunc_trunc:
374 case LibFunc_truncf:
375 case LibFunc_truncl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000376 Opcode = ISD::FTRUNC; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000377 case LibFunc_fmin:
378 case LibFunc_fminf:
379 case LibFunc_fminl:
Hal Finkel0b371752016-03-27 05:40:56 +0000380 Opcode = ISD::FMINNUM; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000381 case LibFunc_fmax:
382 case LibFunc_fmaxf:
383 case LibFunc_fmaxl:
Hal Finkel0b371752016-03-27 05:40:56 +0000384 Opcode = ISD::FMAXNUM; break;
Hal Finkel5f587c52013-05-16 19:58:38 +0000385 }
Hal Finkel0b371752016-03-27 05:40:56 +0000386 }
Hal Finkel5f587c52013-05-16 19:58:38 +0000387
Hal Finkel0b371752016-03-27 05:40:56 +0000388 if (Opcode) {
Eric Christopherb16eacf2017-06-29 23:28:45 +0000389 MVT VTy = TLI->getSimpleValueType(
390 *DL, CI->getArgOperand(0)->getType(), true);
Hal Finkel5f587c52013-05-16 19:58:38 +0000391 if (VTy == MVT::Other)
392 return true;
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000393
Hal Finkel5f587c52013-05-16 19:58:38 +0000394 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
395 continue;
396 else if (VTy.isVector() &&
397 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
398 continue;
399
400 return true;
401 }
402 }
403
404 return true;
405 } else if (isa<BinaryOperator>(J) &&
406 J->getType()->getScalarType()->isPPC_FP128Ty()) {
407 // Most operations on ppc_f128 values become calls.
408 return true;
409 } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
410 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
411 CastInst *CI = cast<CastInst>(J);
412 if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
413 CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
Eric Christopherb16eacf2017-06-29 23:28:45 +0000414 isLargeIntegerTy(!TM->isPPC64(), CI->getSrcTy()->getScalarType()) ||
415 isLargeIntegerTy(!TM->isPPC64(), CI->getDestTy()->getScalarType()))
Hal Finkel5f587c52013-05-16 19:58:38 +0000416 return true;
Eric Christopherb16eacf2017-06-29 23:28:45 +0000417 } else if (isLargeIntegerTy(!TM->isPPC64(),
Hal Finkel22304042014-02-25 20:51:50 +0000418 J->getType()->getScalarType()) &&
Hal Finkelfa5f6f72013-06-07 22:16:19 +0000419 (J->getOpcode() == Instruction::UDiv ||
420 J->getOpcode() == Instruction::SDiv ||
421 J->getOpcode() == Instruction::URem ||
422 J->getOpcode() == Instruction::SRem)) {
423 return true;
Eric Christopherb16eacf2017-06-29 23:28:45 +0000424 } else if (!TM->isPPC64() &&
Hal Finkelc4c6c872014-05-11 16:23:29 +0000425 isLargeIntegerTy(false, J->getType()->getScalarType()) &&
426 (J->getOpcode() == Instruction::Shl ||
427 J->getOpcode() == Instruction::AShr ||
428 J->getOpcode() == Instruction::LShr)) {
429 // Only on PPC32, for 128-bit integers (specifically not 64-bit
430 // integers), these might be runtime calls.
431 return true;
Hal Finkel5f587c52013-05-16 19:58:38 +0000432 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
433 // On PowerPC, indirect jumps use the counter register.
434 return true;
435 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000436 if (SI->getNumCases() + 1 >= (unsigned)TLI->getMinimumJumpTableEntries())
Hal Finkel5f587c52013-05-16 19:58:38 +0000437 return true;
438 }
Petar Jovanovic0b44f242016-03-17 17:11:33 +0000439
Eric Christopherb16eacf2017-06-29 23:28:45 +0000440 if (STI->useSoftFloat()) {
Petar Jovanovic0b44f242016-03-17 17:11:33 +0000441 switch(J->getOpcode()) {
442 case Instruction::FAdd:
443 case Instruction::FSub:
444 case Instruction::FMul:
445 case Instruction::FDiv:
446 case Instruction::FRem:
447 case Instruction::FPTrunc:
448 case Instruction::FPExt:
449 case Instruction::FPToUI:
450 case Instruction::FPToSI:
451 case Instruction::UIToFP:
452 case Instruction::SIToFP:
453 case Instruction::FCmp:
454 return true;
455 }
456 }
457
David Majnemerd0bcef22014-12-27 19:45:38 +0000458 for (Value *Operand : J->operands())
Eric Christopherb16eacf2017-06-29 23:28:45 +0000459 if (memAddrUsesCTR(*TM, Operand))
David Majnemerd0bcef22014-12-27 19:45:38 +0000460 return true;
Hal Finkel5f587c52013-05-16 19:58:38 +0000461 }
462
463 return false;
464}
465
Hal Finkel25c19922013-05-15 21:37:41 +0000466bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
467 bool MadeChange = false;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000468
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000469 // Process nested loops first.
Hal Finkel25c19922013-05-15 21:37:41 +0000470 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
471 MadeChange |= convertToCTRLoop(*I);
Eric Christopher71f6e2f2015-09-08 22:14:58 +0000472 DEBUG(dbgs() << "Nested loop converted\n");
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000473 }
Hal Finkel25c19922013-05-15 21:37:41 +0000474
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000475 // If a nested loop has been converted, then we can't convert this loop.
Hal Finkel25c19922013-05-15 21:37:41 +0000476 if (MadeChange)
477 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000478
Hal Finkel25c19922013-05-15 21:37:41 +0000479#ifndef NDEBUG
480 // Stop trying after reaching the limit (if any).
481 int Limit = CTRLoopLimit;
482 if (Limit >= 0) {
483 if (Counter >= CTRLoopLimit)
Hal Finkel21f2a432013-03-18 17:40:44 +0000484 return false;
Hal Finkel25c19922013-05-15 21:37:41 +0000485 Counter++;
Hal Finkel21f2a432013-03-18 17:40:44 +0000486 }
Hal Finkel25c19922013-05-15 21:37:41 +0000487#endif
Hal Finkel21f2a432013-03-18 17:40:44 +0000488
Hal Finkel25c19922013-05-15 21:37:41 +0000489 // We don't want to spill/restore the counter register, and so we don't
490 // want to use the counter register if the loop contains calls.
491 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
Hal Finkel5f587c52013-05-16 19:58:38 +0000492 I != IE; ++I)
Eric Christopherb16eacf2017-06-29 23:28:45 +0000493 if (mightUseCTR(*I))
Hal Finkel5f587c52013-05-16 19:58:38 +0000494 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000495
Hal Finkel25c19922013-05-15 21:37:41 +0000496 SmallVector<BasicBlock*, 4> ExitingBlocks;
497 L->getExitingBlocks(ExitingBlocks);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000498
Craig Topper062a2ba2014-04-25 05:30:21 +0000499 BasicBlock *CountedExitBlock = nullptr;
500 const SCEV *ExitCount = nullptr;
501 BranchInst *CountedExitBranch = nullptr;
Craig Topperaf0dea12013-07-04 01:31:24 +0000502 for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
Hal Finkel25c19922013-05-15 21:37:41 +0000503 IE = ExitingBlocks.end(); I != IE; ++I) {
504 const SCEV *EC = SE->getExitCount(L, *I);
505 DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
506 (*I)->getName() << ": " << *EC << "\n");
507 if (isa<SCEVCouldNotCompute>(EC))
508 continue;
509 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
510 if (ConstEC->getValue()->isZero())
511 continue;
512 } else if (!SE->isLoopInvariant(EC, L))
513 continue;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000514
Eric Christopherb16eacf2017-06-29 23:28:45 +0000515 if (SE->getTypeSizeInBits(EC->getType()) > (TM->isPPC64() ? 64 : 32))
Hal Finkel25e4a0d2013-07-01 19:34:59 +0000516 continue;
517
Hal Finkel25c19922013-05-15 21:37:41 +0000518 // We now have a loop-invariant count of loop iterations (which is not the
519 // constant zero) for which we know that this loop will not exit via this
520 // exisiting block.
Hal Finkel6261c2d2012-06-16 20:34:07 +0000521
Hal Finkel25c19922013-05-15 21:37:41 +0000522 // We need to make sure that this block will run on every loop iteration.
523 // For this to be true, we must dominate all blocks with backedges. Such
524 // blocks are in-loop predecessors to the header block.
525 bool NotAlways = false;
526 for (pred_iterator PI = pred_begin(L->getHeader()),
527 PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
528 if (!L->contains(*PI))
529 continue;
530
531 if (!DT->dominates(*I, *PI)) {
532 NotAlways = true;
533 break;
534 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000535 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000536
Hal Finkel25c19922013-05-15 21:37:41 +0000537 if (NotAlways)
538 continue;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000539
Hal Finkel25c19922013-05-15 21:37:41 +0000540 // Make sure this blocks ends with a conditional branch.
541 Instruction *TI = (*I)->getTerminator();
542 if (!TI)
543 continue;
544
545 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
546 if (!BI->isConditional())
547 continue;
548
549 CountedExitBranch = BI;
550 } else
551 continue;
552
553 // Note that this block may not be the loop latch block, even if the loop
554 // has a latch block.
555 CountedExitBlock = *I;
556 ExitCount = EC;
557 break;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000558 }
559
Hal Finkel25c19922013-05-15 21:37:41 +0000560 if (!CountedExitBlock)
561 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000562
Hal Finkel25c19922013-05-15 21:37:41 +0000563 BasicBlock *Preheader = L->getLoopPreheader();
Hal Finkel5f587c52013-05-16 19:58:38 +0000564
565 // If we don't have a preheader, then insert one. If we already have a
566 // preheader, then we can use it (except if the preheader contains a use of
567 // the CTR register because some such uses might be reordered by the
568 // selection DAG after the mtctr instruction).
Eric Christopherb16eacf2017-06-29 23:28:45 +0000569 if (!Preheader || mightUseCTR(Preheader))
Justin Bogner843fb202015-12-15 19:40:57 +0000570 Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
Hal Finkel25c19922013-05-15 21:37:41 +0000571 if (!Preheader)
572 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000573
Hal Finkel25c19922013-05-15 21:37:41 +0000574 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000575
Hal Finkel25c19922013-05-15 21:37:41 +0000576 // Insert the count into the preheader and replace the condition used by the
577 // selected branch.
578 MadeChange = true;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000579
Eric Christopherb16eacf2017-06-29 23:28:45 +0000580 SCEVExpander SCEVE(*SE, *DL, "loopcnt");
Hal Finkel25c19922013-05-15 21:37:41 +0000581 LLVMContext &C = SE->getContext();
Eric Christopherb16eacf2017-06-29 23:28:45 +0000582 Type *CountType = TM->isPPC64() ? Type::getInt64Ty(C) : Type::getInt32Ty(C);
Hal Finkel25c19922013-05-15 21:37:41 +0000583 if (!ExitCount->getType()->isPointerTy() &&
584 ExitCount->getType() != CountType)
585 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000586 ExitCount = SE->getAddExpr(ExitCount, SE->getOne(CountType));
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +0000587 Value *ECValue =
588 SCEVE.expandCodeFor(ExitCount, CountType, Preheader->getTerminator());
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000589
Hal Finkel25c19922013-05-15 21:37:41 +0000590 IRBuilder<> CountBuilder(Preheader->getTerminator());
591 Module *M = Preheader->getParent()->getParent();
592 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
593 CountType);
594 CountBuilder.CreateCall(MTCTRFunc, ECValue);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000595
Hal Finkel25c19922013-05-15 21:37:41 +0000596 IRBuilder<> CondBuilder(CountedExitBranch);
597 Value *DecFunc =
598 Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
David Blaikieff6409d2015-05-18 22:13:54 +0000599 Value *NewCond = CondBuilder.CreateCall(DecFunc, {});
Hal Finkel25c19922013-05-15 21:37:41 +0000600 Value *OldCond = CountedExitBranch->getCondition();
601 CountedExitBranch->setCondition(NewCond);
602
603 // The false branch must exit the loop.
604 if (!L->contains(CountedExitBranch->getSuccessor(0)))
605 CountedExitBranch->swapSuccessors();
606
607 // The old condition may be dead now, and may have even created a dead PHI
608 // (the original induction variable).
609 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Sean Fertiled44cb182017-07-05 17:57:57 +0000610 // Run through the basic blocks of the loop and see if any of them have dead
611 // PHIs that can be removed.
612 for (auto I : L->blocks())
613 DeleteDeadPHIs(I);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000614
615 ++NumCTRLoops;
Hal Finkel25c19922013-05-15 21:37:41 +0000616 return MadeChange;
617}
618
Hal Finkel8ca38842013-05-20 16:08:17 +0000619#ifndef NDEBUG
Duncan P. N. Exon Smithe5a22f42016-07-27 13:24:16 +0000620static bool clobbersCTR(const MachineInstr &MI) {
621 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
622 const MachineOperand &MO = MI.getOperand(i);
Hal Finkel8ca38842013-05-20 16:08:17 +0000623 if (MO.isReg()) {
624 if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
625 return true;
626 } else if (MO.isRegMask()) {
627 if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
628 return true;
629 }
630 }
631
632 return false;
633}
634
635static bool verifyCTRBranch(MachineBasicBlock *MBB,
636 MachineBasicBlock::iterator I) {
637 MachineBasicBlock::iterator BI = I;
638 SmallSet<MachineBasicBlock *, 16> Visited;
639 SmallVector<MachineBasicBlock *, 8> Preds;
640 bool CheckPreds;
641
642 if (I == MBB->begin()) {
643 Visited.insert(MBB);
644 goto queue_preds;
645 } else
646 --I;
647
648check_block:
649 Visited.insert(MBB);
650 if (I == MBB->end())
651 goto queue_preds;
652
653 CheckPreds = true;
654 for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
655 unsigned Opc = I->getOpcode();
Hal Finkel0859ef22013-05-20 16:08:37 +0000656 if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
Hal Finkel8ca38842013-05-20 16:08:17 +0000657 CheckPreds = false;
658 break;
659 }
660
Duncan P. N. Exon Smithe5a22f42016-07-27 13:24:16 +0000661 if (I != BI && clobbersCTR(*I)) {
Hal Finkel8ca38842013-05-20 16:08:17 +0000662 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " (" <<
663 MBB->getFullName() << ") instruction " << *I <<
664 " clobbers CTR, invalidating " << "BB#" <<
665 BI->getParent()->getNumber() << " (" <<
666 BI->getParent()->getFullName() << ") instruction " <<
667 *BI << "\n");
668 return false;
669 }
670
671 if (I == IE)
672 break;
673 }
674
675 if (!CheckPreds && Preds.empty())
676 return true;
677
678 if (CheckPreds) {
679queue_preds:
680 if (MachineFunction::iterator(MBB) == MBB->getParent()->begin()) {
681 DEBUG(dbgs() << "Unable to find a MTCTR instruction for BB#" <<
682 BI->getParent()->getNumber() << " (" <<
683 BI->getParent()->getFullName() << ") instruction " <<
684 *BI << "\n");
685 return false;
686 }
687
688 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
689 PIE = MBB->pred_end(); PI != PIE; ++PI)
690 Preds.push_back(*PI);
691 }
692
693 do {
694 MBB = Preds.pop_back_val();
695 if (!Visited.count(MBB)) {
696 I = MBB->getLastNonDebugInstr();
697 goto check_block;
698 }
699 } while (!Preds.empty());
700
701 return true;
702}
703
704bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
705 MDT = &getAnalysis<MachineDominatorTree>();
706
707 // Verify that all bdnz/bdz instructions are dominated by a loop mtctr before
708 // any other instructions that might clobber the ctr register.
709 for (MachineFunction::iterator I = MF.begin(), IE = MF.end();
710 I != IE; ++I) {
Duncan P. N. Exon Smithac65b4c2015-10-20 01:07:37 +0000711 MachineBasicBlock *MBB = &*I;
Hal Finkel8ca38842013-05-20 16:08:17 +0000712 if (!MDT->isReachableFromEntry(MBB))
713 continue;
714
715 for (MachineBasicBlock::iterator MII = MBB->getFirstTerminator(),
716 MIIE = MBB->end(); MII != MIIE; ++MII) {
717 unsigned Opc = MII->getOpcode();
718 if (Opc == PPC::BDNZ8 || Opc == PPC::BDNZ ||
719 Opc == PPC::BDZ8 || Opc == PPC::BDZ)
720 if (!verifyCTRBranch(MBB, MII))
721 llvm_unreachable("Invalid PPC CTR loop!");
722 }
723 }
724
725 return false;
726}
727#endif // NDEBUG