7ab16f13811ffdbaefca905b09291674227d64ef
[oota-llvm.git] / lib / Transforms / Scalar / AlignmentFromAssumptions.cpp
1 //===----------------------- AlignmentFromAssumptions.cpp -----------------===//
2 //                  Set Load/Store Alignments From Assumptions
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file implements a ScalarEvolution-based transformation to set
12 // the alignments of load, stores and memory intrinsics based on the truth
13 // expressions of assume intrinsics. The primary motivation is to handle
14 // complex alignment assumptions that apply to vector loads and stores that
15 // appear after vectorization and unrolling.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define AA_NAME "alignment-from-assumptions"
20 #define DEBUG_TYPE AA_NAME
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AssumptionTracker.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 using namespace llvm;
38
39 STATISTIC(NumLoadAlignChanged,
40   "Number of loads changed by alignment assumptions");
41 STATISTIC(NumStoreAlignChanged,
42   "Number of stores changed by alignment assumptions");
43 STATISTIC(NumMemIntAlignChanged,
44   "Number of memory intrinsics changed by alignment assumptions");
45
46 namespace {
47 struct AlignmentFromAssumptions : public FunctionPass {
48   static char ID; // Pass identification, replacement for typeid
49   AlignmentFromAssumptions() : FunctionPass(ID) {
50     initializeAlignmentFromAssumptionsPass(*PassRegistry::getPassRegistry());
51   }
52
53   bool runOnFunction(Function &F);
54
55   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56     AU.addRequired<AssumptionTracker>();
57     AU.addRequired<ScalarEvolution>();
58     AU.addRequired<DominatorTreeWrapperPass>();
59
60     AU.setPreservesCFG();
61     AU.addPreserved<LoopInfo>();
62     AU.addPreserved<DominatorTreeWrapperPass>();
63     AU.addPreserved<ScalarEvolution>();
64   }
65
66   // For memory transfers, we need a common alignment for both the source and
67   // destination. If we have a new alignment for only one operand of a transfer
68   // instruction, save it in these maps.  If we reach the other operand through
69   // another assumption later, then we may change the alignment at that point.
70   DenseMap<MemTransferInst *, unsigned> NewDestAlignments, NewSrcAlignments;
71
72   AssumptionTracker *AT;
73   ScalarEvolution *SE;
74   DominatorTree *DT;
75   const DataLayout *DL;
76
77   bool extractAlignmentInfo(CallInst *I, Value *&AAPtr, const SCEV *&AlignSCEV,
78                             const SCEV *&OffSCEV);
79   bool processAssumption(CallInst *I);
80 };
81 }
82
83 char AlignmentFromAssumptions::ID = 0;
84 static const char aip_name[] = "Alignment from assumptions";
85 INITIALIZE_PASS_BEGIN(AlignmentFromAssumptions, AA_NAME,
86                       aip_name, false, false)
87 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
88 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
89 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
90 INITIALIZE_PASS_END(AlignmentFromAssumptions, AA_NAME,
91                     aip_name, false, false)
92
93 FunctionPass *llvm::createAlignmentFromAssumptionsPass() {
94   return new AlignmentFromAssumptions();
95 }
96
97 // Given an expression for the (constant) alignment, AlignSCEV, and an
98 // expression for the displacement between a pointer and the aligned address,
99 // DiffSCEV, compute the alignment of the displaced pointer if it can be reduced
100 // to a constant. Using SCEV to compute alignment handles the case where
101 // DiffSCEV is a recurrence with constant start such that the aligned offset
102 // is constant. e.g. {16,+,32} % 32 -> 16.
103 static unsigned getNewAlignmentDiff(const SCEV *DiffSCEV,
104                                     const SCEV *AlignSCEV,
105                                     ScalarEvolution *SE) {
106   // DiffUnits = Diff % int64_t(Alignment)
107   const SCEV *DiffAlignDiv = SE->getUDivExpr(DiffSCEV, AlignSCEV);
108   const SCEV *DiffAlign = SE->getMulExpr(DiffAlignDiv, AlignSCEV);
109   const SCEV *DiffUnitsSCEV = SE->getMinusSCEV(DiffAlign, DiffSCEV);
110
111   DEBUG(dbgs() << "\talignment relative to " << *AlignSCEV << " is " <<
112                   *DiffUnitsSCEV << " (diff: " << *DiffSCEV << ")\n");
113
114   if (const SCEVConstant *ConstDUSCEV =
115       dyn_cast<SCEVConstant>(DiffUnitsSCEV)) {
116     int64_t DiffUnits = ConstDUSCEV->getValue()->getSExtValue();
117
118     // If the displacement is an exact multiple of the alignment, then the
119     // displaced pointer has the same alignment as the aligned pointer, so
120     // return the alignment value.
121     if (!DiffUnits)
122       return (unsigned)
123         cast<SCEVConstant>(AlignSCEV)->getValue()->getSExtValue();
124
125     // If the displacement is not an exact multiple, but the remainder is a
126     // constant, then return this remainder (but only if it is a power of 2).
127     uint64_t DiffUnitsAbs = abs64(DiffUnits);
128     if (isPowerOf2_64(DiffUnitsAbs))
129       return (unsigned) DiffUnitsAbs;
130   }
131
132   return 0;
133 }
134
135 // There is an address given by an offset OffSCEV from AASCEV which has an
136 // alignment AlignSCEV. Use that information, if possible, to compute a new
137 // alignment for Ptr.
138 static unsigned getNewAlignment(const SCEV *AASCEV, const SCEV *AlignSCEV,
139                                 const SCEV *OffSCEV, Value *Ptr,
140                                 ScalarEvolution *SE) {
141   const SCEV *PtrSCEV = SE->getSCEV(Ptr);
142   const SCEV *DiffSCEV = SE->getMinusSCEV(PtrSCEV, AASCEV);
143
144   // What we really want to know is the overall offset to the aligned
145   // address. This address is displaced by the provided offset.
146   DiffSCEV = SE->getMinusSCEV(DiffSCEV, OffSCEV);
147
148   DEBUG(dbgs() << "AFI: alignment of " << *Ptr << " relative to " <<
149                   *AlignSCEV << " and offset " << *OffSCEV <<
150                   " using diff " << *DiffSCEV << "\n");
151
152   unsigned NewAlignment = getNewAlignmentDiff(DiffSCEV, AlignSCEV, SE);
153   DEBUG(dbgs() << "\tnew alignment: " << NewAlignment << "\n");
154
155   if (NewAlignment) {
156     return NewAlignment;
157   } else if (const SCEVAddRecExpr *DiffARSCEV =
158              dyn_cast<SCEVAddRecExpr>(DiffSCEV)) {
159     // The relative offset to the alignment assumption did not yield a constant,
160     // but we should try harder: if we assume that a is 32-byte aligned, then in
161     // for (i = 0; i < 1024; i += 4) r += a[i]; not all of the loads from a are
162     // 32-byte aligned, but instead alternate between 32 and 16-byte alignment.
163     // As a result, the new alignment will not be a constant, but can still
164     // be improved over the default (of 4) to 16.
165
166     const SCEV *DiffStartSCEV = DiffARSCEV->getStart();
167     const SCEV *DiffIncSCEV = DiffARSCEV->getStepRecurrence(*SE);
168
169     DEBUG(dbgs() << "\ttrying start/inc alignment using start " <<
170                     *DiffStartSCEV << " and inc " << *DiffIncSCEV << "\n");
171
172     // Now compute the new alignment using the displacement to the value in the
173     // first iteration, and also the alignment using the per-iteration delta.
174     // If these are the same, then use that answer. Otherwise, use the smaller
175     // one, but only if it divides the larger one.
176     NewAlignment = getNewAlignmentDiff(DiffStartSCEV, AlignSCEV, SE);
177     unsigned NewIncAlignment = getNewAlignmentDiff(DiffIncSCEV, AlignSCEV, SE);
178
179     DEBUG(dbgs() << "\tnew start alignment: " << NewAlignment << "\n");
180     DEBUG(dbgs() << "\tnew inc alignment: " << NewIncAlignment << "\n");
181
182     if (!NewAlignment || !NewIncAlignment) {
183       return 0;
184     } else if (NewAlignment > NewIncAlignment) {
185       if (NewAlignment % NewIncAlignment == 0) {
186         DEBUG(dbgs() << "\tnew start/inc alignment: " <<
187                         NewIncAlignment << "\n");
188         return NewIncAlignment;
189       }
190     } else if (NewIncAlignment > NewAlignment) {
191       if (NewIncAlignment % NewAlignment == 0) {
192         DEBUG(dbgs() << "\tnew start/inc alignment: " <<
193                         NewAlignment << "\n");
194         return NewAlignment;
195       }
196     } else if (NewIncAlignment == NewAlignment) {
197       DEBUG(dbgs() << "\tnew start/inc alignment: " <<
198                       NewAlignment << "\n");
199       return NewAlignment;
200     }
201   }
202
203   return 0;
204 }
205
206 bool AlignmentFromAssumptions::extractAlignmentInfo(CallInst *I,
207                                  Value *&AAPtr, const SCEV *&AlignSCEV,
208                                  const SCEV *&OffSCEV) {
209   // An alignment assume must be a statement about the least-significant
210   // bits of the pointer being zero, possibly with some offset.
211   ICmpInst *ICI = dyn_cast<ICmpInst>(I->getArgOperand(0));
212   if (!ICI)
213     return false;
214
215   // This must be an expression of the form: x & m == 0.
216   if (ICI->getPredicate() != ICmpInst::ICMP_EQ)
217     return false;
218
219   // Swap things around so that the RHS is 0.
220   Value *CmpLHS = ICI->getOperand(0);
221   Value *CmpRHS = ICI->getOperand(1);
222   const SCEV *CmpLHSSCEV = SE->getSCEV(CmpLHS);
223   const SCEV *CmpRHSSCEV = SE->getSCEV(CmpRHS);
224   if (CmpLHSSCEV->isZero())
225     std::swap(CmpLHS, CmpRHS);
226   else if (!CmpRHSSCEV->isZero())
227     return false;
228
229   BinaryOperator *CmpBO = dyn_cast<BinaryOperator>(CmpLHS);
230   if (!CmpBO || CmpBO->getOpcode() != Instruction::And)
231     return false;
232
233   // Swap things around so that the right operand of the and is a constant
234   // (the mask); we cannot deal with variable masks.
235   Value *AndLHS = CmpBO->getOperand(0);
236   Value *AndRHS = CmpBO->getOperand(1);
237   const SCEV *AndLHSSCEV = SE->getSCEV(AndLHS);
238   const SCEV *AndRHSSCEV = SE->getSCEV(AndRHS);
239   if (isa<SCEVConstant>(AndLHSSCEV)) {
240     std::swap(AndLHS, AndRHS);
241     std::swap(AndLHSSCEV, AndRHSSCEV);
242   }
243
244   const SCEVConstant *MaskSCEV = dyn_cast<SCEVConstant>(AndRHSSCEV);
245   if (!MaskSCEV)
246     return false;
247
248   // The mask must have some trailing ones (otherwise the condition is
249   // trivial and tells us nothing about the alignment of the left operand).
250   unsigned TrailingOnes =
251     MaskSCEV->getValue()->getValue().countTrailingOnes();
252   if (!TrailingOnes)
253     return false;
254
255   // Cap the alignment at the maximum with which LLVM can deal (and make sure
256   // we don't overflow the shift).
257   uint64_t Alignment;
258   TrailingOnes = std::min(TrailingOnes,
259     unsigned(sizeof(unsigned) * CHAR_BIT - 1));
260   Alignment = std::min(1u << TrailingOnes, +Value::MaximumAlignment);
261
262   Type *Int64Ty = Type::getInt64Ty(I->getParent()->getParent()->getContext());
263   AlignSCEV = SE->getConstant(Int64Ty, Alignment);
264
265   // The LHS might be a ptrtoint instruction, or it might be the pointer
266   // with an offset.
267   AAPtr = nullptr;
268   OffSCEV = nullptr;
269   if (PtrToIntInst *PToI = dyn_cast<PtrToIntInst>(AndLHS)) {
270     AAPtr = PToI->getPointerOperand();
271     OffSCEV = SE->getConstant(Int64Ty, 0);
272   } else if (const SCEVAddExpr* AndLHSAddSCEV =
273              dyn_cast<SCEVAddExpr>(AndLHSSCEV)) {
274     // Try to find the ptrtoint; subtract it and the rest is the offset.
275     for (SCEVAddExpr::op_iterator J = AndLHSAddSCEV->op_begin(),
276          JE = AndLHSAddSCEV->op_end(); J != JE; ++J)
277       if (const SCEVUnknown *OpUnk = dyn_cast<SCEVUnknown>(*J))
278         if (PtrToIntInst *PToI = dyn_cast<PtrToIntInst>(OpUnk->getValue())) {
279           AAPtr = PToI->getPointerOperand();
280           OffSCEV = SE->getMinusSCEV(AndLHSAddSCEV, *J);
281           break;
282         }
283   }
284
285   if (!AAPtr)
286     return false;
287
288   // Sign extend the offset to 64 bits (so that it is like all of the other
289   // expressions). 
290   unsigned OffSCEVBits = OffSCEV->getType()->getPrimitiveSizeInBits();
291   if (OffSCEVBits < 64)
292     OffSCEV = SE->getSignExtendExpr(OffSCEV, Int64Ty);
293   else if (OffSCEVBits > 64)
294     return false;
295
296   AAPtr = AAPtr->stripPointerCasts();
297   return true;
298 }
299
300 bool AlignmentFromAssumptions::processAssumption(CallInst *ACall) {
301   Value *AAPtr;
302   const SCEV *AlignSCEV, *OffSCEV;
303   if (!extractAlignmentInfo(ACall, AAPtr, AlignSCEV, OffSCEV))
304     return false;
305
306   const SCEV *AASCEV = SE->getSCEV(AAPtr);
307
308   // Apply the assumption to all other users of the specified pointer.
309   SmallPtrSet<Instruction *, 32> Visited;
310   SmallVector<Instruction*, 16> WorkList;
311   for (User *J : AAPtr->users()) {
312     if (J == ACall)
313       continue;
314
315     if (Instruction *K = dyn_cast<Instruction>(J))
316       if (isValidAssumeForContext(ACall, K, DL, DT))
317         WorkList.push_back(K);
318   }
319
320   while (!WorkList.empty()) {
321     Instruction *J = WorkList.pop_back_val();
322
323     if (LoadInst *LI = dyn_cast<LoadInst>(J)) {
324       unsigned NewAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV,
325         LI->getPointerOperand(), SE);
326
327       if (NewAlignment > LI->getAlignment()) {
328         LI->setAlignment(NewAlignment);
329         ++NumLoadAlignChanged;
330       }
331     } else if (StoreInst *SI = dyn_cast<StoreInst>(J)) {
332       unsigned NewAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV,
333         SI->getPointerOperand(), SE);
334
335       if (NewAlignment > SI->getAlignment()) {
336         SI->setAlignment(NewAlignment);
337         ++NumStoreAlignChanged;
338       }
339     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(J)) {
340       unsigned NewDestAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV,
341         MI->getDest(), SE);
342
343       // For memory transfers, we need a common alignment for both the
344       // source and destination. If we have a new alignment for this
345       // instruction, but only for one operand, save it. If we reach the
346       // other operand through another assumption later, then we may
347       // change the alignment at that point.
348       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
349         unsigned NewSrcAlignment = getNewAlignment(AASCEV, AlignSCEV, OffSCEV,
350           MTI->getSource(), SE);
351
352         DenseMap<MemTransferInst *, unsigned>::iterator DI =
353           NewDestAlignments.find(MTI);
354         unsigned AltDestAlignment = (DI == NewDestAlignments.end()) ?
355                                     0 : DI->second;
356
357         DenseMap<MemTransferInst *, unsigned>::iterator SI =
358           NewSrcAlignments.find(MTI);
359         unsigned AltSrcAlignment = (SI == NewSrcAlignments.end()) ?
360                                    0 : SI->second;
361
362         DEBUG(dbgs() << "\tmem trans: " << NewDestAlignment << " " <<
363                         AltDestAlignment << " " << NewSrcAlignment <<
364                         " " << AltSrcAlignment << "\n");
365
366         // Of these four alignments, pick the largest possible...
367         unsigned NewAlignment = 0;
368         if (NewDestAlignment <= std::max(NewSrcAlignment, AltSrcAlignment))
369           NewAlignment = std::max(NewAlignment, NewDestAlignment);
370         if (AltDestAlignment <= std::max(NewSrcAlignment, AltSrcAlignment))
371           NewAlignment = std::max(NewAlignment, AltDestAlignment);
372         if (NewSrcAlignment <= std::max(NewDestAlignment, AltDestAlignment))
373           NewAlignment = std::max(NewAlignment, NewSrcAlignment);
374         if (AltSrcAlignment <= std::max(NewDestAlignment, AltDestAlignment))
375           NewAlignment = std::max(NewAlignment, AltSrcAlignment);
376
377         if (NewAlignment > MI->getAlignment()) {
378           MI->setAlignment(ConstantInt::get(Type::getInt32Ty(
379             MI->getParent()->getContext()), NewAlignment));
380           ++NumMemIntAlignChanged;
381         }
382
383         NewDestAlignments.insert(std::make_pair(MTI, NewDestAlignment));
384         NewSrcAlignments.insert(std::make_pair(MTI, NewSrcAlignment));
385       } else if (NewDestAlignment > MI->getAlignment()) {
386         assert((!isa<MemIntrinsic>(MI) || isa<MemSetInst>(MI)) &&
387                "Unknown memory intrinsic");
388
389         MI->setAlignment(ConstantInt::get(Type::getInt32Ty(
390           MI->getParent()->getContext()), NewDestAlignment));
391         ++NumMemIntAlignChanged;
392       }
393     }
394
395     // Now that we've updated that use of the pointer, look for other uses of
396     // the pointer to update.
397     Visited.insert(J);
398     for (User *UJ : J->users()) {
399       Instruction *K = cast<Instruction>(UJ);
400       if (!Visited.count(K) && isValidAssumeForContext(ACall, K, DL, DT))
401         WorkList.push_back(K);
402     }
403   }
404
405   return true;
406 }
407
408 bool AlignmentFromAssumptions::runOnFunction(Function &F) {
409   bool Changed = false;
410   AT = &getAnalysis<AssumptionTracker>();
411   SE = &getAnalysis<ScalarEvolution>();
412   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
413   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
414   DL = DLP ? &DLP->getDataLayout() : nullptr;
415
416   NewDestAlignments.clear();
417   NewSrcAlignments.clear();
418
419   for (auto &I : AT->assumptions(&F))
420     Changed |= processAssumption(I);
421
422   return Changed;
423 }
424