LLVM 24.0.0git
PPCLoopInstrFormPrep.cpp
Go to the documentation of this file.
1//===------ PPCLoopInstrFormPrep.cpp - Loop Instr Form Prep Pass ----------===//
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//
9// This file implements a pass to prepare loops for ppc preferred addressing
10// modes, leveraging different instruction form. (eg: DS/DQ form, D/DS form with
11// update)
12// Additional PHIs are created for loop induction variables used by load/store
13// instructions so that preferred addressing modes can be used.
14//
15// 1: DS/DQ form preparation, prepare the load/store instructions so that they
16// can satisfy the DS/DQ form displacement requirements.
17// Generically, this means transforming loops like this:
18// for (int i = 0; i < n; ++i) {
19// unsigned long x1 = *(unsigned long *)(p + i + 5);
20// unsigned long x2 = *(unsigned long *)(p + i + 9);
21// }
22//
23// to look like this:
24//
25// unsigned NewP = p + 5;
26// for (int i = 0; i < n; ++i) {
27// unsigned long x1 = *(unsigned long *)(i + NewP);
28// unsigned long x2 = *(unsigned long *)(i + NewP + 4);
29// }
30//
31// 2: D/DS form with update preparation, prepare the load/store instructions so
32// that we can use update form to do pre-increment.
33// Generically, this means transforming loops like this:
34// for (int i = 0; i < n; ++i)
35// array[i] = c;
36//
37// to look like this:
38//
39// T *p = array[-1];
40// for (int i = 0; i < n; ++i)
41// *++p = c;
42//
43// 3: common multiple chains for the load/stores with same offsets in the loop,
44// so that we can reuse the offsets and reduce the register pressure in the
45// loop. This transformation can also increase the loop ILP as now each chain
46// uses its own loop induction add/addi. But this will increase the number of
47// add/addi in the loop.
48//
49// Generically, this means transforming loops like this:
50//
51// char *p;
52// A1 = p + base1
53// A2 = p + base1 + offset
54// B1 = p + base2
55// B2 = p + base2 + offset
56//
57// for (int i = 0; i < n; i++)
58// unsigned long x1 = *(unsigned long *)(A1 + i);
59// unsigned long x2 = *(unsigned long *)(A2 + i)
60// unsigned long x3 = *(unsigned long *)(B1 + i);
61// unsigned long x4 = *(unsigned long *)(B2 + i);
62// }
63//
64// to look like this:
65//
66// A1_new = p + base1 // chain 1
67// B1_new = p + base2 // chain 2, now inside the loop, common offset is
68// // reused.
69//
70// for (long long i = 0; i < n; i+=count) {
71// unsigned long x1 = *(unsigned long *)(A1_new + i);
72// unsigned long x2 = *(unsigned long *)((A1_new + i) + offset);
73// unsigned long x3 = *(unsigned long *)(B1_new + i);
74// unsigned long x4 = *(unsigned long *)((B1_new + i) + offset);
75// }
76//===----------------------------------------------------------------------===//
77
78#include "PPC.h"
79#include "PPCSubtarget.h"
80#include "PPCTargetMachine.h"
84#include "llvm/ADT/Statistic.h"
88#include "llvm/IR/BasicBlock.h"
89#include "llvm/IR/CFG.h"
90#include "llvm/IR/Dominators.h"
91#include "llvm/IR/Instruction.h"
94#include "llvm/IR/IntrinsicsPowerPC.h"
95#include "llvm/IR/Type.h"
96#include "llvm/IR/Value.h"
98#include "llvm/Pass.h"
100#include "llvm/Support/Debug.h"
107#include <cassert>
108#include <cmath>
109#include <utility>
110
111#define DEBUG_TYPE "ppc-loop-instr-form-prep"
112
113using namespace llvm;
114
115STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
116STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
117STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
118STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
119STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
120STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
121STATISTIC(ChainCommoningRewritten, "Num of commoning chains");
122
123namespace {
124 struct BucketElement {
125 BucketElement(const SCEV *O, Instruction *I) : Offset(O), Instr(I) {}
126 BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
127
128 const SCEV *Offset;
129 Instruction *Instr;
130 };
131
132 struct Bucket {
133 Bucket(const SCEV *B, Instruction *I)
134 : BaseSCEV(B), Elements(1, BucketElement(I)) {
135 ChainSize = 0;
136 }
137
138 // The base of the whole bucket.
139 const SCEV *BaseSCEV;
140
141 // All elements in the bucket. In the bucket, the element with the BaseSCEV
142 // has no offset and all other elements are stored as offsets to the
143 // BaseSCEV.
145
146 // The potential chains size. This is used for chain commoning only.
147 unsigned ChainSize;
148
149 // The base for each potential chain. This is used for chain commoning only.
151 };
152
153 // "UpdateForm" is not a real PPC instruction form, it stands for dform
154 // load/store with update like ldu/stdu, or Prefetch intrinsic.
155 // For DS form instructions, their displacements must be multiple of 4.
156 // For DQ form instructions, their displacements must be multiple of 16.
157 enum PrepForm { UpdateForm = 1, DSForm = 4, DQForm = 16, ChainCommoning };
158
159 class PPCLoopInstrFormPrep : public FunctionPass {
160 public:
161 static char ID; // Pass ID, replacement for typeid
162
163 PPCLoopInstrFormPrep(PPCTargetMachine &TM)
164 : FunctionPass(ID), CLOpts(TM.getCLOpts()), TM(&TM) {}
165
166 void getAnalysisUsage(AnalysisUsage &AU) const override {
167 AU.addPreserved<DominatorTreeWrapperPass>();
168 AU.addRequired<LoopInfoWrapperPass>();
169 AU.addPreserved<LoopInfoWrapperPass>();
170 AU.addRequired<ScalarEvolutionWrapperPass>();
171 }
172
173 bool runOnFunction(Function &F) override;
174
175 private:
176 const PPCOptions &CLOpts;
177 PPCTargetMachine *TM = nullptr;
178 const PPCSubtarget *ST;
179 DominatorTree *DT;
180 LoopInfo *LI;
181 ScalarEvolution *SE;
182 bool PreserveLCSSA;
183 bool HasCandidateForPrepare;
184
185 /// Successful preparation number for Update/DS/DQ form in all inner most
186 /// loops. One successful preparation will put one common base out of loop,
187 /// this may leads to register presure like LICM does.
188 /// Make sure total preparation number can be controlled by option.
189 unsigned SuccPrepCount;
190
191 bool runOnLoop(Loop *L);
192
193 /// Check if required PHI node is already exist in Loop \p L.
194 bool alreadyPrepared(Loop *L, Instruction *MemI,
195 const SCEV *BasePtrStartSCEV,
196 const SCEV *BasePtrIncSCEV, PrepForm Form);
197
198 /// Get the value which defines the increment SCEV \p BasePtrIncSCEV.
199 Value *getNodeForInc(Loop *L, Instruction *MemI,
200 const SCEV *BasePtrIncSCEV);
201
202 /// Common chains to reuse offsets for a loop to reduce register pressure.
203 bool chainCommoning(Loop *L, SmallVector<Bucket, 16> &Buckets);
204
205 /// Find out the potential commoning chains and their bases.
206 bool prepareBasesForCommoningChains(Bucket &BucketChain);
207
208 /// Rewrite load/store according to the common chains.
209 bool rewriteLoadStoresForCommoningChains(
210 Loop *L, Bucket &Bucket, SmallPtrSet<BasicBlock *, 16> &BBChanged);
211
212 /// Collect condition matched(\p isValidCandidate() returns true)
213 /// candidates in Loop \p L.
214 SmallVector<Bucket, 16> collectCandidates(
215 Loop *L,
216 std::function<bool(const Instruction *, Value *, const Type *)>
217 isValidCandidate,
218 std::function<bool(const SCEV *)> isValidDiff,
219 unsigned MaxCandidateNum);
220
221 /// Add a candidate to candidates \p Buckets if diff between candidate and
222 /// one base in \p Buckets matches \p isValidDiff.
223 void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
225 std::function<bool(const SCEV *)> isValidDiff,
226 unsigned MaxCandidateNum);
227
228 /// Prepare all candidates in \p Buckets for update form.
229 bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
230
231 /// Prepare all candidates in \p Buckets for displacement form, now for
232 /// ds/dq.
233 bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets, PrepForm Form);
234
235 /// Prepare for one chain \p BucketChain, find the best base element and
236 /// update all other elements in \p BucketChain accordingly.
237 /// \p Form is used to find the best base element.
238 /// If success, best base element must be stored as the first element of
239 /// \p BucketChain.
240 /// Return false if no base element found, otherwise return true.
241 bool prepareBaseForDispFormChain(Bucket &BucketChain, PrepForm Form);
242
243 /// Prepare for one chain \p BucketChain, find the best base element and
244 /// update all other elements in \p BucketChain accordingly.
245 /// If success, best base element must be stored as the first element of
246 /// \p BucketChain.
247 /// Return false if no base element found, otherwise return true.
248 bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
249
250 /// Rewrite load/store instructions in \p BucketChain according to
251 /// preparation.
252 bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
253 SmallPtrSet<BasicBlock *, 16> &BBChanged,
254 PrepForm Form);
255
256 /// Rewrite for the base load/store of a chain.
257 std::pair<Instruction *, Instruction *>
258 rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
259 Instruction *BaseMemI, bool CanPreInc, PrepForm Form,
260 SCEVExpander &SCEVE, SmallPtrSet<Value *, 16> &DeletedPtrs);
261
262 /// Rewrite for the other load/stores of a chain according to the new \p
263 /// Base.
265 rewriteForBucketElement(std::pair<Instruction *, Instruction *> Base,
266 const BucketElement &Element, Value *OffToBase,
267 SmallPtrSet<Value *, 16> &DeletedPtrs);
268 };
269
270} // end anonymous namespace
271
272char PPCLoopInstrFormPrep::ID = 0;
273static const char *name = "Prepare loop for ppc preferred instruction forms";
274INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
277INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
278
279static constexpr StringRef PHINodeNameSuffix = ".phi";
280static constexpr StringRef CastNodeNameSuffix = ".cast";
281static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
282static constexpr StringRef GEPNodeOffNameSuffix = ".off";
283
285 return new PPCLoopInstrFormPrep(TM);
286}
287
288static bool IsPtrInBounds(Value *BasePtr) {
289 Value *StrippedBasePtr = BasePtr;
290 while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
291 StrippedBasePtr = BC->getOperand(0);
292 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
293 return GEP->isInBounds();
294
295 return false;
296}
297
298static std::string getInstrName(const Value *I, StringRef Suffix) {
299 assert(I && "Invalid paramater!");
300 if (I->hasName())
301 return (I->getName() + Suffix).str();
302 else
303 return "";
304}
305
307 Type **PtrElementType = nullptr) {
308
309 Value *PtrValue = nullptr;
310 Type *PointerElementType = nullptr;
311
312 if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
313 PtrValue = LMemI->getPointerOperand();
314 PointerElementType = LMemI->getType();
315 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
316 PtrValue = SMemI->getPointerOperand();
317 PointerElementType = SMemI->getValueOperand()->getType();
318 } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
319 PointerElementType = Type::getInt8Ty(MemI->getContext());
320 if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
321 IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
322 PtrValue = IMemI->getArgOperand(0);
323 } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
324 PtrValue = IMemI->getArgOperand(1);
325 }
326 }
327 /*Get ElementType if PtrElementType is not null.*/
328 if (PtrElementType)
329 *PtrElementType = PointerElementType;
330
331 return PtrValue;
332}
333
334bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
335 if (skipFunction(F))
336 return false;
337
338 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
339 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
340 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
341 DT = DTWP ? &DTWP->getDomTree() : nullptr;
342 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
343 ST = TM ? TM->getSubtargetImpl(F) : nullptr;
344 SuccPrepCount = 0;
345
346 bool MadeChange = false;
347
348 for (Loop *I : *LI)
349 for (Loop *L : depth_first(I))
350 MadeChange |= runOnLoop(L);
351
352 return MadeChange;
353}
354
355// Finding the minimal(chain_number + reusable_offset_number) is a complicated
356// algorithmic problem.
357// For now, the algorithm used here is simply adjusted to handle the case for
358// manually unrolling cases.
359// FIXME: use a more powerful algorithm to find minimal sum of chain_number and
360// reusable_offset_number for one base with multiple offsets.
361bool PPCLoopInstrFormPrep::prepareBasesForCommoningChains(Bucket &CBucket) {
362 // The minimal size for profitable chain commoning:
363 // A1 = base + offset1
364 // A2 = base + offset2 (offset2 - offset1 = X)
365 // A3 = base + offset3
366 // A4 = base + offset4 (offset4 - offset3 = X)
367 // ======>
368 // base1 = base + offset1
369 // base2 = base + offset3
370 // A1 = base1
371 // A2 = base1 + X
372 // A3 = base2
373 // A4 = base2 + X
374 //
375 // There is benefit because of reuse of offest 'X'.
376
377 assert(CLOpts.chaincommon_min_threshold >= 4 &&
378 "Thredhold can not be smaller than 4!\n");
379 if (CBucket.Elements.size() < CLOpts.chaincommon_min_threshold)
380 return false;
381
382 // We simply select the FirstOffset as the first reusable offset between each
383 // chain element 1 and element 0.
384 const SCEV *FirstOffset = CBucket.Elements[1].Offset;
385
386 // Figure out how many times above FirstOffset is used in the chain.
387 // For a success commoning chain candidate, offset difference between each
388 // chain element 1 and element 0 must be also FirstOffset.
389 unsigned FirstOffsetReusedCount = 1;
390
391 // Figure out how many times above FirstOffset is used in the first chain.
392 // Chain number is FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain
393 unsigned FirstOffsetReusedCountInFirstChain = 1;
394
395 unsigned EleNum = CBucket.Elements.size();
396 bool SawChainSeparater = false;
397 for (unsigned j = 2; j != EleNum; ++j) {
398 if (SE->getMinusSCEV(CBucket.Elements[j].Offset,
399 CBucket.Elements[j - 1].Offset) == FirstOffset) {
400 if (!SawChainSeparater)
401 FirstOffsetReusedCountInFirstChain++;
402 FirstOffsetReusedCount++;
403 } else
404 // For now, if we meet any offset which is not FirstOffset, we assume we
405 // find a new Chain.
406 // This makes us miss some opportunities.
407 // For example, we can common:
408 //
409 // {OffsetA, Offset A, OffsetB, OffsetA, OffsetA, OffsetB}
410 //
411 // as two chains:
412 // {{OffsetA, Offset A, OffsetB}, {OffsetA, OffsetA, OffsetB}}
413 // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 2
414 //
415 // But we fail to common:
416 //
417 // {OffsetA, OffsetB, OffsetA, OffsetA, OffsetB, OffsetA}
418 // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 1
419
420 SawChainSeparater = true;
421 }
422
423 // FirstOffset is not reused, skip this bucket.
424 if (FirstOffsetReusedCount == 1)
425 return false;
426
427 unsigned ChainNum =
428 FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain;
429
430 // All elements are increased by FirstOffset.
431 // The number of chains should be sqrt(EleNum).
432 if (!SawChainSeparater)
433 ChainNum = (unsigned)sqrt((double)EleNum);
434
435 CBucket.ChainSize = (unsigned)(EleNum / ChainNum);
436
437 // If this is not a perfect chain(eg: not all elements can be put inside
438 // commoning chains.), skip now.
439 if (CBucket.ChainSize * ChainNum != EleNum)
440 return false;
441
442 if (SawChainSeparater) {
443 // Check that the offset seqs are the same for all chains.
444 for (unsigned i = 1; i < CBucket.ChainSize; i++)
445 for (unsigned j = 1; j < ChainNum; j++)
446 if (CBucket.Elements[i].Offset !=
447 SE->getMinusSCEV(CBucket.Elements[i + j * CBucket.ChainSize].Offset,
448 CBucket.Elements[j * CBucket.ChainSize].Offset))
449 return false;
450 }
451
452 for (unsigned i = 0; i < ChainNum; i++)
453 CBucket.ChainBases.push_back(CBucket.Elements[i * CBucket.ChainSize]);
454
455 LLVM_DEBUG(dbgs() << "Bucket has " << ChainNum << " chains.\n");
456
457 return true;
458}
459
460bool PPCLoopInstrFormPrep::chainCommoning(Loop *L,
461 SmallVector<Bucket, 16> &Buckets) {
462 bool MadeChange = false;
463
464 if (Buckets.empty())
465 return MadeChange;
466
467 SmallPtrSet<BasicBlock *, 16> BBChanged;
468
469 for (auto &Bucket : Buckets) {
470 if (prepareBasesForCommoningChains(Bucket))
471 MadeChange |= rewriteLoadStoresForCommoningChains(L, Bucket, BBChanged);
472 }
473
474 if (MadeChange)
475 for (auto *BB : BBChanged)
476 DeleteDeadPHIs(BB);
477 return MadeChange;
478}
479
480bool PPCLoopInstrFormPrep::rewriteLoadStoresForCommoningChains(
481 Loop *L, Bucket &Bucket, SmallPtrSet<BasicBlock *, 16> &BBChanged) {
482 bool MadeChange = false;
483
484 assert(Bucket.Elements.size() ==
485 Bucket.ChainBases.size() * Bucket.ChainSize &&
486 "invalid bucket for chain commoning!\n");
487 SmallPtrSet<Value *, 16> DeletedPtrs;
488
489 BasicBlock *LoopPredecessor = L->getLoopPredecessor();
490
491 SCEVExpander SCEVE(*SE, "loopprepare-chaincommon");
492
493 for (unsigned ChainIdx = 0; ChainIdx < Bucket.ChainBases.size(); ++ChainIdx) {
494 unsigned BaseElemIdx = Bucket.ChainSize * ChainIdx;
495 const SCEV *BaseSCEV =
496 ChainIdx ? SE->getAddExpr(Bucket.BaseSCEV,
497 Bucket.Elements[BaseElemIdx].Offset)
498 .getPointer()
499 : Bucket.BaseSCEV;
500 const SCEVAddRecExpr *BasePtrSCEV = cast<SCEVAddRecExpr>(BaseSCEV);
501
502 // Make sure the base is able to expand.
503 if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
504 return MadeChange;
505
506 assert(BasePtrSCEV->isAffine() &&
507 "Invalid SCEV type for the base ptr for a candidate chain!\n");
508
509 std::pair<Instruction *, Instruction *> Base = rewriteForBase(
510 L, BasePtrSCEV, Bucket.Elements[BaseElemIdx].Instr,
511 false /* CanPreInc */, ChainCommoning, SCEVE, DeletedPtrs);
512
513 if (!Base.first || !Base.second)
514 return MadeChange;
515
516 // Keep track of the replacement pointer values we've inserted so that we
517 // don't generate more pointer values than necessary.
518 SmallPtrSet<Value *, 16> NewPtrs;
519 NewPtrs.insert(Base.first);
520
521 for (unsigned Idx = BaseElemIdx + 1; Idx < BaseElemIdx + Bucket.ChainSize;
522 ++Idx) {
523 BucketElement &I = Bucket.Elements[Idx];
524 Value *Ptr = getPointerOperandAndType(I.Instr);
525 assert(Ptr && "No pointer operand");
526 if (NewPtrs.count(Ptr))
527 continue;
528
529 const SCEV *OffsetSCEV =
530 BaseElemIdx ? SE->getMinusSCEV(Bucket.Elements[Idx].Offset,
531 Bucket.Elements[BaseElemIdx].Offset)
532 : Bucket.Elements[Idx].Offset;
533
534 // Make sure offset is able to expand. Only need to check one time as the
535 // offsets are reused between different chains.
536 if (!BaseElemIdx)
537 if (!SCEVE.isSafeToExpand(OffsetSCEV))
538 return false;
539
540 Value *OffsetValue = SCEVE.expandCodeFor(
541 OffsetSCEV, OffsetSCEV->getType(), LoopPredecessor->getTerminator());
542
543 Instruction *NewPtr = rewriteForBucketElement(Base, Bucket.Elements[Idx],
544 OffsetValue, DeletedPtrs);
545
546 assert(NewPtr && "Wrong rewrite!\n");
547 NewPtrs.insert(NewPtr);
548 }
549
550 ++ChainCommoningRewritten;
551 }
552
553 // Clear the rewriter cache, because values that are in the rewriter's cache
554 // can be deleted below, causing the AssertingVH in the cache to trigger.
555 SCEVE.clear();
556
557 for (auto *Ptr : DeletedPtrs) {
558 if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
559 BBChanged.insert(IDel->getParent());
561 }
562
563 MadeChange = true;
564 return MadeChange;
565}
566
567// Rewrite the new base according to BasePtrSCEV.
568// bb.loop.preheader:
569// %newstart = ...
570// bb.loop.body:
571// %phinode = phi [ %newstart, %bb.loop.preheader ], [ %add, %bb.loop.body ]
572// ...
573// %add = getelementptr %phinode, %inc
574//
575// First returned instruction is %phinode (or a type cast to %phinode), caller
576// needs this value to rewrite other load/stores in the same chain.
577// Second returned instruction is %add, caller needs this value to rewrite other
578// load/stores in the same chain.
579std::pair<Instruction *, Instruction *>
580PPCLoopInstrFormPrep::rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
581 Instruction *BaseMemI, bool CanPreInc,
582 PrepForm Form, SCEVExpander &SCEVE,
583 SmallPtrSet<Value *, 16> &DeletedPtrs) {
584
585 LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
586
587 assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
588
590 assert(BasePtr && "No pointer operand");
591
592 Type *I8Ty = Type::getInt8Ty(BaseMemI->getParent()->getContext());
593 Type *I8PtrTy =
594 PointerType::get(BaseMemI->getParent()->getContext(),
595 BasePtr->getType()->getPointerAddressSpace());
596
597 bool IsConstantInc = false;
598 const SCEV *BasePtrIncSCEV = BasePtrSCEV->getStepRecurrence(*SE);
599 Value *IncNode = getNodeForInc(L, BaseMemI, BasePtrIncSCEV);
600
601 const SCEVConstant *BasePtrIncConstantSCEV =
602 dyn_cast<SCEVConstant>(BasePtrIncSCEV);
603 if (BasePtrIncConstantSCEV)
604 IsConstantInc = true;
605
606 // No valid representation for the increment.
607 if (!IncNode) {
608 LLVM_DEBUG(dbgs() << "Loop Increasement can not be represented!\n");
609 return std::make_pair(nullptr, nullptr);
610 }
611
612 if (Form == UpdateForm && !IsConstantInc &&
613 !CLOpts.formprep_update_nonconst_inc) {
615 dbgs()
616 << "Update form prepare for non-const increment is not enabled!\n");
617 return std::make_pair(nullptr, nullptr);
618 }
619
620 const SCEV *BasePtrStartSCEV = nullptr;
621 if (CanPreInc) {
622 assert(SE->isLoopInvariant(BasePtrIncSCEV, L) &&
623 "Increment is not loop invariant!\n");
624 BasePtrStartSCEV = SE->getMinusSCEV(BasePtrSCEV->getStart(),
625 IsConstantInc ? BasePtrIncConstantSCEV
626 : BasePtrIncSCEV);
627 } else
628 BasePtrStartSCEV = BasePtrSCEV->getStart();
629
630 if (alreadyPrepared(L, BaseMemI, BasePtrStartSCEV, BasePtrIncSCEV, Form)) {
631 LLVM_DEBUG(dbgs() << "Instruction form is already prepared!\n");
632 return std::make_pair(nullptr, nullptr);
633 }
634
635 LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
636
637 BasicBlock *Header = L->getHeader();
638 unsigned HeaderLoopPredCount = pred_size(Header);
639 BasicBlock *LoopPredecessor = L->getLoopPredecessor();
640
641 PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
643 NewPHI->insertBefore(Header->getFirstNonPHIIt());
644
645 Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
646 LoopPredecessor->getTerminator());
647
648 // Note that LoopPredecessor might occur in the predecessor list multiple
649 // times, and we need to add it the right number of times.
650 for (auto *PI : predecessors(Header)) {
651 if (PI != LoopPredecessor)
652 continue;
653
654 NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
655 }
656
657 Instruction *PtrInc = nullptr;
658 Instruction *NewBasePtr = nullptr;
659 if (CanPreInc) {
660 BasicBlock::iterator InsPoint = Header->getFirstInsertionPt();
662 I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
663 InsPoint);
664 cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
665 for (auto *PI : predecessors(Header)) {
666 if (PI == LoopPredecessor)
667 continue;
668
669 NewPHI->addIncoming(PtrInc, PI);
670 }
671 if (PtrInc->getType() != BasePtr->getType())
672 NewBasePtr =
673 new BitCastInst(PtrInc, BasePtr->getType(),
674 getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
675 else
676 NewBasePtr = PtrInc;
677 } else {
678 // Note that LoopPredecessor might occur in the predecessor list multiple
679 // times, and we need to make sure no more incoming value for them in PHI.
680 for (auto *PI : predecessors(Header)) {
681 if (PI == LoopPredecessor)
682 continue;
683
684 // For the latch predecessor, we need to insert a GEP just before the
685 // terminator to increase the address.
686 BasicBlock *BB = PI;
689 I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
690 InsPoint);
691 cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
692
693 NewPHI->addIncoming(PtrInc, PI);
694 }
695 PtrInc = NewPHI;
696 if (NewPHI->getType() != BasePtr->getType())
697 NewBasePtr = new BitCastInst(NewPHI, BasePtr->getType(),
699 Header->getFirstInsertionPt());
700 else
701 NewBasePtr = NewPHI;
702 }
703
704 BasePtr->replaceAllUsesWith(NewBasePtr);
705
706 DeletedPtrs.insert(BasePtr);
707
708 return std::make_pair(NewBasePtr, PtrInc);
709}
710
711Instruction *PPCLoopInstrFormPrep::rewriteForBucketElement(
712 std::pair<Instruction *, Instruction *> Base, const BucketElement &Element,
713 Value *OffToBase, SmallPtrSet<Value *, 16> &DeletedPtrs) {
714 Instruction *NewBasePtr = Base.first;
715 Instruction *PtrInc = Base.second;
716 assert((NewBasePtr && PtrInc) && "base does not exist!\n");
717
718 Type *I8Ty = Type::getInt8Ty(PtrInc->getParent()->getContext());
719
720 Value *Ptr = getPointerOperandAndType(Element.Instr);
721 assert(Ptr && "No pointer operand");
722
723 Instruction *RealNewPtr;
724 if (!Element.Offset ||
725 (isa<SCEVConstant>(Element.Offset) &&
726 cast<SCEVConstant>(Element.Offset)->getValue()->isZero())) {
727 RealNewPtr = NewBasePtr;
728 } else {
729 std::optional<BasicBlock::iterator> PtrIP = std::nullopt;
730 if (Instruction *I = dyn_cast<Instruction>(Ptr))
731 PtrIP = I->getIterator();
732
733 if (PtrIP && isa<Instruction>(NewBasePtr) &&
734 cast<Instruction>(NewBasePtr)->getParent() == (*PtrIP)->getParent())
735 PtrIP = std::nullopt;
736 else if (PtrIP && isa<PHINode>(*PtrIP))
737 PtrIP = (*PtrIP)->getParent()->getFirstInsertionPt();
738 else if (!PtrIP)
739 PtrIP = Element.Instr->getIterator();
740
741 assert(OffToBase && "There should be an offset for non base element!\n");
742 GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
743 I8Ty, PtrInc, OffToBase,
744 getInstrName(Element.Instr, GEPNodeOffNameSuffix));
745 if (PtrIP)
746 NewPtr->insertBefore(*(*PtrIP)->getParent(), *PtrIP);
747 else
748 NewPtr->insertAfter(cast<Instruction>(PtrInc));
749 NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
750 RealNewPtr = NewPtr;
751 }
752
753 Instruction *ReplNewPtr;
754 if (Ptr->getType() != RealNewPtr->getType()) {
755 ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
757 ReplNewPtr->insertAfter(RealNewPtr);
758 } else
759 ReplNewPtr = RealNewPtr;
760
761 Ptr->replaceAllUsesWith(ReplNewPtr);
762 DeletedPtrs.insert(Ptr);
763
764 return ReplNewPtr;
765}
766
767void PPCLoopInstrFormPrep::addOneCandidate(
768 Instruction *MemI, const SCEV *LSCEV, SmallVector<Bucket, 16> &Buckets,
769 std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
770 assert((MemI && getPointerOperandAndType(MemI)) &&
771 "Candidate should be a memory instruction.");
772 assert(LSCEV && "Invalid SCEV for Ptr value.");
773
774 bool FoundBucket = false;
775 for (auto &B : Buckets) {
776 if (cast<SCEVAddRecExpr>(B.BaseSCEV)->getStepRecurrence(*SE) !=
777 cast<SCEVAddRecExpr>(LSCEV)->getStepRecurrence(*SE))
778 continue;
779 const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
780 if (isValidDiff(Diff)) {
781 B.Elements.push_back(BucketElement(Diff, MemI));
782 FoundBucket = true;
783 break;
784 }
785 }
786
787 if (!FoundBucket) {
788 if (Buckets.size() == MaxCandidateNum) {
789 LLVM_DEBUG(dbgs() << "Can not prepare more chains, reach maximum limit "
790 << MaxCandidateNum << "\n");
791 return;
792 }
793 Buckets.push_back(Bucket(LSCEV, MemI));
794 }
795}
796
797SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
798 Loop *L,
799 std::function<bool(const Instruction *, Value *, const Type *)>
800 isValidCandidate,
801 std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
803
804 for (const auto &BB : L->blocks())
805 for (auto &J : *BB) {
806 Value *PtrValue = nullptr;
807 Type *PointerElementType = nullptr;
808 PtrValue = getPointerOperandAndType(&J, &PointerElementType);
809
810 if (!PtrValue)
811 continue;
812
813 if (PtrValue->getType()->getPointerAddressSpace())
814 continue;
815
816 if (L->isLoopInvariant(PtrValue))
817 continue;
818
819 const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
820 const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
821 if (!LARSCEV || LARSCEV->getLoop() != L)
822 continue;
823
824 // Mark that we have candidates for preparing.
825 HasCandidateForPrepare = true;
826
827 if (isValidCandidate(&J, PtrValue, PointerElementType))
828 addOneCandidate(&J, LSCEV, Buckets, isValidDiff, MaxCandidateNum);
829 }
830 return Buckets;
831}
832
833bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
834 PrepForm Form) {
835 // RemainderOffsetInfo details:
836 // key: value of (Offset urem DispConstraint). For DSForm, it can
837 // be [0, 4).
838 // first of pair: the index of first BucketElement whose remainder is equal
839 // to key. For key 0, this value must be 0.
840 // second of pair: number of load/stores with the same remainder.
841 DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
842
843 for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
844 if (!BucketChain.Elements[j].Offset)
845 RemainderOffsetInfo[0] = std::make_pair(0, 1);
846 else {
847 unsigned Remainder = cast<SCEVConstant>(BucketChain.Elements[j].Offset)
848 ->getAPInt()
849 .urem(Form);
850 if (!RemainderOffsetInfo.contains(Remainder))
851 RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
852 else
853 RemainderOffsetInfo[Remainder].second++;
854 }
855 }
856 // Currently we choose the most profitable base as the one which has the max
857 // number of load/store with same remainder.
858 // FIXME: adjust the base selection strategy according to load/store offset
859 // distribution.
860 // For example, if we have one candidate chain for DS form preparation, which
861 // contains following load/stores with different remainders:
862 // 1: 10 load/store whose remainder is 1;
863 // 2: 9 load/store whose remainder is 2;
864 // 3: 1 for remainder 3 and 0 for remainder 0;
865 // Now we will choose the first load/store whose remainder is 1 as base and
866 // adjust all other load/stores according to new base, so we will get 10 DS
867 // form and 10 X form.
868 // But we should be more clever, for this case we could use two bases, one for
869 // remainder 1 and the other for remainder 2, thus we could get 19 DS form and
870 // 1 X form.
871 unsigned MaxCountRemainder = 0;
872 for (unsigned j = 0; j < (unsigned)Form; j++)
873 if (auto It = RemainderOffsetInfo.find(j);
874 It != RemainderOffsetInfo.end() &&
875 It->second.second > RemainderOffsetInfo[MaxCountRemainder].second)
876 MaxCountRemainder = j;
877
878 // Abort when there are too few insts with common base.
879 if (RemainderOffsetInfo[MaxCountRemainder].second <
880 CLOpts.dispprep_min_threshold)
881 return false;
882
883 // If the first value is most profitable, no needed to adjust BucketChain
884 // elements as they are substracted the first value when collecting.
885 if (MaxCountRemainder == 0)
886 return true;
887
888 // Adjust load/store to the new chosen base.
889 const SCEV *Offset =
890 BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
891 BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
892 for (auto &E : BucketChain.Elements) {
893 if (E.Offset)
894 E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
895 else
897 }
898
899 std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
900 BucketChain.Elements[0]);
901 return true;
902}
903
904// FIXME: implement a more clever base choosing policy.
905// Currently we always choose an exist load/store offset. This maybe lead to
906// suboptimal code sequences. For example, for one DS chain with offsets
907// {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
908// for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
909// multipler of 4, it cannot be represented by sint16.
910bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
911 // We have a choice now of which instruction's memory operand we use as the
912 // base for the generated PHI. Always picking the first instruction in each
913 // bucket does not work well, specifically because that instruction might
914 // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
915 // the choice is somewhat arbitrary, because the backend will happily
916 // generate direct offsets from both the pre-incremented and
917 // post-incremented pointer values. Thus, we'll pick the first non-prefetch
918 // instruction in each bucket, and adjust the recurrence and other offsets
919 // accordingly.
920 for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
921 if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
922 if (II->getIntrinsicID() == Intrinsic::prefetch)
923 continue;
924
925 // If we'd otherwise pick the first element anyway, there's nothing to do.
926 if (j == 0)
927 break;
928
929 // If our chosen element has no offset from the base pointer, there's
930 // nothing to do.
931 if (!BucketChain.Elements[j].Offset ||
932 cast<SCEVConstant>(BucketChain.Elements[j].Offset)->isZero())
933 break;
934
935 const SCEV *Offset = BucketChain.Elements[j].Offset;
936 BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
937 for (auto &E : BucketChain.Elements) {
938 if (E.Offset)
939 E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
940 else
942 }
943
944 std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
945 break;
946 }
947 return true;
948}
949
950bool PPCLoopInstrFormPrep::rewriteLoadStores(
951 Loop *L, Bucket &BucketChain, SmallPtrSet<BasicBlock *, 16> &BBChanged,
952 PrepForm Form) {
953 bool MadeChange = false;
954
955 const SCEVAddRecExpr *BasePtrSCEV =
956 cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
957 if (!BasePtrSCEV->isAffine())
958 return MadeChange;
959
960 SCEVExpander SCEVE(*SE, "loopprepare-formrewrite");
961 if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
962 return MadeChange;
963
964 SmallPtrSet<Value *, 16> DeletedPtrs;
965
966 // For some DS form load/store instructions, it can also be an update form,
967 // if the stride is constant and is a multipler of 4. Use update form if
968 // prefer it.
969 bool CanPreInc = (Form == UpdateForm ||
970 ((Form == DSForm) &&
971 isa<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) &&
972 !cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE))
973 ->getAPInt()
974 .urem(4) &&
975 CLOpts.formprep_prefer_update));
976
977 std::pair<Instruction *, Instruction *> Base =
978 rewriteForBase(L, BasePtrSCEV, BucketChain.Elements.begin()->Instr,
979 CanPreInc, Form, SCEVE, DeletedPtrs);
980
981 if (!Base.first || !Base.second)
982 return MadeChange;
983
984 // Keep track of the replacement pointer values we've inserted so that we
985 // don't generate more pointer values than necessary.
986 SmallPtrSet<Value *, 16> NewPtrs;
987 NewPtrs.insert(Base.first);
988
989 for (const BucketElement &BE : llvm::drop_begin(BucketChain.Elements)) {
990 Value *Ptr = getPointerOperandAndType(BE.Instr);
991 assert(Ptr && "No pointer operand");
992 if (NewPtrs.count(Ptr))
993 continue;
994
995 Instruction *NewPtr = rewriteForBucketElement(
996 Base, BE,
997 BE.Offset ? cast<SCEVConstant>(BE.Offset)->getValue() : nullptr,
998 DeletedPtrs);
999 assert(NewPtr && "wrong rewrite!\n");
1000 NewPtrs.insert(NewPtr);
1001 }
1002
1003 // Clear the rewriter cache, because values that are in the rewriter's cache
1004 // can be deleted below, causing the AssertingVH in the cache to trigger.
1005 SCEVE.clear();
1006
1007 for (auto *Ptr : DeletedPtrs) {
1008 if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
1009 BBChanged.insert(IDel->getParent());
1011 }
1012
1013 MadeChange = true;
1014
1015 SuccPrepCount++;
1016
1017 if (Form == DSForm && !CanPreInc)
1018 DSFormChainRewritten++;
1019 else if (Form == DQForm)
1020 DQFormChainRewritten++;
1021 else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
1022 UpdFormChainRewritten++;
1023
1024 return MadeChange;
1025}
1026
1027bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
1028 SmallVector<Bucket, 16> &Buckets) {
1029 bool MadeChange = false;
1030 if (Buckets.empty())
1031 return MadeChange;
1032 SmallPtrSet<BasicBlock *, 16> BBChanged;
1033 for (auto &Bucket : Buckets)
1034 // The base address of each bucket is transformed into a phi and the others
1035 // are rewritten based on new base.
1036 if (prepareBaseForUpdateFormChain(Bucket))
1037 MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
1038
1039 if (MadeChange)
1040 for (auto *BB : BBChanged)
1041 DeleteDeadPHIs(BB);
1042 return MadeChange;
1043}
1044
1045bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L,
1046 SmallVector<Bucket, 16> &Buckets,
1047 PrepForm Form) {
1048 bool MadeChange = false;
1049
1050 if (Buckets.empty())
1051 return MadeChange;
1052
1053 SmallPtrSet<BasicBlock *, 16> BBChanged;
1054 for (auto &Bucket : Buckets) {
1055 if (Bucket.Elements.size() < CLOpts.dispprep_min_threshold)
1056 continue;
1057 if (prepareBaseForDispFormChain(Bucket, Form))
1058 MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
1059 }
1060
1061 if (MadeChange)
1062 for (auto *BB : BBChanged)
1063 DeleteDeadPHIs(BB);
1064 return MadeChange;
1065}
1066
1067// Find the loop invariant increment node for SCEV BasePtrIncSCEV.
1068// bb.loop.preheader:
1069// %start = ...
1070// bb.loop.body:
1071// %phinode = phi [ %start, %bb.loop.preheader ], [ %add, %bb.loop.body ]
1072// ...
1073// %add = add %phinode, %inc ; %inc is what we want to get.
1074//
1075Value *PPCLoopInstrFormPrep::getNodeForInc(Loop *L, Instruction *MemI,
1076 const SCEV *BasePtrIncSCEV) {
1077 // If the increment is a constant, no definition is needed.
1078 // Return the value directly.
1079 if (isa<SCEVConstant>(BasePtrIncSCEV))
1080 return cast<SCEVConstant>(BasePtrIncSCEV)->getValue();
1081
1082 if (!SE->isLoopInvariant(BasePtrIncSCEV, L))
1083 return nullptr;
1084
1085 BasicBlock *BB = MemI->getParent();
1086 if (!BB)
1087 return nullptr;
1088
1089 BasicBlock *LatchBB = L->getLoopLatch();
1090
1091 if (!LatchBB)
1092 return nullptr;
1093
1094 // Run through the PHIs and check their operands to find valid representation
1095 // for the increment SCEV.
1097 for (auto &CurrentPHI : PHIIter) {
1098 PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1099 if (!CurrentPHINode)
1100 continue;
1101
1102 if (!SE->isSCEVable(CurrentPHINode->getType()))
1103 continue;
1104
1105 const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1106
1107 const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1108 if (!PHIBasePtrSCEV)
1109 continue;
1110
1111 const SCEV *PHIBasePtrIncSCEV = PHIBasePtrSCEV->getStepRecurrence(*SE);
1112
1113 if (!PHIBasePtrIncSCEV || (PHIBasePtrIncSCEV != BasePtrIncSCEV))
1114 continue;
1115
1116 // Get the incoming value from the loop latch and check if the value has
1117 // the add form with the required increment.
1118 if (CurrentPHINode->getBasicBlockIndex(LatchBB) < 0)
1119 continue;
1120 if (Instruction *I = dyn_cast<Instruction>(
1121 CurrentPHINode->getIncomingValueForBlock(LatchBB))) {
1122 Value *StrippedBaseI = I;
1123 while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBaseI))
1124 StrippedBaseI = BC->getOperand(0);
1125
1126 Instruction *StrippedI = dyn_cast<Instruction>(StrippedBaseI);
1127 if (!StrippedI)
1128 continue;
1129
1130 // LSR pass may add a getelementptr instruction to do the loop increment,
1131 // also search in that getelementptr instruction.
1132 if (StrippedI->getOpcode() == Instruction::Add ||
1133 (StrippedI->getOpcode() == Instruction::GetElementPtr &&
1134 StrippedI->getNumOperands() == 2)) {
1135 if (SE->getSCEVAtScope(StrippedI->getOperand(0), L) == BasePtrIncSCEV)
1136 return StrippedI->getOperand(0);
1137 if (SE->getSCEVAtScope(StrippedI->getOperand(1), L) == BasePtrIncSCEV)
1138 return StrippedI->getOperand(1);
1139 }
1140 }
1141 }
1142 return nullptr;
1143}
1144
1145// In order to prepare for the preferred instruction form, a PHI is added.
1146// This function will check to see if that PHI already exists and will return
1147// true if it found an existing PHI with the matched start and increment as the
1148// one we wanted to create.
1149bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI,
1150 const SCEV *BasePtrStartSCEV,
1151 const SCEV *BasePtrIncSCEV,
1152 PrepForm Form) {
1153 BasicBlock *BB = MemI->getParent();
1154 if (!BB)
1155 return false;
1156
1157 BasicBlock *PredBB = L->getLoopPredecessor();
1158 BasicBlock *LatchBB = L->getLoopLatch();
1159
1160 if (!PredBB || !LatchBB)
1161 return false;
1162
1163 // Run through the PHIs and see if we have some that looks like a preparation
1165 for (auto & CurrentPHI : PHIIter) {
1166 PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1167 if (!CurrentPHINode)
1168 continue;
1169
1170 if (!SE->isSCEVable(CurrentPHINode->getType()))
1171 continue;
1172
1173 const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1174
1175 const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1176 if (!PHIBasePtrSCEV)
1177 continue;
1178
1179 const SCEVConstant *PHIBasePtrIncSCEV =
1180 dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
1181 if (!PHIBasePtrIncSCEV)
1182 continue;
1183
1184 if (CurrentPHINode->getNumIncomingValues() == 2) {
1185 if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
1186 CurrentPHINode->getIncomingBlock(1) == PredBB) ||
1187 (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
1188 CurrentPHINode->getIncomingBlock(0) == PredBB)) {
1189 if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
1190 // The existing PHI (CurrentPHINode) has the same start and increment
1191 // as the PHI that we wanted to create.
1192 if ((Form == UpdateForm || Form == ChainCommoning ) &&
1193 PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
1194 ++PHINodeAlreadyExistsUpdate;
1195 return true;
1196 }
1197 if (Form == DSForm || Form == DQForm) {
1198 const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
1199 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
1200 if (Diff && !Diff->getAPInt().urem(Form)) {
1201 if (Form == DSForm)
1202 ++PHINodeAlreadyExistsDS;
1203 else
1204 ++PHINodeAlreadyExistsDQ;
1205 return true;
1206 }
1207 }
1208 }
1209 }
1210 }
1211 }
1212 return false;
1213}
1214
1215bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
1216 bool MadeChange = false;
1217
1218 // Only prep. the inner-most loop
1219 if (!L->isInnermost())
1220 return MadeChange;
1221
1222 // Return if already done enough preparation.
1223 if (SuccPrepCount >= CLOpts.formprep_max_vars)
1224 return MadeChange;
1225
1226 LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
1227
1228 BasicBlock *LoopPredecessor = L->getLoopPredecessor();
1229 // If there is no loop predecessor, or the loop predecessor's terminator
1230 // returns a value (which might contribute to determining the loop's
1231 // iteration space), insert a new preheader for the loop.
1232 if (!LoopPredecessor ||
1233 !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
1234 LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
1235 if (LoopPredecessor)
1236 MadeChange = true;
1237 }
1238 if (!LoopPredecessor) {
1239 LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
1240 return MadeChange;
1241 }
1242 // Check if a load/store has update form. This lambda is used by function
1243 // collectCandidates which can collect candidates for types defined by lambda.
1244 auto isUpdateFormCandidate = [&](const Instruction *I, Value *PtrValue,
1245 const Type *PointerElementType) {
1246 assert((PtrValue && I) && "Invalid parameter!");
1247 // There are no update forms for Altivec vector load/stores.
1248 if (ST && ST->hasAltivec() && PointerElementType->isVectorTy())
1249 return false;
1250 // There are no update forms for P10 lxvp/stxvp intrinsic.
1251 auto *II = dyn_cast<IntrinsicInst>(I);
1252 if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
1253 II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
1254 return false;
1255 // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
1256 // be 4's multiple (DS-form). For i64 loads/stores when the displacement
1257 // fits in a 16-bit signed field but isn't a multiple of 4, it will be
1258 // useless and possible to break some original well-form addressing mode
1259 // to make this pre-inc prep for it.
1260 if (PointerElementType->isIntegerTy(64)) {
1261 const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
1262 const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
1263 if (!LARSCEV || LARSCEV->getLoop() != L)
1264 return false;
1265 if (const SCEVConstant *StepConst =
1267 const APInt &ConstInt = StepConst->getValue()->getValue();
1268 if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
1269 return false;
1270 }
1271 }
1272 return true;
1273 };
1274
1275 // Check if a load/store has DS form.
1276 auto isDSFormCandidate = [](const Instruction *I, Value *PtrValue,
1277 const Type *PointerElementType) {
1278 assert((PtrValue && I) && "Invalid parameter!");
1279 if (isa<IntrinsicInst>(I))
1280 return false;
1281 return (PointerElementType->isIntegerTy(64)) ||
1282 (PointerElementType->isFloatTy()) ||
1283 (PointerElementType->isDoubleTy()) ||
1284 (PointerElementType->isIntegerTy(32) &&
1285 llvm::any_of(I->users(),
1286 [](const User *U) { return isa<SExtInst>(U); }));
1287 };
1288
1289 // Check if a load/store has DQ form.
1290 auto isDQFormCandidate = [&](const Instruction *I, Value *PtrValue,
1291 const Type *PointerElementType) {
1292 assert((PtrValue && I) && "Invalid parameter!");
1293 // Check if it is a P10 lxvp/stxvp intrinsic.
1294 auto *II = dyn_cast<IntrinsicInst>(I);
1295 if (II)
1296 return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
1297 II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
1298 // Check if it is a P9 vector load/store.
1299 return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy());
1300 };
1301
1302 // Check if a load/store is candidate for chain commoning.
1303 // If the SCEV is only with one ptr operand in its start, we can use that
1304 // start as a chain separator. Mark this load/store as a candidate.
1305 auto isChainCommoningCandidate = [&](const Instruction *I, Value *PtrValue,
1306 const Type *PointerElementType) {
1307 const SCEVAddRecExpr *ARSCEV =
1308 cast<SCEVAddRecExpr>(SE->getSCEVAtScope(PtrValue, L));
1309 if (!ARSCEV)
1310 return false;
1311
1312 if (!ARSCEV->isAffine())
1313 return false;
1314
1315 const SCEV *Start = ARSCEV->getStart();
1316
1317 // A single pointer. We can treat it as offset 0.
1318 if (isa<SCEVUnknown>(Start) && Start->getType()->isPointerTy())
1319 return true;
1320
1321 const SCEVAddExpr *ASCEV = dyn_cast<SCEVAddExpr>(Start);
1322
1323 // We need a SCEVAddExpr to include both base and offset.
1324 if (!ASCEV)
1325 return false;
1326
1327 // Make sure there is only one pointer operand(base) and all other operands
1328 // are integer type.
1329 bool SawPointer = false;
1330 for (const SCEV *Op : ASCEV->operands()) {
1331 if (Op->getType()->isPointerTy()) {
1332 if (SawPointer)
1333 return false;
1334 SawPointer = true;
1335 } else if (!Op->getType()->isIntegerTy())
1336 return false;
1337 }
1338
1339 return SawPointer;
1340 };
1341
1342 // Check if the diff is a constant type. This is used for update/DS/DQ form
1343 // preparation.
1344 auto isValidConstantDiff = [](const SCEV *Diff) {
1345 return dyn_cast<SCEVConstant>(Diff) != nullptr;
1346 };
1347
1348 // Make sure the diff between the base and new candidate is required type.
1349 // This is used for chain commoning preparation.
1350 auto isValidChainCommoningDiff = [](const SCEV *Diff) {
1351 assert(Diff && "Invalid Diff!\n");
1352
1353 // Don't mess up previous dform prepare.
1354 if (isa<SCEVConstant>(Diff))
1355 return false;
1356
1357 // A single integer type offset.
1358 if (isa<SCEVUnknown>(Diff) && Diff->getType()->isIntegerTy())
1359 return true;
1360
1361 const SCEVNAryExpr *ADiff = dyn_cast<SCEVNAryExpr>(Diff);
1362 if (!ADiff)
1363 return false;
1364
1365 for (const SCEV *Op : ADiff->operands())
1366 if (!Op->getType()->isIntegerTy())
1367 return false;
1368
1369 return true;
1370 };
1371
1372 HasCandidateForPrepare = false;
1373
1374 LLVM_DEBUG(dbgs() << "Start to prepare for update form.\n");
1375 // Collect buckets of comparable addresses used by loads and stores for update
1376 // form.
1377 SmallVector<Bucket, 16> UpdateFormBuckets =
1378 collectCandidates(L, isUpdateFormCandidate, isValidConstantDiff,
1379 CLOpts.preinc_prep_max_vars);
1380
1381 // Prepare for update form.
1382 if (!UpdateFormBuckets.empty())
1383 MadeChange |= updateFormPrep(L, UpdateFormBuckets);
1384 else if (!HasCandidateForPrepare) {
1385 LLVM_DEBUG(
1386 dbgs()
1387 << "No prepare candidates found, stop praparation for current loop!\n");
1388 // If no candidate for preparing, return early.
1389 return MadeChange;
1390 }
1391
1392 LLVM_DEBUG(dbgs() << "Start to prepare for DS form.\n");
1393 // Collect buckets of comparable addresses used by loads and stores for DS
1394 // form.
1395 SmallVector<Bucket, 16> DSFormBuckets = collectCandidates(
1396 L, isDSFormCandidate, isValidConstantDiff, CLOpts.dsprep_max_vars);
1397
1398 // Prepare for DS form.
1399 if (!DSFormBuckets.empty())
1400 MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
1401
1402 LLVM_DEBUG(dbgs() << "Start to prepare for DQ form.\n");
1403 // Collect buckets of comparable addresses used by loads and stores for DQ
1404 // form.
1405 SmallVector<Bucket, 16> DQFormBuckets = collectCandidates(
1406 L, isDQFormCandidate, isValidConstantDiff, CLOpts.dqprep_max_vars);
1407
1408 // Prepare for DQ form.
1409 if (!DQFormBuckets.empty())
1410 MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
1411
1412 // Collect buckets of comparable addresses used by loads and stores for chain
1413 // commoning. With chain commoning, we reuse offsets between the chains, so
1414 // the register pressure will be reduced.
1415 if (!CLOpts.formprep_chain_commoning) {
1416 LLVM_DEBUG(dbgs() << "Chain commoning is not enabled.\n");
1417 return MadeChange;
1418 }
1419
1420 LLVM_DEBUG(dbgs() << "Start to prepare for chain commoning.\n");
1421 SmallVector<Bucket, 16> Buckets =
1422 collectCandidates(L, isChainCommoningCandidate, isValidChainCommoningDiff,
1423 CLOpts.chaincommon_max_vars);
1424
1425 // Prepare for chain commoning.
1426 if (!Buckets.empty())
1427 MadeChange |= chainCommoning(L, Buckets);
1428
1429 return MadeChange;
1430}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const Function * getParent(const Value *V)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
static constexpr StringRef GEPNodeOffNameSuffix
static Value * getPointerOperandAndType(Value *MemI, Type **PtrElementType=nullptr)
static constexpr StringRef GEPNodeIncNameSuffix
static std::string getInstrName(const Value *I, StringRef Suffix)
static constexpr StringRef PHINodeNameSuffix
static bool IsPtrInBounds(Value *BasePtr)
static constexpr StringRef CastNodeNameSuffix
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static const char * name
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:431
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1774
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class represents a no-op cast from one type to another.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Common code between 32-bit and 64-bit PowerPC targets.
const PPCSubtarget * getSubtargetImpl(const Function &F) const override
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
const APInt & getAPInt() const
LLVM_ABI bool isSafeToExpand(const SCEV *S) const
Return true if the given expression is safe to expand in the sense that all materialized values are s...
void clear()
Erase the contents of the InsertedExpressions map so that users trying to expand the same expression ...
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
ArrayRef< SCEVUse > operands() const
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
const AArch64MCOptions & getCLOpts(const MCTargetOptions &Options)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
LLVM_ABI BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
FunctionPass * createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
LLVM_ABI char & LCSSAID
Definition LCSSA.cpp:545
auto pred_size(const MachineBasicBlock *BB)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
iterator_range< df_iterator< T > > depth_first(const T &G)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
SCEVPtrT getPointer() const