1*0b57cec5SDimitry Andric //===-- HardwareLoops.cpp - Target Independent Hardware Loops --*- C++ -*-===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric /// \file
9*0b57cec5SDimitry Andric /// Insert hardware loop intrinsics into loops which are deemed profitable by
10*0b57cec5SDimitry Andric /// the target, by querying TargetTransformInfo. A hardware loop comprises of
11*0b57cec5SDimitry Andric /// two intrinsics: one, outside the loop, to set the loop iteration count and
12*0b57cec5SDimitry Andric /// another, in the exit block, to decrement the counter. The decremented value
13*0b57cec5SDimitry Andric /// can either be carried through the loop via a phi or handled in some opaque
14*0b57cec5SDimitry Andric /// way by the target.
15*0b57cec5SDimitry Andric ///
16*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
17*0b57cec5SDimitry Andric 
18*0b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
19*0b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
20*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
21480093f4SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
22*0b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
235ffd83dbSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
24*0b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
25*0b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
26*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
27*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
28480093f4SDimitry Andric #include "llvm/IR/Constants.h"
29*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
30*0b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
31*0b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
35480093f4SDimitry Andric #include "llvm/InitializePasses.h"
36480093f4SDimitry Andric #include "llvm/Pass.h"
37480093f4SDimitry Andric #include "llvm/PassRegistry.h"
38480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
39*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
40*0b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h"
41*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils.h"
42*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
44*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
455ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
46*0b57cec5SDimitry Andric 
47*0b57cec5SDimitry Andric #define DEBUG_TYPE "hardware-loops"
48*0b57cec5SDimitry Andric 
49*0b57cec5SDimitry Andric #define HW_LOOPS_NAME "Hardware Loop Insertion"
50*0b57cec5SDimitry Andric 
51*0b57cec5SDimitry Andric using namespace llvm;
52*0b57cec5SDimitry Andric 
53*0b57cec5SDimitry Andric static cl::opt<bool>
54*0b57cec5SDimitry Andric ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false),
55*0b57cec5SDimitry Andric                    cl::desc("Force hardware loops intrinsics to be inserted"));
56*0b57cec5SDimitry Andric 
57*0b57cec5SDimitry Andric static cl::opt<bool>
58*0b57cec5SDimitry Andric ForceHardwareLoopPHI(
59*0b57cec5SDimitry Andric   "force-hardware-loop-phi", cl::Hidden, cl::init(false),
60*0b57cec5SDimitry Andric   cl::desc("Force hardware loop counter to be updated through a phi"));
61*0b57cec5SDimitry Andric 
62*0b57cec5SDimitry Andric static cl::opt<bool>
63*0b57cec5SDimitry Andric ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false),
64*0b57cec5SDimitry Andric                 cl::desc("Force allowance of nested hardware loops"));
65*0b57cec5SDimitry Andric 
66*0b57cec5SDimitry Andric static cl::opt<unsigned>
67*0b57cec5SDimitry Andric LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1),
68*0b57cec5SDimitry Andric             cl::desc("Set the loop decrement value"));
69*0b57cec5SDimitry Andric 
70*0b57cec5SDimitry Andric static cl::opt<unsigned>
71*0b57cec5SDimitry Andric CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32),
72*0b57cec5SDimitry Andric                 cl::desc("Set the loop counter bitwidth"));
73*0b57cec5SDimitry Andric 
74*0b57cec5SDimitry Andric static cl::opt<bool>
75*0b57cec5SDimitry Andric ForceGuardLoopEntry(
76*0b57cec5SDimitry Andric   "force-hardware-loop-guard", cl::Hidden, cl::init(false),
77*0b57cec5SDimitry Andric   cl::desc("Force generation of loop guard intrinsic"));
78*0b57cec5SDimitry Andric 
79*0b57cec5SDimitry Andric STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
80*0b57cec5SDimitry Andric 
81480093f4SDimitry Andric #ifndef NDEBUG
82480093f4SDimitry Andric static void debugHWLoopFailure(const StringRef DebugMsg,
83480093f4SDimitry Andric     Instruction *I) {
84480093f4SDimitry Andric   dbgs() << "HWLoops: " << DebugMsg;
85480093f4SDimitry Andric   if (I)
86480093f4SDimitry Andric     dbgs() << ' ' << *I;
87480093f4SDimitry Andric   else
88480093f4SDimitry Andric     dbgs() << '.';
89480093f4SDimitry Andric   dbgs() << '\n';
90480093f4SDimitry Andric }
91480093f4SDimitry Andric #endif
92480093f4SDimitry Andric 
93480093f4SDimitry Andric static OptimizationRemarkAnalysis
94480093f4SDimitry Andric createHWLoopAnalysis(StringRef RemarkName, Loop *L, Instruction *I) {
95480093f4SDimitry Andric   Value *CodeRegion = L->getHeader();
96480093f4SDimitry Andric   DebugLoc DL = L->getStartLoc();
97480093f4SDimitry Andric 
98480093f4SDimitry Andric   if (I) {
99480093f4SDimitry Andric     CodeRegion = I->getParent();
100480093f4SDimitry Andric     // If there is no debug location attached to the instruction, revert back to
101480093f4SDimitry Andric     // using the loop's.
102480093f4SDimitry Andric     if (I->getDebugLoc())
103480093f4SDimitry Andric       DL = I->getDebugLoc();
104480093f4SDimitry Andric   }
105480093f4SDimitry Andric 
106480093f4SDimitry Andric   OptimizationRemarkAnalysis R(DEBUG_TYPE, RemarkName, DL, CodeRegion);
107480093f4SDimitry Andric   R << "hardware-loop not created: ";
108480093f4SDimitry Andric   return R;
109480093f4SDimitry Andric }
110480093f4SDimitry Andric 
111*0b57cec5SDimitry Andric namespace {
112*0b57cec5SDimitry Andric 
113480093f4SDimitry Andric   void reportHWLoopFailure(const StringRef Msg, const StringRef ORETag,
114480093f4SDimitry Andric       OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I = nullptr) {
115480093f4SDimitry Andric     LLVM_DEBUG(debugHWLoopFailure(Msg, I));
116480093f4SDimitry Andric     ORE->emit(createHWLoopAnalysis(ORETag, TheLoop, I) << Msg);
117480093f4SDimitry Andric   }
118480093f4SDimitry Andric 
119*0b57cec5SDimitry Andric   using TTI = TargetTransformInfo;
120*0b57cec5SDimitry Andric 
121*0b57cec5SDimitry Andric   class HardwareLoops : public FunctionPass {
122*0b57cec5SDimitry Andric   public:
123*0b57cec5SDimitry Andric     static char ID;
124*0b57cec5SDimitry Andric 
125*0b57cec5SDimitry Andric     HardwareLoops() : FunctionPass(ID) {
126*0b57cec5SDimitry Andric       initializeHardwareLoopsPass(*PassRegistry::getPassRegistry());
127*0b57cec5SDimitry Andric     }
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric     bool runOnFunction(Function &F) override;
130*0b57cec5SDimitry Andric 
131*0b57cec5SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
132*0b57cec5SDimitry Andric       AU.addRequired<LoopInfoWrapperPass>();
133*0b57cec5SDimitry Andric       AU.addPreserved<LoopInfoWrapperPass>();
134*0b57cec5SDimitry Andric       AU.addRequired<DominatorTreeWrapperPass>();
135*0b57cec5SDimitry Andric       AU.addPreserved<DominatorTreeWrapperPass>();
136*0b57cec5SDimitry Andric       AU.addRequired<ScalarEvolutionWrapperPass>();
137*0b57cec5SDimitry Andric       AU.addRequired<AssumptionCacheTracker>();
138*0b57cec5SDimitry Andric       AU.addRequired<TargetTransformInfoWrapperPass>();
139480093f4SDimitry Andric       AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
140*0b57cec5SDimitry Andric     }
141*0b57cec5SDimitry Andric 
142*0b57cec5SDimitry Andric     // Try to convert the given Loop into a hardware loop.
143*0b57cec5SDimitry Andric     bool TryConvertLoop(Loop *L);
144*0b57cec5SDimitry Andric 
145*0b57cec5SDimitry Andric     // Given that the target believes the loop to be profitable, try to
146*0b57cec5SDimitry Andric     // convert it.
147*0b57cec5SDimitry Andric     bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo);
148*0b57cec5SDimitry Andric 
149*0b57cec5SDimitry Andric   private:
150*0b57cec5SDimitry Andric     ScalarEvolution *SE = nullptr;
151*0b57cec5SDimitry Andric     LoopInfo *LI = nullptr;
152*0b57cec5SDimitry Andric     const DataLayout *DL = nullptr;
153480093f4SDimitry Andric     OptimizationRemarkEmitter *ORE = nullptr;
154*0b57cec5SDimitry Andric     const TargetTransformInfo *TTI = nullptr;
155*0b57cec5SDimitry Andric     DominatorTree *DT = nullptr;
156*0b57cec5SDimitry Andric     bool PreserveLCSSA = false;
157*0b57cec5SDimitry Andric     AssumptionCache *AC = nullptr;
158*0b57cec5SDimitry Andric     TargetLibraryInfo *LibInfo = nullptr;
159*0b57cec5SDimitry Andric     Module *M = nullptr;
160*0b57cec5SDimitry Andric     bool MadeChange = false;
161*0b57cec5SDimitry Andric   };
162*0b57cec5SDimitry Andric 
163*0b57cec5SDimitry Andric   class HardwareLoop {
164*0b57cec5SDimitry Andric     // Expand the trip count scev into a value that we can use.
165*0b57cec5SDimitry Andric     Value *InitLoopCount();
166*0b57cec5SDimitry Andric 
167*0b57cec5SDimitry Andric     // Insert the set_loop_iteration intrinsic.
168e8d8bef9SDimitry Andric     Value *InsertIterationSetup(Value *LoopCountInit);
169*0b57cec5SDimitry Andric 
170*0b57cec5SDimitry Andric     // Insert the loop_decrement intrinsic.
171*0b57cec5SDimitry Andric     void InsertLoopDec();
172*0b57cec5SDimitry Andric 
173*0b57cec5SDimitry Andric     // Insert the loop_decrement_reg intrinsic.
174*0b57cec5SDimitry Andric     Instruction *InsertLoopRegDec(Value *EltsRem);
175*0b57cec5SDimitry Andric 
176*0b57cec5SDimitry Andric     // If the target requires the counter value to be updated in the loop,
177*0b57cec5SDimitry Andric     // insert a phi to hold the value. The intended purpose is for use by
178*0b57cec5SDimitry Andric     // loop_decrement_reg.
179*0b57cec5SDimitry Andric     PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
180*0b57cec5SDimitry Andric 
181*0b57cec5SDimitry Andric     // Create a new cmp, that checks the returned value of loop_decrement*,
182*0b57cec5SDimitry Andric     // and update the exit branch to use it.
183*0b57cec5SDimitry Andric     void UpdateBranch(Value *EltsRem);
184*0b57cec5SDimitry Andric 
185*0b57cec5SDimitry Andric   public:
186*0b57cec5SDimitry Andric     HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE,
187480093f4SDimitry Andric                  const DataLayout &DL,
188480093f4SDimitry Andric                  OptimizationRemarkEmitter *ORE) :
189480093f4SDimitry Andric       SE(SE), DL(DL), ORE(ORE), L(Info.L), M(L->getHeader()->getModule()),
190e8d8bef9SDimitry Andric       TripCount(Info.TripCount),
191*0b57cec5SDimitry Andric       CountType(Info.CountType),
192*0b57cec5SDimitry Andric       ExitBranch(Info.ExitBranch),
193*0b57cec5SDimitry Andric       LoopDecrement(Info.LoopDecrement),
194*0b57cec5SDimitry Andric       UsePHICounter(Info.CounterInReg),
195*0b57cec5SDimitry Andric       UseLoopGuard(Info.PerformEntryTest) { }
196*0b57cec5SDimitry Andric 
197*0b57cec5SDimitry Andric     void Create();
198*0b57cec5SDimitry Andric 
199*0b57cec5SDimitry Andric   private:
200*0b57cec5SDimitry Andric     ScalarEvolution &SE;
201*0b57cec5SDimitry Andric     const DataLayout &DL;
202480093f4SDimitry Andric     OptimizationRemarkEmitter *ORE = nullptr;
203*0b57cec5SDimitry Andric     Loop *L                 = nullptr;
204*0b57cec5SDimitry Andric     Module *M               = nullptr;
205e8d8bef9SDimitry Andric     const SCEV *TripCount   = nullptr;
206*0b57cec5SDimitry Andric     Type *CountType         = nullptr;
207*0b57cec5SDimitry Andric     BranchInst *ExitBranch  = nullptr;
208*0b57cec5SDimitry Andric     Value *LoopDecrement    = nullptr;
209*0b57cec5SDimitry Andric     bool UsePHICounter      = false;
210*0b57cec5SDimitry Andric     bool UseLoopGuard       = false;
211*0b57cec5SDimitry Andric     BasicBlock *BeginBB     = nullptr;
212*0b57cec5SDimitry Andric   };
213*0b57cec5SDimitry Andric }
214*0b57cec5SDimitry Andric 
215*0b57cec5SDimitry Andric char HardwareLoops::ID = 0;
216*0b57cec5SDimitry Andric 
217*0b57cec5SDimitry Andric bool HardwareLoops::runOnFunction(Function &F) {
218*0b57cec5SDimitry Andric   if (skipFunction(F))
219*0b57cec5SDimitry Andric     return false;
220*0b57cec5SDimitry Andric 
221*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
222*0b57cec5SDimitry Andric 
223*0b57cec5SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
224*0b57cec5SDimitry Andric   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
225*0b57cec5SDimitry Andric   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
226*0b57cec5SDimitry Andric   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
227*0b57cec5SDimitry Andric   DL = &F.getParent()->getDataLayout();
228480093f4SDimitry Andric   ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
229*0b57cec5SDimitry Andric   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2308bcb0991SDimitry Andric   LibInfo = TLIP ? &TLIP->getTLI(F) : nullptr;
231*0b57cec5SDimitry Andric   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
232*0b57cec5SDimitry Andric   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
233*0b57cec5SDimitry Andric   M = F.getParent();
234*0b57cec5SDimitry Andric 
235*0b57cec5SDimitry Andric   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
236*0b57cec5SDimitry Andric     Loop *L = *I;
237e8d8bef9SDimitry Andric     if (L->isOutermost())
238*0b57cec5SDimitry Andric       TryConvertLoop(L);
239*0b57cec5SDimitry Andric   }
240*0b57cec5SDimitry Andric 
241*0b57cec5SDimitry Andric   return MadeChange;
242*0b57cec5SDimitry Andric }
243*0b57cec5SDimitry Andric 
244*0b57cec5SDimitry Andric // Return true if the search should stop, which will be when an inner loop is
245*0b57cec5SDimitry Andric // converted and the parent loop doesn't support containing a hardware loop.
246*0b57cec5SDimitry Andric bool HardwareLoops::TryConvertLoop(Loop *L) {
247*0b57cec5SDimitry Andric   // Process nested loops first.
2485ffd83dbSDimitry Andric   bool AnyChanged = false;
2495ffd83dbSDimitry Andric   for (Loop *SL : *L)
2505ffd83dbSDimitry Andric     AnyChanged |= TryConvertLoop(SL);
2515ffd83dbSDimitry Andric   if (AnyChanged) {
252480093f4SDimitry Andric     reportHWLoopFailure("nested hardware-loops not supported", "HWLoopNested",
253480093f4SDimitry Andric                         ORE, L);
254*0b57cec5SDimitry Andric     return true; // Stop search.
255480093f4SDimitry Andric   }
2565ffd83dbSDimitry Andric 
2575ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Loop " << L->getHeader()->getName() << "\n");
258*0b57cec5SDimitry Andric 
259*0b57cec5SDimitry Andric   HardwareLoopInfo HWLoopInfo(L);
260480093f4SDimitry Andric   if (!HWLoopInfo.canAnalyze(*LI)) {
261480093f4SDimitry Andric     reportHWLoopFailure("cannot analyze loop, irreducible control flow",
262480093f4SDimitry Andric                         "HWLoopCannotAnalyze", ORE, L);
263*0b57cec5SDimitry Andric     return false;
264480093f4SDimitry Andric   }
265*0b57cec5SDimitry Andric 
266480093f4SDimitry Andric   if (!ForceHardwareLoops &&
267480093f4SDimitry Andric       !TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo)) {
268480093f4SDimitry Andric     reportHWLoopFailure("it's not profitable to create a hardware-loop",
269480093f4SDimitry Andric                         "HWLoopNotProfitable", ORE, L);
270480093f4SDimitry Andric     return false;
271480093f4SDimitry Andric   }
272*0b57cec5SDimitry Andric 
273*0b57cec5SDimitry Andric   // Allow overriding of the counter width and loop decrement value.
274*0b57cec5SDimitry Andric   if (CounterBitWidth.getNumOccurrences())
275*0b57cec5SDimitry Andric     HWLoopInfo.CountType =
276*0b57cec5SDimitry Andric       IntegerType::get(M->getContext(), CounterBitWidth);
277*0b57cec5SDimitry Andric 
278*0b57cec5SDimitry Andric   if (LoopDecrement.getNumOccurrences())
279*0b57cec5SDimitry Andric     HWLoopInfo.LoopDecrement =
280*0b57cec5SDimitry Andric       ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
281*0b57cec5SDimitry Andric 
282*0b57cec5SDimitry Andric   MadeChange |= TryConvertLoop(HWLoopInfo);
283*0b57cec5SDimitry Andric   return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
284*0b57cec5SDimitry Andric }
285*0b57cec5SDimitry Andric 
286*0b57cec5SDimitry Andric bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) {
287*0b57cec5SDimitry Andric 
288*0b57cec5SDimitry Andric   Loop *L = HWLoopInfo.L;
289*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
290*0b57cec5SDimitry Andric 
291*0b57cec5SDimitry Andric   if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop,
292480093f4SDimitry Andric                                           ForceHardwareLoopPHI)) {
293480093f4SDimitry Andric     // TODO: there can be many reasons a loop is not considered a
294480093f4SDimitry Andric     // candidate, so we should let isHardwareLoopCandidate fill in the
295480093f4SDimitry Andric     // reason and then report a better message here.
296480093f4SDimitry Andric     reportHWLoopFailure("loop is not a candidate", "HWLoopNoCandidate", ORE, L);
297*0b57cec5SDimitry Andric     return false;
298480093f4SDimitry Andric   }
299*0b57cec5SDimitry Andric 
300*0b57cec5SDimitry Andric   assert(
301e8d8bef9SDimitry Andric       (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.TripCount) &&
302*0b57cec5SDimitry Andric       "Hardware Loop must have set exit info.");
303*0b57cec5SDimitry Andric 
304*0b57cec5SDimitry Andric   BasicBlock *Preheader = L->getLoopPreheader();
305*0b57cec5SDimitry Andric 
306*0b57cec5SDimitry Andric   // If we don't have a preheader, then insert one.
307*0b57cec5SDimitry Andric   if (!Preheader)
308*0b57cec5SDimitry Andric     Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
309*0b57cec5SDimitry Andric   if (!Preheader)
310*0b57cec5SDimitry Andric     return false;
311*0b57cec5SDimitry Andric 
312480093f4SDimitry Andric   HardwareLoop HWLoop(HWLoopInfo, *SE, *DL, ORE);
313*0b57cec5SDimitry Andric   HWLoop.Create();
314*0b57cec5SDimitry Andric   ++NumHWLoops;
315*0b57cec5SDimitry Andric   return true;
316*0b57cec5SDimitry Andric }
317*0b57cec5SDimitry Andric 
318*0b57cec5SDimitry Andric void HardwareLoop::Create() {
319*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
320*0b57cec5SDimitry Andric 
321*0b57cec5SDimitry Andric   Value *LoopCountInit = InitLoopCount();
322480093f4SDimitry Andric   if (!LoopCountInit) {
323480093f4SDimitry Andric     reportHWLoopFailure("could not safely create a loop count expression",
324480093f4SDimitry Andric                         "HWLoopNotSafe", ORE, L);
325*0b57cec5SDimitry Andric     return;
326480093f4SDimitry Andric   }
327*0b57cec5SDimitry Andric 
328e8d8bef9SDimitry Andric   Value *Setup = InsertIterationSetup(LoopCountInit);
329*0b57cec5SDimitry Andric 
330*0b57cec5SDimitry Andric   if (UsePHICounter || ForceHardwareLoopPHI) {
331*0b57cec5SDimitry Andric     Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
332e8d8bef9SDimitry Andric     Value *EltsRem = InsertPHICounter(Setup, LoopDec);
333*0b57cec5SDimitry Andric     LoopDec->setOperand(0, EltsRem);
334*0b57cec5SDimitry Andric     UpdateBranch(LoopDec);
335*0b57cec5SDimitry Andric   } else
336*0b57cec5SDimitry Andric     InsertLoopDec();
337*0b57cec5SDimitry Andric 
338*0b57cec5SDimitry Andric   // Run through the basic blocks of the loop and see if any of them have dead
339*0b57cec5SDimitry Andric   // PHIs that can be removed.
340*0b57cec5SDimitry Andric   for (auto I : L->blocks())
341*0b57cec5SDimitry Andric     DeleteDeadPHIs(I);
342*0b57cec5SDimitry Andric }
343*0b57cec5SDimitry Andric 
344*0b57cec5SDimitry Andric static bool CanGenerateTest(Loop *L, Value *Count) {
345*0b57cec5SDimitry Andric   BasicBlock *Preheader = L->getLoopPreheader();
346*0b57cec5SDimitry Andric   if (!Preheader->getSinglePredecessor())
347*0b57cec5SDimitry Andric     return false;
348*0b57cec5SDimitry Andric 
349*0b57cec5SDimitry Andric   BasicBlock *Pred = Preheader->getSinglePredecessor();
350*0b57cec5SDimitry Andric   if (!isa<BranchInst>(Pred->getTerminator()))
351*0b57cec5SDimitry Andric     return false;
352*0b57cec5SDimitry Andric 
353*0b57cec5SDimitry Andric   auto *BI = cast<BranchInst>(Pred->getTerminator());
354*0b57cec5SDimitry Andric   if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition()))
355*0b57cec5SDimitry Andric     return false;
356*0b57cec5SDimitry Andric 
357*0b57cec5SDimitry Andric   // Check that the icmp is checking for equality of Count and zero and that
358*0b57cec5SDimitry Andric   // a non-zero value results in entering the loop.
359*0b57cec5SDimitry Andric   auto ICmp = cast<ICmpInst>(BI->getCondition());
360*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << " - Found condition: " << *ICmp << "\n");
361*0b57cec5SDimitry Andric   if (!ICmp->isEquality())
362*0b57cec5SDimitry Andric     return false;
363*0b57cec5SDimitry Andric 
364*0b57cec5SDimitry Andric   auto IsCompareZero = [](ICmpInst *ICmp, Value *Count, unsigned OpIdx) {
365*0b57cec5SDimitry Andric     if (auto *Const = dyn_cast<ConstantInt>(ICmp->getOperand(OpIdx)))
366*0b57cec5SDimitry Andric       return Const->isZero() && ICmp->getOperand(OpIdx ^ 1) == Count;
367*0b57cec5SDimitry Andric     return false;
368*0b57cec5SDimitry Andric   };
369*0b57cec5SDimitry Andric 
370*0b57cec5SDimitry Andric   if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1))
371*0b57cec5SDimitry Andric     return false;
372*0b57cec5SDimitry Andric 
373*0b57cec5SDimitry Andric   unsigned SuccIdx = ICmp->getPredicate() == ICmpInst::ICMP_NE ? 0 : 1;
374*0b57cec5SDimitry Andric   if (BI->getSuccessor(SuccIdx) != Preheader)
375*0b57cec5SDimitry Andric     return false;
376*0b57cec5SDimitry Andric 
377*0b57cec5SDimitry Andric   return true;
378*0b57cec5SDimitry Andric }
379*0b57cec5SDimitry Andric 
380*0b57cec5SDimitry Andric Value *HardwareLoop::InitLoopCount() {
381*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Initialising loop counter value:\n");
382*0b57cec5SDimitry Andric   // Can we replace a conditional branch with an intrinsic that sets the
383*0b57cec5SDimitry Andric   // loop counter and tests that is not zero?
384*0b57cec5SDimitry Andric 
385*0b57cec5SDimitry Andric   SCEVExpander SCEVE(SE, DL, "loopcnt");
386*0b57cec5SDimitry Andric 
387*0b57cec5SDimitry Andric   // If we're trying to use the 'test and set' form of the intrinsic, we need
388*0b57cec5SDimitry Andric   // to replace a conditional branch that is controlling entry to the loop. It
389*0b57cec5SDimitry Andric   // is likely (guaranteed?) that the preheader has an unconditional branch to
390*0b57cec5SDimitry Andric   // the loop header, so also check if it has a single predecessor.
391e8d8bef9SDimitry Andric   if (SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, TripCount,
392e8d8bef9SDimitry Andric                                   SE.getZero(TripCount->getType()))) {
393*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " - Attempting to use test.set counter.\n");
394*0b57cec5SDimitry Andric     UseLoopGuard |= ForceGuardLoopEntry;
395*0b57cec5SDimitry Andric   } else
396*0b57cec5SDimitry Andric     UseLoopGuard = false;
397*0b57cec5SDimitry Andric 
398*0b57cec5SDimitry Andric   BasicBlock *BB = L->getLoopPreheader();
399*0b57cec5SDimitry Andric   if (UseLoopGuard && BB->getSinglePredecessor() &&
400e8d8bef9SDimitry Andric       cast<BranchInst>(BB->getTerminator())->isUnconditional()) {
401e8d8bef9SDimitry Andric     BasicBlock *Predecessor = BB->getSinglePredecessor();
402e8d8bef9SDimitry Andric     // If it's not safe to create a while loop then don't force it and create a
403e8d8bef9SDimitry Andric     // do-while loop instead
404e8d8bef9SDimitry Andric     if (!isSafeToExpandAt(TripCount, Predecessor->getTerminator(), SE))
405e8d8bef9SDimitry Andric         UseLoopGuard = false;
406e8d8bef9SDimitry Andric     else
407e8d8bef9SDimitry Andric         BB = Predecessor;
408e8d8bef9SDimitry Andric   }
409*0b57cec5SDimitry Andric 
410e8d8bef9SDimitry Andric   if (!isSafeToExpandAt(TripCount, BB->getTerminator(), SE)) {
411e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "- Bailing, unsafe to expand TripCount "
412e8d8bef9SDimitry Andric                << *TripCount << "\n");
413*0b57cec5SDimitry Andric     return nullptr;
414*0b57cec5SDimitry Andric   }
415*0b57cec5SDimitry Andric 
416e8d8bef9SDimitry Andric   Value *Count = SCEVE.expandCodeFor(TripCount, CountType,
417*0b57cec5SDimitry Andric                                      BB->getTerminator());
418*0b57cec5SDimitry Andric 
419*0b57cec5SDimitry Andric   // FIXME: We've expanded Count where we hope to insert the counter setting
420*0b57cec5SDimitry Andric   // intrinsic. But, in the case of the 'test and set' form, we may fallback to
421*0b57cec5SDimitry Andric   // the just 'set' form and in which case the insertion block is most likely
422*0b57cec5SDimitry Andric   // different. It means there will be instruction(s) in a block that possibly
423*0b57cec5SDimitry Andric   // aren't needed. The isLoopEntryGuardedByCond is trying to avoid this issue,
424*0b57cec5SDimitry Andric   // but it's doesn't appear to work in all cases.
425*0b57cec5SDimitry Andric 
426*0b57cec5SDimitry Andric   UseLoopGuard = UseLoopGuard && CanGenerateTest(L, Count);
427*0b57cec5SDimitry Andric   BeginBB = UseLoopGuard ? BB : L->getLoopPreheader();
428*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << " - Loop Count: " << *Count << "\n"
429*0b57cec5SDimitry Andric              << " - Expanded Count in " << BB->getName() << "\n"
430*0b57cec5SDimitry Andric              << " - Will insert set counter intrinsic into: "
431*0b57cec5SDimitry Andric              << BeginBB->getName() << "\n");
432*0b57cec5SDimitry Andric   return Count;
433*0b57cec5SDimitry Andric }
434*0b57cec5SDimitry Andric 
435e8d8bef9SDimitry Andric Value* HardwareLoop::InsertIterationSetup(Value *LoopCountInit) {
436*0b57cec5SDimitry Andric   IRBuilder<> Builder(BeginBB->getTerminator());
437*0b57cec5SDimitry Andric   Type *Ty = LoopCountInit->getType();
438e8d8bef9SDimitry Andric   bool UsePhi = UsePHICounter || ForceHardwareLoopPHI;
439e8d8bef9SDimitry Andric   Intrinsic::ID ID = UseLoopGuard ? Intrinsic::test_set_loop_iterations
440e8d8bef9SDimitry Andric                                   : (UsePhi ? Intrinsic::start_loop_iterations
441e8d8bef9SDimitry Andric                                            : Intrinsic::set_loop_iterations);
442*0b57cec5SDimitry Andric   Function *LoopIter = Intrinsic::getDeclaration(M, ID, Ty);
443*0b57cec5SDimitry Andric   Value *SetCount = Builder.CreateCall(LoopIter, LoopCountInit);
444*0b57cec5SDimitry Andric 
445*0b57cec5SDimitry Andric   // Use the return value of the intrinsic to control the entry of the loop.
446*0b57cec5SDimitry Andric   if (UseLoopGuard) {
447*0b57cec5SDimitry Andric     assert((isa<BranchInst>(BeginBB->getTerminator()) &&
448*0b57cec5SDimitry Andric             cast<BranchInst>(BeginBB->getTerminator())->isConditional()) &&
449*0b57cec5SDimitry Andric            "Expected conditional branch");
450*0b57cec5SDimitry Andric     auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator());
451*0b57cec5SDimitry Andric     LoopGuard->setCondition(SetCount);
452*0b57cec5SDimitry Andric     if (LoopGuard->getSuccessor(0) != L->getLoopPreheader())
453*0b57cec5SDimitry Andric       LoopGuard->swapSuccessors();
454*0b57cec5SDimitry Andric   }
455*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop counter: "
456*0b57cec5SDimitry Andric              << *SetCount << "\n");
457e8d8bef9SDimitry Andric   return UseLoopGuard ? LoopCountInit : SetCount;
458*0b57cec5SDimitry Andric }
459*0b57cec5SDimitry Andric 
460*0b57cec5SDimitry Andric void HardwareLoop::InsertLoopDec() {
461*0b57cec5SDimitry Andric   IRBuilder<> CondBuilder(ExitBranch);
462*0b57cec5SDimitry Andric 
463*0b57cec5SDimitry Andric   Function *DecFunc =
464*0b57cec5SDimitry Andric     Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
465*0b57cec5SDimitry Andric                               LoopDecrement->getType());
466*0b57cec5SDimitry Andric   Value *Ops[] = { LoopDecrement };
467*0b57cec5SDimitry Andric   Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
468*0b57cec5SDimitry Andric   Value *OldCond = ExitBranch->getCondition();
469*0b57cec5SDimitry Andric   ExitBranch->setCondition(NewCond);
470*0b57cec5SDimitry Andric 
471*0b57cec5SDimitry Andric   // The false branch must exit the loop.
472*0b57cec5SDimitry Andric   if (!L->contains(ExitBranch->getSuccessor(0)))
473*0b57cec5SDimitry Andric     ExitBranch->swapSuccessors();
474*0b57cec5SDimitry Andric 
475*0b57cec5SDimitry Andric   // The old condition may be dead now, and may have even created a dead PHI
476*0b57cec5SDimitry Andric   // (the original induction variable).
477*0b57cec5SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
478*0b57cec5SDimitry Andric 
479*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
480*0b57cec5SDimitry Andric }
481*0b57cec5SDimitry Andric 
482*0b57cec5SDimitry Andric Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
483*0b57cec5SDimitry Andric   IRBuilder<> CondBuilder(ExitBranch);
484*0b57cec5SDimitry Andric 
485*0b57cec5SDimitry Andric   Function *DecFunc =
486*0b57cec5SDimitry Andric       Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
4875ffd83dbSDimitry Andric                                 { EltsRem->getType() });
488*0b57cec5SDimitry Andric   Value *Ops[] = { EltsRem, LoopDecrement };
489*0b57cec5SDimitry Andric   Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
490*0b57cec5SDimitry Andric 
491*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
492*0b57cec5SDimitry Andric   return cast<Instruction>(Call);
493*0b57cec5SDimitry Andric }
494*0b57cec5SDimitry Andric 
495*0b57cec5SDimitry Andric PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
496*0b57cec5SDimitry Andric   BasicBlock *Preheader = L->getLoopPreheader();
497*0b57cec5SDimitry Andric   BasicBlock *Header = L->getHeader();
498*0b57cec5SDimitry Andric   BasicBlock *Latch = ExitBranch->getParent();
499*0b57cec5SDimitry Andric   IRBuilder<> Builder(Header->getFirstNonPHI());
500*0b57cec5SDimitry Andric   PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
501*0b57cec5SDimitry Andric   Index->addIncoming(NumElts, Preheader);
502*0b57cec5SDimitry Andric   Index->addIncoming(EltsRem, Latch);
503*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
504*0b57cec5SDimitry Andric   return Index;
505*0b57cec5SDimitry Andric }
506*0b57cec5SDimitry Andric 
507*0b57cec5SDimitry Andric void HardwareLoop::UpdateBranch(Value *EltsRem) {
508*0b57cec5SDimitry Andric   IRBuilder<> CondBuilder(ExitBranch);
509*0b57cec5SDimitry Andric   Value *NewCond =
510*0b57cec5SDimitry Andric     CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
511*0b57cec5SDimitry Andric   Value *OldCond = ExitBranch->getCondition();
512*0b57cec5SDimitry Andric   ExitBranch->setCondition(NewCond);
513*0b57cec5SDimitry Andric 
514*0b57cec5SDimitry Andric   // The false branch must exit the loop.
515*0b57cec5SDimitry Andric   if (!L->contains(ExitBranch->getSuccessor(0)))
516*0b57cec5SDimitry Andric     ExitBranch->swapSuccessors();
517*0b57cec5SDimitry Andric 
518*0b57cec5SDimitry Andric   // The old condition may be dead now, and may have even created a dead PHI
519*0b57cec5SDimitry Andric   // (the original induction variable).
520*0b57cec5SDimitry Andric   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
521*0b57cec5SDimitry Andric }
522*0b57cec5SDimitry Andric 
523*0b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
524*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
525*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
526*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
527480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
528*0b57cec5SDimitry Andric INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
529*0b57cec5SDimitry Andric 
530*0b57cec5SDimitry Andric FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }
531