Rename LoopSimplify.h to LoopUtils.h
[oota-llvm.git] / lib / Target / PowerPC / PPCCTRLoops.cpp
1 //===-- 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).
12 //
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.
17 //
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.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #define DEBUG_TYPE "ctrloops"
27
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/ScalarEvolutionExpander.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/InlineAsm.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/PassSupport.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/LoopUtils.h"
48 #include "llvm/Target/TargetLibraryInfo.h"
49 #include "PPCTargetMachine.h"
50 #include "PPC.h"
51
52 #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
59 #include <algorithm>
60 #include <vector>
61
62 using namespace llvm;
63
64 #ifndef NDEBUG
65 static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
66 #endif
67
68 STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
69
70 namespace llvm {
71   void initializePPCCTRLoopsPass(PassRegistry&);
72 #ifndef NDEBUG
73   void initializePPCCTRLoopsVerifyPass(PassRegistry&);
74 #endif
75 }
76
77 namespace {
78   struct PPCCTRLoops : public FunctionPass {
79
80 #ifndef NDEBUG
81     static int Counter;
82 #endif
83
84   public:
85     static char ID;
86
87     PPCCTRLoops() : FunctionPass(ID), TM(0) {
88       initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
89     }
90     PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
91       initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
92     }
93
94     virtual bool runOnFunction(Function &F);
95
96     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97       AU.addRequired<LoopInfo>();
98       AU.addPreserved<LoopInfo>();
99       AU.addRequired<DominatorTree>();
100       AU.addPreserved<DominatorTree>();
101       AU.addRequired<ScalarEvolution>();
102     }
103
104   private:
105     bool mightUseCTR(const Triple &TT, BasicBlock *BB);
106     bool convertToCTRLoop(Loop *L);
107
108   private:
109     PPCTargetMachine *TM;
110     LoopInfo *LI;
111     ScalarEvolution *SE;
112     DataLayout *TD;
113     DominatorTree *DT;
114     const TargetLibraryInfo *LibInfo;
115   };
116
117   char PPCCTRLoops::ID = 0;
118 #ifndef NDEBUG
119   int PPCCTRLoops::Counter = 0;
120 #endif
121
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
144 } // end anonymous namespace
145
146 INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
147                       false, false)
148 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
149 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
150 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
151 INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
152                     false, false)
153
154 FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
155   return new PPCCTRLoops(TM);
156 }
157
158 #ifndef NDEBUG
159 INITIALIZE_PASS_BEGIN(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
160                       "PowerPC CTR Loops Verify", false, false)
161 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
162 INITIALIZE_PASS_END(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
163                     "PowerPC CTR Loops Verify", false, false)
164
165 FunctionPass *llvm::createPPCCTRLoopsVerify() {
166   return new PPCCTRLoopsVerify();
167 }
168 #endif // NDEBUG
169
170 bool PPCCTRLoops::runOnFunction(Function &F) {
171   LI = &getAnalysis<LoopInfo>();
172   SE = &getAnalysis<ScalarEvolution>();
173   DT = &getAnalysis<DominatorTree>();
174   TD = getAnalysisIfAvailable<DataLayout>();
175   LibInfo = getAnalysisIfAvailable<TargetLibraryInfo>();
176
177   bool MadeChange = false;
178
179   for (LoopInfo::iterator I = LI->begin(), E = LI->end();
180        I != E; ++I) {
181     Loop *L = *I;
182     if (!L->getParentLoop())
183       MadeChange |= convertToCTRLoop(L);
184   }
185
186   return MadeChange;
187 }
188
189 bool PPCCTRLoops::mightUseCTR(const Triple &TT, BasicBlock *BB) {
190   for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
191        J != JE; ++J) {
192     if (CallInst *CI = dyn_cast<CallInst>(J)) {
193       if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
194         // Inline ASM is okay, unless it clobbers the ctr register.
195         InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
196         for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
197           InlineAsm::ConstraintInfo &C = CIV[i];
198           if (C.Type != InlineAsm::isInput)
199             for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
200               if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
201                 return true;
202         }
203
204         continue;
205       }
206
207       if (!TM)
208         return true;
209       const TargetLowering *TLI = TM->getTargetLowering();
210
211       if (Function *F = CI->getCalledFunction()) {
212         // Most intrinsics don't become function calls, but some might.
213         // sin, cos, exp and log are always calls.
214         unsigned Opcode;
215         if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
216           switch (F->getIntrinsicID()) {
217           default: continue;
218
219 // VisualStudio defines setjmp as _setjmp
220 #if defined(_MSC_VER) && defined(setjmp) && \
221                        !defined(setjmp_undefined_for_msvc)
222 #  pragma push_macro("setjmp")
223 #  undef setjmp
224 #  define setjmp_undefined_for_msvc
225 #endif
226
227           case Intrinsic::setjmp:
228
229 #if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
230  // let's return it to _setjmp state
231 #  pragma pop_macro("setjmp")
232 #  undef setjmp_undefined_for_msvc
233 #endif
234
235           case Intrinsic::longjmp:
236           case Intrinsic::memcpy:
237           case Intrinsic::memmove:
238           case Intrinsic::memset:
239           case Intrinsic::powi:
240           case Intrinsic::log:
241           case Intrinsic::log2:
242           case Intrinsic::log10:
243           case Intrinsic::exp:
244           case Intrinsic::exp2:
245           case Intrinsic::pow:
246           case Intrinsic::sin:
247           case Intrinsic::cos:
248             return true;
249           case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
250           case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
251           case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
252           case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
253           case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
254           case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
255           }
256         }
257
258         // PowerPC does not use [US]DIVREM or other library calls for
259         // operations on regular types which are not otherwise library calls
260         // (i.e. soft float or atomics). If adapting for targets that do,
261         // additional care is required here.
262
263         LibFunc::Func Func;
264         if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
265             LibInfo->getLibFunc(F->getName(), Func) &&
266             LibInfo->hasOptimizedCodeGen(Func)) {
267           // Non-read-only functions are never treated as intrinsics.
268           if (!CI->onlyReadsMemory())
269             return true;
270
271           // Conversion happens only for FP calls.
272           if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
273             return true;
274
275           switch (Func) {
276           default: return true;
277           case LibFunc::copysign:
278           case LibFunc::copysignf:
279           case LibFunc::copysignl:
280             continue; // ISD::FCOPYSIGN is never a library call.
281           case LibFunc::fabs:
282           case LibFunc::fabsf:
283           case LibFunc::fabsl:
284             continue; // ISD::FABS is never a library call.
285           case LibFunc::sqrt:
286           case LibFunc::sqrtf:
287           case LibFunc::sqrtl:
288             Opcode = ISD::FSQRT; break;
289           case LibFunc::floor:
290           case LibFunc::floorf:
291           case LibFunc::floorl:
292             Opcode = ISD::FFLOOR; break;
293           case LibFunc::nearbyint:
294           case LibFunc::nearbyintf:
295           case LibFunc::nearbyintl:
296             Opcode = ISD::FNEARBYINT; break;
297           case LibFunc::ceil:
298           case LibFunc::ceilf:
299           case LibFunc::ceill:
300             Opcode = ISD::FCEIL; break;
301           case LibFunc::rint:
302           case LibFunc::rintf:
303           case LibFunc::rintl:
304             Opcode = ISD::FRINT; break;
305           case LibFunc::trunc:
306           case LibFunc::truncf:
307           case LibFunc::truncl:
308             Opcode = ISD::FTRUNC; break;
309           }
310
311           MVT VTy =
312             TLI->getSimpleValueType(CI->getArgOperand(0)->getType(), true);
313           if (VTy == MVT::Other)
314             return true;
315           
316           if (TLI->isOperationLegalOrCustom(Opcode, VTy))
317             continue;
318           else if (VTy.isVector() &&
319                    TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
320             continue;
321
322           return true;
323         }
324       }
325
326       return true;
327     } else if (isa<BinaryOperator>(J) &&
328                J->getType()->getScalarType()->isPPC_FP128Ty()) {
329       // Most operations on ppc_f128 values become calls.
330       return true;
331     } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
332                isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
333       CastInst *CI = cast<CastInst>(J);
334       if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
335           CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
336           (TT.isArch32Bit() &&
337            (CI->getSrcTy()->getScalarType()->isIntegerTy(64) ||
338             CI->getDestTy()->getScalarType()->isIntegerTy(64))
339           ))
340         return true;
341     } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
342       // On PowerPC, indirect jumps use the counter register.
343       return true;
344     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
345       if (!TM)
346         return true;
347       const TargetLowering *TLI = TM->getTargetLowering();
348
349       if (TLI->supportJumpTables() &&
350           SI->getNumCases()+1 >= (unsigned) TLI->getMinimumJumpTableEntries())
351         return true;
352     }
353   }
354
355   return false;
356 }
357
358 bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
359   bool MadeChange = false;
360
361   Triple TT = Triple(L->getHeader()->getParent()->getParent()->
362                      getTargetTriple());
363   if (!TT.isArch32Bit() && !TT.isArch64Bit())
364     return MadeChange; // Unknown arch. type.
365
366   // Process nested loops first.
367   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
368     MadeChange |= convertToCTRLoop(*I);
369   }
370
371   // If a nested loop has been converted, then we can't convert this loop.
372   if (MadeChange)
373     return MadeChange;
374
375 #ifndef NDEBUG
376   // Stop trying after reaching the limit (if any).
377   int Limit = CTRLoopLimit;
378   if (Limit >= 0) {
379     if (Counter >= CTRLoopLimit)
380       return false;
381     Counter++;
382   }
383 #endif
384
385   // We don't want to spill/restore the counter register, and so we don't
386   // want to use the counter register if the loop contains calls.
387   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
388        I != IE; ++I)
389     if (mightUseCTR(TT, *I))
390       return MadeChange;
391
392   SmallVector<BasicBlock*, 4> ExitingBlocks;
393   L->getExitingBlocks(ExitingBlocks);
394
395   BasicBlock *CountedExitBlock = 0;
396   const SCEV *ExitCount = 0;
397   BranchInst *CountedExitBranch = 0;
398   for (SmallVector<BasicBlock*, 4>::iterator I = ExitingBlocks.begin(),
399        IE = ExitingBlocks.end(); I != IE; ++I) {
400     const SCEV *EC = SE->getExitCount(L, *I);
401     DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
402                     (*I)->getName() << ": " << *EC << "\n");
403     if (isa<SCEVCouldNotCompute>(EC))
404       continue;
405     if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
406       if (ConstEC->getValue()->isZero())
407         continue;
408     } else if (!SE->isLoopInvariant(EC, L))
409       continue;
410
411     // We now have a loop-invariant count of loop iterations (which is not the
412     // constant zero) for which we know that this loop will not exit via this
413     // exisiting block.
414
415     // We need to make sure that this block will run on every loop iteration.
416     // For this to be true, we must dominate all blocks with backedges. Such
417     // blocks are in-loop predecessors to the header block.
418     bool NotAlways = false;
419     for (pred_iterator PI = pred_begin(L->getHeader()),
420          PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
421       if (!L->contains(*PI))
422         continue;
423
424       if (!DT->dominates(*I, *PI)) {
425         NotAlways = true;
426         break;
427       }
428     }
429
430     if (NotAlways)
431       continue;
432
433     // Make sure this blocks ends with a conditional branch.
434     Instruction *TI = (*I)->getTerminator();
435     if (!TI)
436       continue;
437
438     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
439       if (!BI->isConditional())
440         continue;
441
442       CountedExitBranch = BI;
443     } else
444       continue;
445
446     // Note that this block may not be the loop latch block, even if the loop
447     // has a latch block.
448     CountedExitBlock = *I;
449     ExitCount = EC;
450     break;
451   }
452
453   if (!CountedExitBlock)
454     return MadeChange;
455
456   BasicBlock *Preheader = L->getLoopPreheader();
457
458   // If we don't have a preheader, then insert one. If we already have a
459   // preheader, then we can use it (except if the preheader contains a use of
460   // the CTR register because some such uses might be reordered by the
461   // selection DAG after the mtctr instruction).
462   if (!Preheader || mightUseCTR(TT, Preheader))
463     Preheader = InsertPreheaderForLoop(L, this);
464   if (!Preheader)
465     return MadeChange;
466
467   DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
468
469   // Insert the count into the preheader and replace the condition used by the
470   // selected branch.
471   MadeChange = true;
472
473   SCEVExpander SCEVE(*SE, "loopcnt");
474   LLVMContext &C = SE->getContext();
475   Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(C) :
476                                        Type::getInt32Ty(C);
477   if (!ExitCount->getType()->isPointerTy() &&
478       ExitCount->getType() != CountType)
479     ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
480   ExitCount = SE->getAddExpr(ExitCount,
481                              SE->getConstant(CountType, 1)); 
482   Value *ECValue = SCEVE.expandCodeFor(ExitCount, CountType,
483                                        Preheader->getTerminator());
484
485   IRBuilder<> CountBuilder(Preheader->getTerminator());
486   Module *M = Preheader->getParent()->getParent();
487   Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
488                                                CountType);
489   CountBuilder.CreateCall(MTCTRFunc, ECValue);
490
491   IRBuilder<> CondBuilder(CountedExitBranch);
492   Value *DecFunc =
493     Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
494   Value *NewCond = CondBuilder.CreateCall(DecFunc);
495   Value *OldCond = CountedExitBranch->getCondition();
496   CountedExitBranch->setCondition(NewCond);
497
498   // The false branch must exit the loop.
499   if (!L->contains(CountedExitBranch->getSuccessor(0)))
500     CountedExitBranch->swapSuccessors();
501
502   // The old condition may be dead now, and may have even created a dead PHI
503   // (the original induction variable).
504   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
505   DeleteDeadPHIs(CountedExitBlock);
506
507   ++NumCTRLoops;
508   return MadeChange;
509 }
510
511 #ifndef NDEBUG
512 static bool clobbersCTR(const MachineInstr *MI) {
513   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
514     const MachineOperand &MO = MI->getOperand(i);
515     if (MO.isReg()) {
516       if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
517         return true;
518     } else if (MO.isRegMask()) {
519       if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
520         return true;
521     }
522   }
523
524   return false;
525 }
526
527 static bool verifyCTRBranch(MachineBasicBlock *MBB,
528                             MachineBasicBlock::iterator I) {
529   MachineBasicBlock::iterator BI = I;
530   SmallSet<MachineBasicBlock *, 16>   Visited;
531   SmallVector<MachineBasicBlock *, 8> Preds;
532   bool CheckPreds;
533
534   if (I == MBB->begin()) {
535     Visited.insert(MBB);
536     goto queue_preds;
537   } else
538     --I;
539
540 check_block:
541   Visited.insert(MBB);
542   if (I == MBB->end())
543     goto queue_preds;
544
545   CheckPreds = true;
546   for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
547     unsigned Opc = I->getOpcode();
548     if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
549       CheckPreds = false;
550       break;
551     }
552
553     if (I != BI && clobbersCTR(I)) {
554       DEBUG(dbgs() << "BB#" << MBB->getNumber() << " (" <<
555                       MBB->getFullName() << ") instruction " << *I <<
556                       " clobbers CTR, invalidating " << "BB#" <<
557                       BI->getParent()->getNumber() << " (" <<
558                       BI->getParent()->getFullName() << ") instruction " <<
559                       *BI << "\n");
560       return false;
561     }
562
563     if (I == IE)
564       break;
565   }
566
567   if (!CheckPreds && Preds.empty())
568     return true;
569
570   if (CheckPreds) {
571 queue_preds:
572     if (MachineFunction::iterator(MBB) == MBB->getParent()->begin()) {
573       DEBUG(dbgs() << "Unable to find a MTCTR instruction for BB#" <<
574                       BI->getParent()->getNumber() << " (" <<
575                       BI->getParent()->getFullName() << ") instruction " <<
576                       *BI << "\n");
577       return false;
578     }
579
580     for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
581          PIE = MBB->pred_end(); PI != PIE; ++PI)
582       Preds.push_back(*PI);
583   }
584
585   do {
586     MBB = Preds.pop_back_val();
587     if (!Visited.count(MBB)) {
588       I = MBB->getLastNonDebugInstr();
589       goto check_block;
590     }
591   } while (!Preds.empty());
592
593   return true;
594 }
595
596 bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
597   MDT = &getAnalysis<MachineDominatorTree>();
598
599   // Verify that all bdnz/bdz instructions are dominated by a loop mtctr before
600   // any other instructions that might clobber the ctr register.
601   for (MachineFunction::iterator I = MF.begin(), IE = MF.end();
602        I != IE; ++I) {
603     MachineBasicBlock *MBB = I;
604     if (!MDT->isReachableFromEntry(MBB))
605       continue;
606
607     for (MachineBasicBlock::iterator MII = MBB->getFirstTerminator(),
608       MIIE = MBB->end(); MII != MIIE; ++MII) {
609       unsigned Opc = MII->getOpcode();
610       if (Opc == PPC::BDNZ8 || Opc == PPC::BDNZ ||
611           Opc == PPC::BDZ8  || Opc == PPC::BDZ)
612         if (!verifyCTRBranch(MBB, MII))
613           llvm_unreachable("Invalid PPC CTR loop!");
614     }
615   }
616
617   return false;
618 }
619 #endif // NDEBUG
620