1 //===------ PPCLoopPreIncPrep.cpp - Loop Pre-Inc. AM Prep. Pass -----------===//
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 file implements a pass to prepare loops for pre-increment addressing
11 // modes. Additional PHIs are created for loop induction variables used by
12 // load/store instructions so that the pre-increment forms can be used.
13 // Generically, this means transforming loops like this:
14 // for (int i = 0; i < n; ++i)
15 // array[i] = c;
16 // to look like this:
17 // T *p = array[-1];
18 // for (int i = 0; i < n; ++i)
19 // *++p = c;
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "ppc-loop-preinc-prep"
23 #include "PPC.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/DepthFirstIterator.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/CodeMetrics.h"
30 #include "llvm/Analysis/InstructionSimplify.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/ScalarEvolution.h"
33 #include "llvm/Analysis/ScalarEvolutionExpander.h"
34 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/IR/CFG.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Transforms/Scalar.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Transforms/Utils/LoopUtils.h"
47 #include "llvm/Transforms/Utils/ValueMapper.h"
48 using namespace llvm;
49
50 // By default, we limit this to creating 16 PHIs (which is a little over half
51 // of the allocatable register set).
52 static cl::opt<unsigned> MaxVars("ppc-preinc-prep-max-vars",
53 cl::Hidden, cl::init(16),
54 cl::desc("Potential PHI threshold for PPC preinc loop prep"));
55
56 namespace llvm {
57 void initializePPCLoopPreIncPrepPass(PassRegistry&);
58 }
59
60 namespace {
61
62 class PPCLoopPreIncPrep : public FunctionPass {
63 public:
64 static char ID; // Pass ID, replacement for typeid
PPCLoopPreIncPrep()65 PPCLoopPreIncPrep() : FunctionPass(ID), TM(nullptr) {
66 initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
67 }
PPCLoopPreIncPrep(PPCTargetMachine & TM)68 PPCLoopPreIncPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
69 initializePPCLoopPreIncPrepPass(*PassRegistry::getPassRegistry());
70 }
71
getAnalysisUsage(AnalysisUsage & AU) const72 void getAnalysisUsage(AnalysisUsage &AU) const override {
73 AU.addPreserved<DominatorTreeWrapperPass>();
74 AU.addRequired<LoopInfoWrapperPass>();
75 AU.addPreserved<LoopInfoWrapperPass>();
76 AU.addRequired<ScalarEvolutionWrapperPass>();
77 }
78
79 bool runOnFunction(Function &F) override;
80
81 bool runOnLoop(Loop *L);
82 void simplifyLoopLatch(Loop *L);
83 bool rotateLoop(Loop *L);
84
85 private:
86 PPCTargetMachine *TM;
87 DominatorTree *DT;
88 LoopInfo *LI;
89 ScalarEvolution *SE;
90 bool PreserveLCSSA;
91 };
92 }
93
94 char PPCLoopPreIncPrep::ID = 0;
95 static const char *name = "Prepare loop for pre-inc. addressing modes";
INITIALIZE_PASS_BEGIN(PPCLoopPreIncPrep,DEBUG_TYPE,name,false,false)96 INITIALIZE_PASS_BEGIN(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
97 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
98 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
99 INITIALIZE_PASS_END(PPCLoopPreIncPrep, DEBUG_TYPE, name, false, false)
100
101 FunctionPass *llvm::createPPCLoopPreIncPrepPass(PPCTargetMachine &TM) {
102 return new PPCLoopPreIncPrep(TM);
103 }
104
105 namespace {
106 struct BucketElement {
BucketElement__anon49494ef30211::BucketElement107 BucketElement(const SCEVConstant *O, Instruction *I) : Offset(O), Instr(I) {}
BucketElement__anon49494ef30211::BucketElement108 BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
109
110 const SCEVConstant *Offset;
111 Instruction *Instr;
112 };
113
114 struct Bucket {
Bucket__anon49494ef30211::Bucket115 Bucket(const SCEV *B, Instruction *I) : BaseSCEV(B),
116 Elements(1, BucketElement(I)) {}
117
118 const SCEV *BaseSCEV;
119 SmallVector<BucketElement, 16> Elements;
120 };
121 }
122
IsPtrInBounds(Value * BasePtr)123 static bool IsPtrInBounds(Value *BasePtr) {
124 Value *StrippedBasePtr = BasePtr;
125 while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
126 StrippedBasePtr = BC->getOperand(0);
127 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
128 return GEP->isInBounds();
129
130 return false;
131 }
132
GetPointerOperand(Value * MemI)133 static Value *GetPointerOperand(Value *MemI) {
134 if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
135 return LMemI->getPointerOperand();
136 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
137 return SMemI->getPointerOperand();
138 } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
139 if (IMemI->getIntrinsicID() == Intrinsic::prefetch)
140 return IMemI->getArgOperand(0);
141 }
142
143 return 0;
144 }
145
runOnFunction(Function & F)146 bool PPCLoopPreIncPrep::runOnFunction(Function &F) {
147 if (skipFunction(F))
148 return false;
149
150 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
151 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
152 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
153 DT = DTWP ? &DTWP->getDomTree() : nullptr;
154 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
155
156 bool MadeChange = false;
157
158 for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
159 for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
160 MadeChange |= runOnLoop(*L);
161
162 return MadeChange;
163 }
164
runOnLoop(Loop * L)165 bool PPCLoopPreIncPrep::runOnLoop(Loop *L) {
166 bool MadeChange = false;
167
168 // Only prep. the inner-most loop
169 if (!L->empty())
170 return MadeChange;
171
172 DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
173
174 BasicBlock *Header = L->getHeader();
175
176 const PPCSubtarget *ST =
177 TM ? TM->getSubtargetImpl(*Header->getParent()) : nullptr;
178
179 unsigned HeaderLoopPredCount =
180 std::distance(pred_begin(Header), pred_end(Header));
181
182 // Collect buckets of comparable addresses used by loads and stores.
183 SmallVector<Bucket, 16> Buckets;
184 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
185 I != IE; ++I) {
186 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
187 J != JE; ++J) {
188 Value *PtrValue;
189 Instruction *MemI;
190
191 if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
192 MemI = LMemI;
193 PtrValue = LMemI->getPointerOperand();
194 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
195 MemI = SMemI;
196 PtrValue = SMemI->getPointerOperand();
197 } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(J)) {
198 if (IMemI->getIntrinsicID() == Intrinsic::prefetch) {
199 MemI = IMemI;
200 PtrValue = IMemI->getArgOperand(0);
201 } else continue;
202 } else continue;
203
204 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
205 if (PtrAddrSpace)
206 continue;
207
208 // There are no update forms for Altivec vector load/stores.
209 if (ST && ST->hasAltivec() &&
210 PtrValue->getType()->getPointerElementType()->isVectorTy())
211 continue;
212
213 if (L->isLoopInvariant(PtrValue))
214 continue;
215
216 const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
217 if (const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV)) {
218 if (LARSCEV->getLoop() != L)
219 continue;
220 } else {
221 continue;
222 }
223
224 bool FoundBucket = false;
225 for (auto &B : Buckets) {
226 const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
227 if (const auto *CDiff = dyn_cast<SCEVConstant>(Diff)) {
228 B.Elements.push_back(BucketElement(CDiff, MemI));
229 FoundBucket = true;
230 break;
231 }
232 }
233
234 if (!FoundBucket) {
235 if (Buckets.size() == MaxVars)
236 return MadeChange;
237 Buckets.push_back(Bucket(LSCEV, MemI));
238 }
239 }
240 }
241
242 if (Buckets.empty())
243 return MadeChange;
244
245 BasicBlock *LoopPredecessor = L->getLoopPredecessor();
246 // If there is no loop predecessor, or the loop predecessor's terminator
247 // returns a value (which might contribute to determining the loop's
248 // iteration space), insert a new preheader for the loop.
249 if (!LoopPredecessor ||
250 !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
251 LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
252 if (LoopPredecessor)
253 MadeChange = true;
254 }
255 if (!LoopPredecessor)
256 return MadeChange;
257
258 DEBUG(dbgs() << "PIP: Found " << Buckets.size() << " buckets\n");
259
260 SmallSet<BasicBlock *, 16> BBChanged;
261 for (unsigned i = 0, e = Buckets.size(); i != e; ++i) {
262 // The base address of each bucket is transformed into a phi and the others
263 // are rewritten as offsets of that variable.
264
265 // We have a choice now of which instruction's memory operand we use as the
266 // base for the generated PHI. Always picking the first instruction in each
267 // bucket does not work well, specifically because that instruction might
268 // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
269 // the choice is somewhat arbitrary, because the backend will happily
270 // generate direct offsets from both the pre-incremented and
271 // post-incremented pointer values. Thus, we'll pick the first non-prefetch
272 // instruction in each bucket, and adjust the recurrence and other offsets
273 // accordingly.
274 for (int j = 0, je = Buckets[i].Elements.size(); j != je; ++j) {
275 if (auto *II = dyn_cast<IntrinsicInst>(Buckets[i].Elements[j].Instr))
276 if (II->getIntrinsicID() == Intrinsic::prefetch)
277 continue;
278
279 // If we'd otherwise pick the first element anyway, there's nothing to do.
280 if (j == 0)
281 break;
282
283 // If our chosen element has no offset from the base pointer, there's
284 // nothing to do.
285 if (!Buckets[i].Elements[j].Offset ||
286 Buckets[i].Elements[j].Offset->isZero())
287 break;
288
289 const SCEV *Offset = Buckets[i].Elements[j].Offset;
290 Buckets[i].BaseSCEV = SE->getAddExpr(Buckets[i].BaseSCEV, Offset);
291 for (auto &E : Buckets[i].Elements) {
292 if (E.Offset)
293 E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
294 else
295 E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
296 }
297
298 std::swap(Buckets[i].Elements[j], Buckets[i].Elements[0]);
299 break;
300 }
301
302 const SCEVAddRecExpr *BasePtrSCEV =
303 cast<SCEVAddRecExpr>(Buckets[i].BaseSCEV);
304 if (!BasePtrSCEV->isAffine())
305 continue;
306
307 DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
308 assert(BasePtrSCEV->getLoop() == L &&
309 "AddRec for the wrong loop?");
310
311 // The instruction corresponding to the Bucket's BaseSCEV must be the first
312 // in the vector of elements.
313 Instruction *MemI = Buckets[i].Elements.begin()->Instr;
314 Value *BasePtr = GetPointerOperand(MemI);
315 assert(BasePtr && "No pointer operand");
316
317 Type *I8Ty = Type::getInt8Ty(MemI->getParent()->getContext());
318 Type *I8PtrTy = Type::getInt8PtrTy(MemI->getParent()->getContext(),
319 BasePtr->getType()->getPointerAddressSpace());
320
321 const SCEV *BasePtrStartSCEV = BasePtrSCEV->getStart();
322 if (!SE->isLoopInvariant(BasePtrStartSCEV, L))
323 continue;
324
325 const SCEVConstant *BasePtrIncSCEV =
326 dyn_cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE));
327 if (!BasePtrIncSCEV)
328 continue;
329 BasePtrStartSCEV = SE->getMinusSCEV(BasePtrStartSCEV, BasePtrIncSCEV);
330 if (!isSafeToExpand(BasePtrStartSCEV, *SE))
331 continue;
332
333 DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
334
335 PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
336 MemI->hasName() ? MemI->getName() + ".phi" : "",
337 Header->getFirstNonPHI());
338
339 SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(), "pistart");
340 Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
341 LoopPredecessor->getTerminator());
342
343 // Note that LoopPredecessor might occur in the predecessor list multiple
344 // times, and we need to add it the right number of times.
345 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
346 PI != PE; ++PI) {
347 if (*PI != LoopPredecessor)
348 continue;
349
350 NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
351 }
352
353 Instruction *InsPoint = &*Header->getFirstInsertionPt();
354 GetElementPtrInst *PtrInc = GetElementPtrInst::Create(
355 I8Ty, NewPHI, BasePtrIncSCEV->getValue(),
356 MemI->hasName() ? MemI->getName() + ".inc" : "", InsPoint);
357 PtrInc->setIsInBounds(IsPtrInBounds(BasePtr));
358 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
359 PI != PE; ++PI) {
360 if (*PI == LoopPredecessor)
361 continue;
362
363 NewPHI->addIncoming(PtrInc, *PI);
364 }
365
366 Instruction *NewBasePtr;
367 if (PtrInc->getType() != BasePtr->getType())
368 NewBasePtr = new BitCastInst(PtrInc, BasePtr->getType(),
369 PtrInc->hasName() ? PtrInc->getName() + ".cast" : "", InsPoint);
370 else
371 NewBasePtr = PtrInc;
372
373 if (Instruction *IDel = dyn_cast<Instruction>(BasePtr))
374 BBChanged.insert(IDel->getParent());
375 BasePtr->replaceAllUsesWith(NewBasePtr);
376 RecursivelyDeleteTriviallyDeadInstructions(BasePtr);
377
378 // Keep track of the replacement pointer values we've inserted so that we
379 // don't generate more pointer values than necessary.
380 SmallPtrSet<Value *, 16> NewPtrs;
381 NewPtrs.insert( NewBasePtr);
382
383 for (auto I = std::next(Buckets[i].Elements.begin()),
384 IE = Buckets[i].Elements.end(); I != IE; ++I) {
385 Value *Ptr = GetPointerOperand(I->Instr);
386 assert(Ptr && "No pointer operand");
387 if (NewPtrs.count(Ptr))
388 continue;
389
390 Instruction *RealNewPtr;
391 if (!I->Offset || I->Offset->getValue()->isZero()) {
392 RealNewPtr = NewBasePtr;
393 } else {
394 Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
395 if (PtrIP && isa<Instruction>(NewBasePtr) &&
396 cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
397 PtrIP = 0;
398 else if (isa<PHINode>(PtrIP))
399 PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
400 else if (!PtrIP)
401 PtrIP = I->Instr;
402
403 GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
404 I8Ty, PtrInc, I->Offset->getValue(),
405 I->Instr->hasName() ? I->Instr->getName() + ".off" : "", PtrIP);
406 if (!PtrIP)
407 NewPtr->insertAfter(cast<Instruction>(PtrInc));
408 NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
409 RealNewPtr = NewPtr;
410 }
411
412 if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
413 BBChanged.insert(IDel->getParent());
414
415 Instruction *ReplNewPtr;
416 if (Ptr->getType() != RealNewPtr->getType()) {
417 ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
418 Ptr->hasName() ? Ptr->getName() + ".cast" : "");
419 ReplNewPtr->insertAfter(RealNewPtr);
420 } else
421 ReplNewPtr = RealNewPtr;
422
423 Ptr->replaceAllUsesWith(ReplNewPtr);
424 RecursivelyDeleteTriviallyDeadInstructions(Ptr);
425
426 NewPtrs.insert(RealNewPtr);
427 }
428
429 MadeChange = true;
430 }
431
432 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
433 I != IE; ++I) {
434 if (BBChanged.count(*I))
435 DeleteDeadPHIs(*I);
436 }
437
438 return MadeChange;
439 }
440
441