1 //===-- PPCCTRLoops.cpp - Identify and generate CTR loops -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
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.
18 // Criteria for CTR loops:
19 // - Countable loops (w/ ind. var for a trip count)
20 // - Try inner-most loops first
21 // - No nested CTR loops.
22 // - No function calls in loops.
24 //===----------------------------------------------------------------------===//
27 #include "PPCSubtarget.h"
28 #include "PPCTargetMachine.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/ScalarEvolutionExpander.h"
33 #include "llvm/Analysis/TargetLibraryInfo.h"
34 #include "llvm/CodeGen/TargetPassConfig.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/InlineAsm.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/ValueHandle.h"
43 #include "llvm/PassSupport.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Transforms/Utils/LoopUtils.h"
53 #include "llvm/CodeGen/MachineDominators.h"
54 #include "llvm/CodeGen/MachineFunction.h"
55 #include "llvm/CodeGen/MachineFunctionPass.h"
56 #include "llvm/CodeGen/MachineRegisterInfo.h"
61 #define DEBUG_TYPE "ctrloops"
64 static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
67 STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
70 void initializePPCCTRLoopsPass(PassRegistry&);
72 void initializePPCCTRLoopsVerifyPass(PassRegistry&);
77 struct PPCCTRLoops : public FunctionPass {
86 PPCCTRLoops() : FunctionPass(ID) {
87 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
90 bool runOnFunction(Function &F) override;
92 void getAnalysisUsage(AnalysisUsage &AU) const override {
93 AU.addRequired<LoopInfoWrapperPass>();
94 AU.addPreserved<LoopInfoWrapperPass>();
95 AU.addRequired<DominatorTreeWrapperPass>();
96 AU.addPreserved<DominatorTreeWrapperPass>();
97 AU.addRequired<ScalarEvolutionWrapperPass>();
101 bool mightUseCTR(BasicBlock *BB);
102 bool convertToCTRLoop(Loop *L);
105 const PPCTargetMachine *TM;
106 const PPCSubtarget *STI;
107 const PPCTargetLowering *TLI;
108 const DataLayout *DL;
109 const TargetLibraryInfo *LibInfo;
116 char PPCCTRLoops::ID = 0;
118 int PPCCTRLoops::Counter = 0;
122 struct PPCCTRLoopsVerify : public MachineFunctionPass {
126 PPCCTRLoopsVerify() : MachineFunctionPass(ID) {
127 initializePPCCTRLoopsVerifyPass(*PassRegistry::getPassRegistry());
130 void getAnalysisUsage(AnalysisUsage &AU) const override {
131 AU.addRequired<MachineDominatorTree>();
132 MachineFunctionPass::getAnalysisUsage(AU);
135 bool runOnMachineFunction(MachineFunction &MF) override;
138 MachineDominatorTree *MDT;
141 char PPCCTRLoopsVerify::ID = 0;
143 } // end anonymous namespace
145 INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
147 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
148 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
149 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
150 INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
153 FunctionPass *llvm::createPPCCTRLoops() { return new PPCCTRLoops(); }
156 INITIALIZE_PASS_BEGIN(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
157 "PowerPC CTR Loops Verify", false, false)
158 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
159 INITIALIZE_PASS_END(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
160 "PowerPC CTR Loops Verify", false, false)
162 FunctionPass *llvm::createPPCCTRLoopsVerify() {
163 return new PPCCTRLoopsVerify();
167 bool PPCCTRLoops::runOnFunction(Function &F) {
171 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
175 TM = &TPC->getTM<PPCTargetMachine>();
176 STI = TM->getSubtargetImpl(F);
177 TLI = STI->getTargetLowering();
179 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
180 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
181 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
182 DL = &F.getParent()->getDataLayout();
183 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
184 LibInfo = TLIP ? &TLIP->getTLI() : nullptr;
185 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
187 bool MadeChange = false;
189 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
192 if (!L->getParentLoop())
193 MadeChange |= convertToCTRLoop(L);
199 static bool isLargeIntegerTy(bool Is32Bit, Type *Ty) {
200 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
201 return ITy->getBitWidth() > (Is32Bit ? 32U : 64U);
206 // Determining the address of a TLS variable results in a function call in
207 // certain TLS models.
208 static bool memAddrUsesCTR(const PPCTargetMachine &TM, const Value *MemAddr) {
209 const auto *GV = dyn_cast<GlobalValue>(MemAddr);
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))
220 if (!GV->isThreadLocal())
222 TLSModel::Model Model = TM.getTLSModel(GV);
223 return Model == TLSModel::GeneralDynamic || Model == TLSModel::LocalDynamic;
226 // Loop through the inline asm constraints and look for something that clobbers
228 static 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}"))
240 bool PPCCTRLoops::mightUseCTR(BasicBlock *BB) {
241 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
243 if (CallInst *CI = dyn_cast<CallInst>(J)) {
244 // Inline ASM is okay, unless it clobbers the ctr register.
245 if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
246 if (asmClobbersCTR(IA))
251 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.
255 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
256 switch (F->getIntrinsicID()) {
258 // 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:
261 case Intrinsic::ppc_mtctr:
264 // VisualStudio defines setjmp as _setjmp
265 #if defined(_MSC_VER) && defined(setjmp) && \
266 !defined(setjmp_undefined_for_msvc)
267 # pragma push_macro("setjmp")
269 # define setjmp_undefined_for_msvc
272 case Intrinsic::setjmp:
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
280 case Intrinsic::longjmp:
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:
288 case Intrinsic::memcpy:
289 case Intrinsic::memmove:
290 case Intrinsic::memset:
291 case Intrinsic::powi:
293 case Intrinsic::log2:
294 case Intrinsic::log10:
296 case Intrinsic::exp2:
301 case Intrinsic::copysign:
302 if (CI->getArgOperand(0)->getType()->getScalarType()->
306 continue; // ISD::FCOPYSIGN is never a library call.
307 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;
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.
327 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())
334 // Conversion happens only for FP calls.
335 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
339 default: return true;
340 case LibFunc_copysign:
341 case LibFunc_copysignf:
342 continue; // ISD::FCOPYSIGN is never a library call.
343 case LibFunc_copysignl:
348 continue; // ISD::FABS is never a library call.
352 Opcode = ISD::FSQRT; break;
356 Opcode = ISD::FFLOOR; break;
357 case LibFunc_nearbyint:
358 case LibFunc_nearbyintf:
359 case LibFunc_nearbyintl:
360 Opcode = ISD::FNEARBYINT; break;
364 Opcode = ISD::FCEIL; break;
368 Opcode = ISD::FRINT; break;
372 Opcode = ISD::FROUND; break;
376 Opcode = ISD::FTRUNC; break;
380 Opcode = ISD::FMINNUM; break;
384 Opcode = ISD::FMAXNUM; break;
389 MVT VTy = TLI->getSimpleValueType(
390 *DL, CI->getArgOperand(0)->getType(), true);
391 if (VTy == MVT::Other)
394 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
396 else if (VTy.isVector() &&
397 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
405 } else if (isa<BinaryOperator>(J) &&
406 J->getType()->getScalarType()->isPPC_FP128Ty()) {
407 // Most operations on ppc_f128 values become calls.
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() ||
414 isLargeIntegerTy(!TM->isPPC64(), CI->getSrcTy()->getScalarType()) ||
415 isLargeIntegerTy(!TM->isPPC64(), CI->getDestTy()->getScalarType()))
417 } else if (isLargeIntegerTy(!TM->isPPC64(),
418 J->getType()->getScalarType()) &&
419 (J->getOpcode() == Instruction::UDiv ||
420 J->getOpcode() == Instruction::SDiv ||
421 J->getOpcode() == Instruction::URem ||
422 J->getOpcode() == Instruction::SRem)) {
424 } else if (!TM->isPPC64() &&
425 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.
432 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
433 // On PowerPC, indirect jumps use the counter register.
435 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
436 if (SI->getNumCases() + 1 >= (unsigned)TLI->getMinimumJumpTableEntries())
440 if (STI->useSoftFloat()) {
441 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:
458 for (Value *Operand : J->operands())
459 if (memAddrUsesCTR(*TM, Operand))
466 bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
467 bool MadeChange = false;
469 // Process nested loops first.
470 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
471 MadeChange |= convertToCTRLoop(*I);
472 DEBUG(dbgs() << "Nested loop converted\n");
475 // If a nested loop has been converted, then we can't convert this loop.
480 // Stop trying after reaching the limit (if any).
481 int Limit = CTRLoopLimit;
483 if (Counter >= CTRLoopLimit)
489 // 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();
496 SmallVector<BasicBlock*, 4> ExitingBlocks;
497 L->getExitingBlocks(ExitingBlocks);
499 BasicBlock *CountedExitBlock = nullptr;
500 const SCEV *ExitCount = nullptr;
501 BranchInst *CountedExitBranch = nullptr;
502 for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
503 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))
509 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
510 if (ConstEC->getValue()->isZero())
512 } else if (!SE->isLoopInvariant(EC, L))
515 if (SE->getTypeSizeInBits(EC->getType()) > (TM->isPPC64() ? 64 : 32))
518 // 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
522 // 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))
531 if (!DT->dominates(*I, *PI)) {
540 // Make sure this blocks ends with a conditional branch.
541 Instruction *TI = (*I)->getTerminator();
545 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
546 if (!BI->isConditional())
549 CountedExitBranch = BI;
553 // Note that this block may not be the loop latch block, even if the loop
554 // has a latch block.
555 CountedExitBlock = *I;
560 if (!CountedExitBlock)
563 BasicBlock *Preheader = L->getLoopPreheader();
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).
569 if (!Preheader || mightUseCTR(Preheader))
570 Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
574 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
576 // Insert the count into the preheader and replace the condition used by the
580 SCEVExpander SCEVE(*SE, *DL, "loopcnt");
581 LLVMContext &C = SE->getContext();
582 Type *CountType = TM->isPPC64() ? Type::getInt64Ty(C) : Type::getInt32Ty(C);
583 if (!ExitCount->getType()->isPointerTy() &&
584 ExitCount->getType() != CountType)
585 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
586 ExitCount = SE->getAddExpr(ExitCount, SE->getOne(CountType));
588 SCEVE.expandCodeFor(ExitCount, CountType, Preheader->getTerminator());
590 IRBuilder<> CountBuilder(Preheader->getTerminator());
591 Module *M = Preheader->getParent()->getParent();
592 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
594 CountBuilder.CreateCall(MTCTRFunc, ECValue);
596 IRBuilder<> CondBuilder(CountedExitBranch);
598 Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
599 Value *NewCond = CondBuilder.CreateCall(DecFunc, {});
600 Value *OldCond = CountedExitBranch->getCondition();
601 CountedExitBranch->setCondition(NewCond);
603 // The false branch must exit the loop.
604 if (!L->contains(CountedExitBranch->getSuccessor(0)))
605 CountedExitBranch->swapSuccessors();
607 // The old condition may be dead now, and may have even created a dead PHI
608 // (the original induction variable).
609 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
610 DeleteDeadPHIs(CountedExitBlock);
617 static bool clobbersCTR(const MachineInstr &MI) {
618 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
619 const MachineOperand &MO = MI.getOperand(i);
621 if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
623 } else if (MO.isRegMask()) {
624 if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
632 static bool verifyCTRBranch(MachineBasicBlock *MBB,
633 MachineBasicBlock::iterator I) {
634 MachineBasicBlock::iterator BI = I;
635 SmallSet<MachineBasicBlock *, 16> Visited;
636 SmallVector<MachineBasicBlock *, 8> Preds;
639 if (I == MBB->begin()) {
651 for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
652 unsigned Opc = I->getOpcode();
653 if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
658 if (I != BI && clobbersCTR(*I)) {
659 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " (" <<
660 MBB->getFullName() << ") instruction " << *I <<
661 " clobbers CTR, invalidating " << "BB#" <<
662 BI->getParent()->getNumber() << " (" <<
663 BI->getParent()->getFullName() << ") instruction " <<
672 if (!CheckPreds && Preds.empty())
677 if (MachineFunction::iterator(MBB) == MBB->getParent()->begin()) {
678 DEBUG(dbgs() << "Unable to find a MTCTR instruction for BB#" <<
679 BI->getParent()->getNumber() << " (" <<
680 BI->getParent()->getFullName() << ") instruction " <<
685 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
686 PIE = MBB->pred_end(); PI != PIE; ++PI)
687 Preds.push_back(*PI);
691 MBB = Preds.pop_back_val();
692 if (!Visited.count(MBB)) {
693 I = MBB->getLastNonDebugInstr();
696 } while (!Preds.empty());
701 bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
702 MDT = &getAnalysis<MachineDominatorTree>();
704 // Verify that all bdnz/bdz instructions are dominated by a loop mtctr before
705 // any other instructions that might clobber the ctr register.
706 for (MachineFunction::iterator I = MF.begin(), IE = MF.end();
708 MachineBasicBlock *MBB = &*I;
709 if (!MDT->isReachableFromEntry(MBB))
712 for (MachineBasicBlock::iterator MII = MBB->getFirstTerminator(),
713 MIIE = MBB->end(); MII != MIIE; ++MII) {
714 unsigned Opc = MII->getOpcode();
715 if (Opc == PPC::BDNZ8 || Opc == PPC::BDNZ ||
716 Opc == PPC::BDZ8 || Opc == PPC::BDZ)
717 if (!verifyCTRBranch(MBB, MII))
718 llvm_unreachable("Invalid PPC CTR loop!");