1 //==- llvm/CodeGen/SelectionDAGAddressAnalysis.cpp - DAG Address Analysis --==//
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 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
10 #include "llvm/Analysis/MemoryLocation.h"
11 #include "llvm/CodeGen/ISDOpcodes.h"
12 #include "llvm/CodeGen/MachineFrameInfo.h"
13 #include "llvm/CodeGen/MachineFunction.h"
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/SelectionDAGNodes.h"
16 #include "llvm/CodeGen/TargetLowering.h"
17 #include "llvm/IR/GlobalAlias.h"
18 #include "llvm/Support/Casting.h"
19 #include "llvm/Support/Debug.h"
20 #include <cstdint>
21 
22 using namespace llvm;
23 
24 bool BaseIndexOffset::equalBaseIndex(const BaseIndexOffset &Other,
25                                      const SelectionDAG &DAG,
26                                      int64_t &Off) const {
27   // Conservatively fail if we a match failed..
28   if (!Base.getNode() || !Other.Base.getNode())
29     return false;
30   if (!hasValidOffset() || !Other.hasValidOffset())
31     return false;
32   // Initial Offset difference.
33   Off = *Other.Offset - *Offset;
34 
35   if ((Other.Index == Index) && (Other.IsIndexSignExt == IsIndexSignExt)) {
36     // Trivial match.
37     if (Other.Base == Base)
38       return true;
39 
40     // Match GlobalAddresses
41     if (auto *A = dyn_cast<GlobalAddressSDNode>(Base))
42       if (auto *B = dyn_cast<GlobalAddressSDNode>(Other.Base))
43         if (A->getGlobal() == B->getGlobal()) {
44           Off += B->getOffset() - A->getOffset();
45           return true;
46         }
47 
48     // Match Constants
49     if (auto *A = dyn_cast<ConstantPoolSDNode>(Base))
50       if (auto *B = dyn_cast<ConstantPoolSDNode>(Other.Base)) {
51         bool IsMatch =
52             A->isMachineConstantPoolEntry() == B->isMachineConstantPoolEntry();
53         if (IsMatch) {
54           if (A->isMachineConstantPoolEntry())
55             IsMatch = A->getMachineCPVal() == B->getMachineCPVal();
56           else
57             IsMatch = A->getConstVal() == B->getConstVal();
58         }
59         if (IsMatch) {
60           Off += B->getOffset() - A->getOffset();
61           return true;
62         }
63       }
64 
65     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
66 
67     // Match FrameIndexes.
68     if (auto *A = dyn_cast<FrameIndexSDNode>(Base))
69       if (auto *B = dyn_cast<FrameIndexSDNode>(Other.Base)) {
70         // Equal FrameIndexes - offsets are directly comparable.
71         if (A->getIndex() == B->getIndex())
72           return true;
73         // Non-equal FrameIndexes - If both frame indices are fixed
74         // we know their relative offsets and can compare them. Otherwise
75         // we must be conservative.
76         if (MFI.isFixedObjectIndex(A->getIndex()) &&
77             MFI.isFixedObjectIndex(B->getIndex())) {
78           Off += MFI.getObjectOffset(B->getIndex()) -
79                  MFI.getObjectOffset(A->getIndex());
80           return true;
81         }
82       }
83   }
84   return false;
85 }
86 
87 bool BaseIndexOffset::computeAliasing(const SDNode *Op0,
88                                       const Optional<int64_t> NumBytes0,
89                                       const SDNode *Op1,
90                                       const Optional<int64_t> NumBytes1,
91                                       const SelectionDAG &DAG, bool &IsAlias) {
92 
93   BaseIndexOffset BasePtr0 = match(Op0, DAG);
94   BaseIndexOffset BasePtr1 = match(Op1, DAG);
95 
96   if (!(BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()))
97     return false;
98   int64_t PtrDiff;
99   if (NumBytes0.hasValue() && NumBytes1.hasValue() &&
100       BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) {
101     // If the size of memory access is unknown, do not use it to analysis.
102     // One example of unknown size memory access is to load/store scalable
103     // vector objects on the stack.
104     // BasePtr1 is PtrDiff away from BasePtr0. They alias if none of the
105     // following situations arise:
106     if (PtrDiff >= 0 &&
107         *NumBytes0 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
108       // [----BasePtr0----]
109       //                         [---BasePtr1--]
110       // ========PtrDiff========>
111       IsAlias = !(*NumBytes0 <= PtrDiff);
112       return true;
113     }
114     if (PtrDiff < 0 &&
115         *NumBytes1 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
116       //                     [----BasePtr0----]
117       // [---BasePtr1--]
118       // =====(-PtrDiff)====>
119       IsAlias = !((PtrDiff + *NumBytes1) <= 0);
120       return true;
121     }
122     return false;
123   }
124   // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
125   // able to calculate their relative offset if at least one arises
126   // from an alloca. However, these allocas cannot overlap and we
127   // can infer there is no alias.
128   if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
129     if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
130       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
131       // If the base are the same frame index but the we couldn't find a
132       // constant offset, (indices are different) be conservative.
133       if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
134                      !MFI.isFixedObjectIndex(B->getIndex()))) {
135         IsAlias = false;
136         return true;
137       }
138     }
139 
140   bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
141   bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
142   bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
143   bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
144   bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
145   bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
146 
147   if ((IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) {
148     // We can derive NoAlias In case of mismatched base types.
149     if (IsFI0 != IsFI1 || IsGV0 != IsGV1 || IsCV0 != IsCV1) {
150       IsAlias = false;
151       return true;
152     }
153     // We cannot safely determine whether the pointers alias if we compare two
154     // global values and at least one is a GlobalAlias.
155     if (IsGV0 && IsGV1 &&
156         (isa<GlobalAlias>(
157              cast<GlobalAddressSDNode>(BasePtr0.getBase())->getGlobal()) ||
158          isa<GlobalAlias>(
159              cast<GlobalAddressSDNode>(BasePtr1.getBase())->getGlobal())))
160       return false;
161     // If checkable indices we can check they do not alias.
162     // FIXME: Please describe this a bit better. Looks weird to say that there
163     // is no alias if the indices are the same. Is this code assuming that
164     // someone has checked that the base isn't the same as a precondition? And
165     // what about offsets? And what about NumBytes0 and NumBytest1 (can we
166     // really derive NoAlias here if we do not even know how many bytes that are
167     // dereferenced)?
168     if (BasePtr0.getIndex() == BasePtr1.getIndex()) {
169       IsAlias = false;
170       return true;
171     }
172   }
173   return false; // Cannot determine whether the pointers alias.
174 }
175 
176 bool BaseIndexOffset::contains(const SelectionDAG &DAG, int64_t BitSize,
177                                const BaseIndexOffset &Other,
178                                int64_t OtherBitSize, int64_t &BitOffset) const {
179   int64_t Offset;
180   if (!equalBaseIndex(Other, DAG, Offset))
181     return false;
182   if (Offset >= 0) {
183     // Other is after *this:
184     // [-------*this---------]
185     //            [---Other--]
186     // ==Offset==>
187     BitOffset = 8 * Offset;
188     return BitOffset + OtherBitSize <= BitSize;
189   }
190   // Other starts strictly before *this, it cannot be fully contained.
191   //    [-------*this---------]
192   // [--Other--]
193   return false;
194 }
195 
196 /// Parses tree in Ptr for base, index, offset addresses.
197 static BaseIndexOffset matchLSNode(const LSBaseSDNode *N,
198                                    const SelectionDAG &DAG) {
199   SDValue Ptr = N->getBasePtr();
200 
201   // (((B + I*M) + c)) + c ...
202   SDValue Base = DAG.getTargetLoweringInfo().unwrapAddress(Ptr);
203   SDValue Index = SDValue();
204   int64_t Offset = 0;
205   bool IsIndexSignExt = false;
206 
207   // pre-inc/pre-dec ops are components of EA.
208   if (N->getAddressingMode() == ISD::PRE_INC) {
209     if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
210       Offset += C->getSExtValue();
211     else // If unknown, give up now.
212       return BaseIndexOffset(SDValue(), SDValue(), 0, false);
213   } else if (N->getAddressingMode() == ISD::PRE_DEC) {
214     if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
215       Offset -= C->getSExtValue();
216     else // If unknown, give up now.
217       return BaseIndexOffset(SDValue(), SDValue(), 0, false);
218   }
219 
220   // Consume constant adds & ors with appropriate masking.
221   while (true) {
222     switch (Base->getOpcode()) {
223     case ISD::OR:
224       // Only consider ORs which act as adds.
225       if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1)))
226         if (DAG.MaskedValueIsZero(Base->getOperand(0), C->getAPIntValue())) {
227           Offset += C->getSExtValue();
228           Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
229           continue;
230         }
231       break;
232     case ISD::ADD:
233       if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1))) {
234         Offset += C->getSExtValue();
235         Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
236         continue;
237       }
238       break;
239     case ISD::LOAD:
240     case ISD::STORE: {
241       auto *LSBase = cast<LSBaseSDNode>(Base.getNode());
242       unsigned int IndexResNo = (Base->getOpcode() == ISD::LOAD) ? 1 : 0;
243       if (LSBase->isIndexed() && Base.getResNo() == IndexResNo)
244         if (auto *C = dyn_cast<ConstantSDNode>(LSBase->getOffset())) {
245           auto Off = C->getSExtValue();
246           if (LSBase->getAddressingMode() == ISD::PRE_DEC ||
247               LSBase->getAddressingMode() == ISD::POST_DEC)
248             Offset -= Off;
249           else
250             Offset += Off;
251           Base = DAG.getTargetLoweringInfo().unwrapAddress(LSBase->getBasePtr());
252           continue;
253         }
254       break;
255     }
256     }
257     // If we get here break out of the loop.
258     break;
259   }
260 
261   if (Base->getOpcode() == ISD::ADD) {
262     // TODO: The following code appears to be needless as it just
263     //       bails on some Ptrs early, reducing the cases where we
264     //       find equivalence. We should be able to remove this.
265     // Inside a loop the current BASE pointer is calculated using an ADD and a
266     // MUL instruction. In this case Base is the actual BASE pointer.
267     // (i64 add (i64 %array_ptr)
268     //          (i64 mul (i64 %induction_var)
269     //                   (i64 %element_size)))
270     if (Base->getOperand(1)->getOpcode() == ISD::MUL)
271       return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
272 
273     // Look at Base + Index + Offset cases.
274     Index = Base->getOperand(1);
275     SDValue PotentialBase = Base->getOperand(0);
276 
277     // Skip signextends.
278     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
279       Index = Index->getOperand(0);
280       IsIndexSignExt = true;
281     }
282 
283     // Check if Index Offset pattern
284     if (Index->getOpcode() != ISD::ADD ||
285         !isa<ConstantSDNode>(Index->getOperand(1)))
286       return BaseIndexOffset(PotentialBase, Index, Offset, IsIndexSignExt);
287 
288     Offset += cast<ConstantSDNode>(Index->getOperand(1))->getSExtValue();
289     Index = Index->getOperand(0);
290     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
291       Index = Index->getOperand(0);
292       IsIndexSignExt = true;
293     } else
294       IsIndexSignExt = false;
295     Base = PotentialBase;
296   }
297   return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
298 }
299 
300 BaseIndexOffset BaseIndexOffset::match(const SDNode *N,
301                                        const SelectionDAG &DAG) {
302   if (const auto *LS0 = dyn_cast<LSBaseSDNode>(N))
303     return matchLSNode(LS0, DAG);
304   if (const auto *LN = dyn_cast<LifetimeSDNode>(N)) {
305     if (LN->hasOffset())
306       return BaseIndexOffset(LN->getOperand(1), SDValue(), LN->getOffset(),
307                              false);
308     return BaseIndexOffset(LN->getOperand(1), SDValue(), false);
309   }
310   return BaseIndexOffset();
311 }
312 
313 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
314 
315 LLVM_DUMP_METHOD void BaseIndexOffset::dump() const {
316   print(dbgs());
317 }
318 
319 void BaseIndexOffset::print(raw_ostream& OS) const {
320   OS << "BaseIndexOffset base=[";
321   Base->print(OS);
322   OS << "] index=[";
323   if (Index)
324     Index->print(OS);
325   OS << "] offset=" << Offset;
326 }
327 
328 #endif
329