blob: 65c2a37e5d43b736d27156561208f55b9c2cbbd6 [file] [log] [blame]
Sam Parkerc5ef5022019-06-07 07:35:30 +00001//===-- HardwareLoops.cpp - Target Independent Hardware Loops --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// Insert hardware loop intrinsics into loops which are deemed profitable by
10/// the target, by querying TargetTransformInfo. A hardware loop comprises of
11/// two intrinsics: one, outside the loop, to set the loop iteration count and
12/// another, in the exit block, to decrement the counter. The decremented value
13/// can either be carried through the loop via a phi or handled in some opaque
14/// way by the target.
15///
16//===----------------------------------------------------------------------===//
17
Sam Parkerc5ef5022019-06-07 07:35:30 +000018#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/AssumptionCache.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000020#include "llvm/Analysis/LoopInfo.h"
Sjoerd Meijer92164cf2019-11-05 08:56:14 +000021#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000022#include "llvm/Analysis/ScalarEvolution.h"
Florian Hahnb8a3c342020-01-04 18:44:38 +000023#include "llvm/Analysis/ScalarEvolutionExpander.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000024#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/CodeGen/Passes.h"
26#include "llvm/CodeGen/TargetPassConfig.h"
27#include "llvm/IR/BasicBlock.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080028#include "llvm/IR/Constants.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Dominators.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000031#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Value.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080035#include "llvm/InitializePasses.h"
36#include "llvm/Pass.h"
37#include "llvm/PassRegistry.h"
38#include "llvm/PassSupport.h"
Reid Kleckner4c1a1d32019-11-14 15:15:48 -080039#include "llvm/Support/CommandLine.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Transforms/Scalar.h"
Jinsong Ji06fef0b2019-07-09 17:53:09 +000042#include "llvm/Transforms/Utils.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Jinsong Ji06fef0b2019-07-09 17:53:09 +000045#include "llvm/Transforms/Utils/LoopUtils.h"
Sam Parkerc5ef5022019-06-07 07:35:30 +000046
47#define DEBUG_TYPE "hardware-loops"
48
49#define HW_LOOPS_NAME "Hardware Loop Insertion"
50
51using namespace llvm;
52
53static cl::opt<bool>
54ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false),
55 cl::desc("Force hardware loops intrinsics to be inserted"));
56
57static cl::opt<bool>
58ForceHardwareLoopPHI(
59 "force-hardware-loop-phi", cl::Hidden, cl::init(false),
60 cl::desc("Force hardware loop counter to be updated through a phi"));
61
62static cl::opt<bool>
63ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false),
64 cl::desc("Force allowance of nested hardware loops"));
65
66static cl::opt<unsigned>
67LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1),
68 cl::desc("Set the loop decrement value"));
69
70static cl::opt<unsigned>
71CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32),
72 cl::desc("Set the loop counter bitwidth"));
73
Sam Parker9a92be12019-06-28 07:38:16 +000074static cl::opt<bool>
75ForceGuardLoopEntry(
76 "force-hardware-loop-guard", cl::Hidden, cl::init(false),
77 cl::desc("Force generation of loop guard intrinsic"));
78
Sam Parkerc5ef5022019-06-07 07:35:30 +000079STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
80
Sjoerd Meijer92164cf2019-11-05 08:56:14 +000081#ifndef NDEBUG
82static void debugHWLoopFailure(const StringRef DebugMsg,
83 Instruction *I) {
84 dbgs() << "HWLoops: " << DebugMsg;
85 if (I)
86 dbgs() << ' ' << *I;
87 else
88 dbgs() << '.';
89 dbgs() << '\n';
90}
91#endif
92
93static OptimizationRemarkAnalysis
94createHWLoopAnalysis(StringRef RemarkName, Loop *L, Instruction *I) {
95 Value *CodeRegion = L->getHeader();
96 DebugLoc DL = L->getStartLoc();
97
98 if (I) {
99 CodeRegion = I->getParent();
100 // If there is no debug location attached to the instruction, revert back to
101 // using the loop's.
102 if (I->getDebugLoc())
103 DL = I->getDebugLoc();
104 }
105
106 OptimizationRemarkAnalysis R(DEBUG_TYPE, RemarkName, DL, CodeRegion);
107 R << "hardware-loop not created: ";
108 return R;
109}
110
Sam Parkerc5ef5022019-06-07 07:35:30 +0000111namespace {
112
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000113 void reportHWLoopFailure(const StringRef Msg, const StringRef ORETag,
114 OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I = nullptr) {
115 LLVM_DEBUG(debugHWLoopFailure(Msg, I));
116 ORE->emit(createHWLoopAnalysis(ORETag, TheLoop, I) << Msg);
117 }
118
Sam Parkerc5ef5022019-06-07 07:35:30 +0000119 using TTI = TargetTransformInfo;
120
121 class HardwareLoops : public FunctionPass {
122 public:
123 static char ID;
124
125 HardwareLoops() : FunctionPass(ID) {
126 initializeHardwareLoopsPass(*PassRegistry::getPassRegistry());
127 }
128
129 bool runOnFunction(Function &F) override;
130
131 void getAnalysisUsage(AnalysisUsage &AU) const override {
132 AU.addRequired<LoopInfoWrapperPass>();
133 AU.addPreserved<LoopInfoWrapperPass>();
134 AU.addRequired<DominatorTreeWrapperPass>();
135 AU.addPreserved<DominatorTreeWrapperPass>();
136 AU.addRequired<ScalarEvolutionWrapperPass>();
137 AU.addRequired<AssumptionCacheTracker>();
138 AU.addRequired<TargetTransformInfoWrapperPass>();
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000139 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Sam Parkerc5ef5022019-06-07 07:35:30 +0000140 }
141
142 // Try to convert the given Loop into a hardware loop.
143 bool TryConvertLoop(Loop *L);
144
145 // Given that the target believes the loop to be profitable, try to
146 // convert it.
Chen Zhengc5b918d2019-06-19 01:26:31 +0000147 bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000148
149 private:
150 ScalarEvolution *SE = nullptr;
151 LoopInfo *LI = nullptr;
152 const DataLayout *DL = nullptr;
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000153 OptimizationRemarkEmitter *ORE = nullptr;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000154 const TargetTransformInfo *TTI = nullptr;
155 DominatorTree *DT = nullptr;
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000156 bool PreserveLCSSA = false;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000157 AssumptionCache *AC = nullptr;
158 TargetLibraryInfo *LibInfo = nullptr;
159 Module *M = nullptr;
160 bool MadeChange = false;
161 };
162
163 class HardwareLoop {
164 // Expand the trip count scev into a value that we can use.
Sam Parker9a92be12019-06-28 07:38:16 +0000165 Value *InitLoopCount();
Sam Parkerc5ef5022019-06-07 07:35:30 +0000166
167 // Insert the set_loop_iteration intrinsic.
Sam Parker9a92be12019-06-28 07:38:16 +0000168 void InsertIterationSetup(Value *LoopCountInit);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000169
170 // Insert the loop_decrement intrinsic.
171 void InsertLoopDec();
172
173 // Insert the loop_decrement_reg intrinsic.
174 Instruction *InsertLoopRegDec(Value *EltsRem);
175
176 // If the target requires the counter value to be updated in the loop,
177 // insert a phi to hold the value. The intended purpose is for use by
178 // loop_decrement_reg.
179 PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
180
181 // Create a new cmp, that checks the returned value of loop_decrement*,
182 // and update the exit branch to use it.
183 void UpdateBranch(Value *EltsRem);
184
185 public:
Chen Zhengc5b918d2019-06-19 01:26:31 +0000186 HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE,
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000187 const DataLayout &DL,
188 OptimizationRemarkEmitter *ORE) :
189 SE(SE), DL(DL), ORE(ORE), L(Info.L), M(L->getHeader()->getModule()),
Sam Parkerc5ef5022019-06-07 07:35:30 +0000190 ExitCount(Info.ExitCount),
191 CountType(Info.CountType),
192 ExitBranch(Info.ExitBranch),
193 LoopDecrement(Info.LoopDecrement),
Sam Parker9a92be12019-06-28 07:38:16 +0000194 UsePHICounter(Info.CounterInReg),
195 UseLoopGuard(Info.PerformEntryTest) { }
Sam Parkerc5ef5022019-06-07 07:35:30 +0000196
197 void Create();
198
199 private:
200 ScalarEvolution &SE;
201 const DataLayout &DL;
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000202 OptimizationRemarkEmitter *ORE = nullptr;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000203 Loop *L = nullptr;
204 Module *M = nullptr;
205 const SCEV *ExitCount = nullptr;
206 Type *CountType = nullptr;
207 BranchInst *ExitBranch = nullptr;
Sam Parker9a92be12019-06-28 07:38:16 +0000208 Value *LoopDecrement = nullptr;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000209 bool UsePHICounter = false;
Sam Parker9a92be12019-06-28 07:38:16 +0000210 bool UseLoopGuard = false;
211 BasicBlock *BeginBB = nullptr;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000212 };
213}
214
215char HardwareLoops::ID = 0;
216
217bool HardwareLoops::runOnFunction(Function &F) {
218 if (skipFunction(F))
219 return false;
220
221 LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
222
223 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
224 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
225 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
226 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
227 DL = &F.getParent()->getDataLayout();
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000228 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Sam Parkerc5ef5022019-06-07 07:35:30 +0000229 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
Teresa Johnson9c27b592019-09-07 03:09:36 +0000230 LibInfo = TLIP ? &TLIP->getTLI(F) : nullptr;
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000231 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000232 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
233 M = F.getParent();
234
235 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
236 Loop *L = *I;
237 if (!L->getParentLoop())
238 TryConvertLoop(L);
239 }
240
241 return MadeChange;
242}
243
244// Return true if the search should stop, which will be when an inner loop is
245// converted and the parent loop doesn't support containing a hardware loop.
246bool HardwareLoops::TryConvertLoop(Loop *L) {
247 // Process nested loops first.
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000248 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
249 if (TryConvertLoop(*I)) {
250 reportHWLoopFailure("nested hardware-loops not supported", "HWLoopNested",
251 ORE, L);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000252 return true; // Stop search.
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000253 }
Sjoerd Meijerad763752019-10-16 09:09:55 +0000254 }
255
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000256 HardwareLoopInfo HWLoopInfo(L);
257 if (!HWLoopInfo.canAnalyze(*LI)) {
258 reportHWLoopFailure("cannot analyze loop, irreducible control flow",
259 "HWLoopCannotAnalyze", ORE, L);
260 return false;
261 }
262
263 if (!ForceHardwareLoops &&
264 !TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo)) {
265 reportHWLoopFailure("it's not profitable to create a hardware-loop",
266 "HWLoopNotProfitable", ORE, L);
267 return false;
268 }
269
270 // Allow overriding of the counter width and loop decrement value.
271 if (CounterBitWidth.getNumOccurrences())
272 HWLoopInfo.CountType =
273 IntegerType::get(M->getContext(), CounterBitWidth);
274
275 if (LoopDecrement.getNumOccurrences())
276 HWLoopInfo.LoopDecrement =
277 ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
278
279 MadeChange |= TryConvertLoop(HWLoopInfo);
280 return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000281}
282
Chen Zhengc5b918d2019-06-19 01:26:31 +0000283bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) {
Sam Parkerc5ef5022019-06-07 07:35:30 +0000284
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000285 Loop *L = HWLoopInfo.L;
286 LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000287
Chen Zhengc5b918d2019-06-19 01:26:31 +0000288 if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop,
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000289 ForceHardwareLoopPHI)) {
290 // TODO: there can be many reasons a loop is not considered a
291 // candidate, so we should let isHardwareLoopCandidate fill in the
292 // reason and then report a better message here.
293 reportHWLoopFailure("loop is not a candidate", "HWLoopNoCandidate", ORE, L);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000294 return false;
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000295 }
Sam Parkerc5ef5022019-06-07 07:35:30 +0000296
Chen Zhengc5b918d2019-06-19 01:26:31 +0000297 assert(
298 (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) &&
299 "Hardware Loop must have set exit info.");
300
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000301 BasicBlock *Preheader = L->getLoopPreheader();
302
303 // If we don't have a preheader, then insert one.
304 if (!Preheader)
305 Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
306 if (!Preheader)
307 return false;
308
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000309 HardwareLoop HWLoop(HWLoopInfo, *SE, *DL, ORE);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000310 HWLoop.Create();
311 ++NumHWLoops;
312 return true;
313}
314
315void HardwareLoop::Create() {
316 LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000317
Sam Parker9a92be12019-06-28 07:38:16 +0000318 Value *LoopCountInit = InitLoopCount();
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000319 if (!LoopCountInit) {
320 reportHWLoopFailure("could not safely create a loop count expression",
321 "HWLoopNotSafe", ORE, L);
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000322 return;
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000323 }
Sam Parkerc5ef5022019-06-07 07:35:30 +0000324
Sam Parker9a92be12019-06-28 07:38:16 +0000325 InsertIterationSetup(LoopCountInit);
Sam Parkerc5ef5022019-06-07 07:35:30 +0000326
327 if (UsePHICounter || ForceHardwareLoopPHI) {
328 Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
329 Value *EltsRem = InsertPHICounter(LoopCountInit, LoopDec);
330 LoopDec->setOperand(0, EltsRem);
331 UpdateBranch(LoopDec);
332 } else
333 InsertLoopDec();
334
335 // Run through the basic blocks of the loop and see if any of them have dead
336 // PHIs that can be removed.
337 for (auto I : L->blocks())
338 DeleteDeadPHIs(I);
339}
340
Sam Parker9a92be12019-06-28 07:38:16 +0000341static bool CanGenerateTest(Loop *L, Value *Count) {
342 BasicBlock *Preheader = L->getLoopPreheader();
343 if (!Preheader->getSinglePredecessor())
344 return false;
345
346 BasicBlock *Pred = Preheader->getSinglePredecessor();
347 if (!isa<BranchInst>(Pred->getTerminator()))
348 return false;
349
350 auto *BI = cast<BranchInst>(Pred->getTerminator());
351 if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition()))
352 return false;
353
354 // Check that the icmp is checking for equality of Count and zero and that
355 // a non-zero value results in entering the loop.
356 auto ICmp = cast<ICmpInst>(BI->getCondition());
Sam Parker98722692019-07-01 08:21:28 +0000357 LLVM_DEBUG(dbgs() << " - Found condition: " << *ICmp << "\n");
Sam Parker9a92be12019-06-28 07:38:16 +0000358 if (!ICmp->isEquality())
359 return false;
360
361 auto IsCompareZero = [](ICmpInst *ICmp, Value *Count, unsigned OpIdx) {
362 if (auto *Const = dyn_cast<ConstantInt>(ICmp->getOperand(OpIdx)))
363 return Const->isZero() && ICmp->getOperand(OpIdx ^ 1) == Count;
364 return false;
365 };
366
367 if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1))
368 return false;
369
370 unsigned SuccIdx = ICmp->getPredicate() == ICmpInst::ICMP_NE ? 0 : 1;
371 if (BI->getSuccessor(SuccIdx) != Preheader)
372 return false;
373
374 return true;
375}
376
377Value *HardwareLoop::InitLoopCount() {
378 LLVM_DEBUG(dbgs() << "HWLoops: Initialising loop counter value:\n");
379 // Can we replace a conditional branch with an intrinsic that sets the
380 // loop counter and tests that is not zero?
381
Sam Parkerc5ef5022019-06-07 07:35:30 +0000382 SCEVExpander SCEVE(SE, DL, "loopcnt");
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000383 if (!ExitCount->getType()->isPointerTy() &&
384 ExitCount->getType() != CountType)
385 ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
386
387 ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
Sam Parkerc5ef5022019-06-07 07:35:30 +0000388
Sam Parker9a92be12019-06-28 07:38:16 +0000389 // If we're trying to use the 'test and set' form of the intrinsic, we need
390 // to replace a conditional branch that is controlling entry to the loop. It
391 // is likely (guaranteed?) that the preheader has an unconditional branch to
392 // the loop header, so also check if it has a single predecessor.
393 if (SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000394 SE.getZero(ExitCount->getType()))) {
395 LLVM_DEBUG(dbgs() << " - Attempting to use test.set counter.\n");
Sam Parker9a92be12019-06-28 07:38:16 +0000396 UseLoopGuard |= ForceGuardLoopEntry;
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000397 } else
Sam Parker9a92be12019-06-28 07:38:16 +0000398 UseLoopGuard = false;
399
400 BasicBlock *BB = L->getLoopPreheader();
401 if (UseLoopGuard && BB->getSinglePredecessor() &&
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000402 cast<BranchInst>(BB->getTerminator())->isUnconditional())
Sam Parker9a92be12019-06-28 07:38:16 +0000403 BB = BB->getSinglePredecessor();
Jinsong Ji06fef0b2019-07-09 17:53:09 +0000404
405 if (!isSafeToExpandAt(ExitCount, BB->getTerminator(), SE)) {
406 LLVM_DEBUG(dbgs() << "- Bailing, unsafe to expand ExitCount "
407 << *ExitCount << "\n");
408 return nullptr;
Sam Parkerc5ef5022019-06-07 07:35:30 +0000409 }
410
411 Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
412 BB->getTerminator());
Sam Parker9a92be12019-06-28 07:38:16 +0000413
414 // FIXME: We've expanded Count where we hope to insert the counter setting
415 // intrinsic. But, in the case of the 'test and set' form, we may fallback to
416 // the just 'set' form and in which case the insertion block is most likely
417 // different. It means there will be instruction(s) in a block that possibly
418 // aren't needed. The isLoopEntryGuardedByCond is trying to avoid this issue,
419 // but it's doesn't appear to work in all cases.
420
421 UseLoopGuard = UseLoopGuard && CanGenerateTest(L, Count);
422 BeginBB = UseLoopGuard ? BB : L->getLoopPreheader();
423 LLVM_DEBUG(dbgs() << " - Loop Count: " << *Count << "\n"
424 << " - Expanded Count in " << BB->getName() << "\n"
425 << " - Will insert set counter intrinsic into: "
426 << BeginBB->getName() << "\n");
Sam Parkerc5ef5022019-06-07 07:35:30 +0000427 return Count;
428}
429
Sam Parker9a92be12019-06-28 07:38:16 +0000430void HardwareLoop::InsertIterationSetup(Value *LoopCountInit) {
431 IRBuilder<> Builder(BeginBB->getTerminator());
Sam Parkerc5ef5022019-06-07 07:35:30 +0000432 Type *Ty = LoopCountInit->getType();
Sam Parker9a92be12019-06-28 07:38:16 +0000433 Intrinsic::ID ID = UseLoopGuard ?
434 Intrinsic::test_set_loop_iterations : Intrinsic::set_loop_iterations;
435 Function *LoopIter = Intrinsic::getDeclaration(M, ID, Ty);
436 Value *SetCount = Builder.CreateCall(LoopIter, LoopCountInit);
437
438 // Use the return value of the intrinsic to control the entry of the loop.
439 if (UseLoopGuard) {
440 assert((isa<BranchInst>(BeginBB->getTerminator()) &&
441 cast<BranchInst>(BeginBB->getTerminator())->isConditional()) &&
442 "Expected conditional branch");
443 auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator());
444 LoopGuard->setCondition(SetCount);
445 if (LoopGuard->getSuccessor(0) != L->getLoopPreheader())
446 LoopGuard->swapSuccessors();
447 }
448 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop counter: "
449 << *SetCount << "\n");
Sam Parkerc5ef5022019-06-07 07:35:30 +0000450}
451
452void HardwareLoop::InsertLoopDec() {
453 IRBuilder<> CondBuilder(ExitBranch);
454
455 Function *DecFunc =
456 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
457 LoopDecrement->getType());
458 Value *Ops[] = { LoopDecrement };
459 Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
460 Value *OldCond = ExitBranch->getCondition();
461 ExitBranch->setCondition(NewCond);
462
463 // The false branch must exit the loop.
464 if (!L->contains(ExitBranch->getSuccessor(0)))
465 ExitBranch->swapSuccessors();
466
467 // The old condition may be dead now, and may have even created a dead PHI
468 // (the original induction variable).
469 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
470
471 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
472}
473
474Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
475 IRBuilder<> CondBuilder(ExitBranch);
476
477 Function *DecFunc =
478 Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
479 { EltsRem->getType(), EltsRem->getType(),
480 LoopDecrement->getType()
481 });
482 Value *Ops[] = { EltsRem, LoopDecrement };
483 Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
484
485 LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
486 return cast<Instruction>(Call);
487}
488
489PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
490 BasicBlock *Preheader = L->getLoopPreheader();
491 BasicBlock *Header = L->getHeader();
492 BasicBlock *Latch = ExitBranch->getParent();
493 IRBuilder<> Builder(Header->getFirstNonPHI());
494 PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
495 Index->addIncoming(NumElts, Preheader);
496 Index->addIncoming(EltsRem, Latch);
497 LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
498 return Index;
499}
500
501void HardwareLoop::UpdateBranch(Value *EltsRem) {
502 IRBuilder<> CondBuilder(ExitBranch);
503 Value *NewCond =
504 CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
505 Value *OldCond = ExitBranch->getCondition();
506 ExitBranch->setCondition(NewCond);
507
508 // The false branch must exit the loop.
509 if (!L->contains(ExitBranch->getSuccessor(0)))
510 ExitBranch->swapSuccessors();
511
512 // The old condition may be dead now, and may have even created a dead PHI
513 // (the original induction variable).
514 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
515}
516
517INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
518INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
519INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
520INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Sjoerd Meijer92164cf2019-11-05 08:56:14 +0000521INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Sam Parkerc5ef5022019-06-07 07:35:30 +0000522INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
523
524FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }