xref: /freebsd-src/contrib/llvm-project/llvm/lib/IR/Operator.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
1 //===-- Operator.cpp - Implement the LLVM operators -----------------------===//
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 the non-inline methods for the LLVM Operator classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/Operator.h"
14 #include "llvm/IR/DataLayout.h"
15 #include "llvm/IR/GetElementPtrTypeIterator.h"
16 #include "llvm/IR/Instructions.h"
17 #include "llvm/IR/Type.h"
18 
19 #include "ConstantsContext.h"
20 
21 namespace llvm {
22 bool Operator::hasPoisonGeneratingFlags() const {
23   switch (getOpcode()) {
24   case Instruction::Add:
25   case Instruction::Sub:
26   case Instruction::Mul:
27   case Instruction::Shl: {
28     auto *OBO = cast<OverflowingBinaryOperator>(this);
29     return OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap();
30   }
31   case Instruction::UDiv:
32   case Instruction::SDiv:
33   case Instruction::AShr:
34   case Instruction::LShr:
35     return cast<PossiblyExactOperator>(this)->isExact();
36   case Instruction::GetElementPtr: {
37     auto *GEP = cast<GEPOperator>(this);
38     // Note: inrange exists on constexpr only
39     return GEP->isInBounds() || GEP->getInRangeIndex() != None;
40   }
41   default:
42     if (const auto *FP = dyn_cast<FPMathOperator>(this))
43       return FP->hasNoNaNs() || FP->hasNoInfs();
44     return false;
45   }
46 }
47 
48 Type *GEPOperator::getSourceElementType() const {
49   if (auto *I = dyn_cast<GetElementPtrInst>(this))
50     return I->getSourceElementType();
51   return cast<GetElementPtrConstantExpr>(this)->getSourceElementType();
52 }
53 
54 Type *GEPOperator::getResultElementType() const {
55   if (auto *I = dyn_cast<GetElementPtrInst>(this))
56     return I->getResultElementType();
57   return cast<GetElementPtrConstantExpr>(this)->getResultElementType();
58 }
59 
60 Align GEPOperator::getMaxPreservedAlignment(const DataLayout &DL) const {
61   /// compute the worse possible offset for every level of the GEP et accumulate
62   /// the minimum alignment into Result.
63 
64   Align Result = Align(llvm::Value::MaximumAlignment);
65   for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
66        GTI != GTE; ++GTI) {
67     int64_t Offset = 1;
68     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
69 
70     if (StructType *STy = GTI.getStructTypeOrNull()) {
71       const StructLayout *SL = DL.getStructLayout(STy);
72       Offset = SL->getElementOffset(OpC->getZExtValue());
73     } else {
74       assert(GTI.isSequential() && "should be sequencial");
75       /// If the index isn't know we take 1 because it is the index that will
76       /// give the worse alignment of the offset.
77       int64_t ElemCount = 1;
78       if (OpC)
79         ElemCount = OpC->getZExtValue();
80       Offset = DL.getTypeAllocSize(GTI.getIndexedType()) * ElemCount;
81     }
82     Result = Align(MinAlign(Offset, Result.value()));
83   }
84   return Result;
85 }
86 
87 bool GEPOperator::accumulateConstantOffset(
88     const DataLayout &DL, APInt &Offset,
89     function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
90   assert(Offset.getBitWidth() ==
91              DL.getIndexSizeInBits(getPointerAddressSpace()) &&
92          "The offset bit width does not match DL specification.");
93   SmallVector<const Value *> Index(llvm::drop_begin(operand_values()));
94   return GEPOperator::accumulateConstantOffset(getSourceElementType(), Index,
95                                                DL, Offset, ExternalAnalysis);
96 }
97 
98 bool GEPOperator::accumulateConstantOffset(
99     Type *SourceType, ArrayRef<const Value *> Index, const DataLayout &DL,
100     APInt &Offset, function_ref<bool(Value &, APInt &)> ExternalAnalysis) {
101   bool UsedExternalAnalysis = false;
102   auto AccumulateOffset = [&](APInt Index, uint64_t Size) -> bool {
103     Index = Index.sextOrTrunc(Offset.getBitWidth());
104     APInt IndexedSize = APInt(Offset.getBitWidth(), Size);
105     // For array or vector indices, scale the index by the size of the type.
106     if (!UsedExternalAnalysis) {
107       Offset += Index * IndexedSize;
108     } else {
109       // External Analysis can return a result higher/lower than the value
110       // represents. We need to detect overflow/underflow.
111       bool Overflow = false;
112       APInt OffsetPlus = Index.smul_ov(IndexedSize, Overflow);
113       if (Overflow)
114         return false;
115       Offset = Offset.sadd_ov(OffsetPlus, Overflow);
116       if (Overflow)
117         return false;
118     }
119     return true;
120   };
121   auto begin = generic_gep_type_iterator<decltype(Index.begin())>::begin(
122       SourceType, Index.begin());
123   auto end = generic_gep_type_iterator<decltype(Index.end())>::end(Index.end());
124   for (auto GTI = begin, GTE = end; GTI != GTE; ++GTI) {
125     // Scalable vectors are multiplied by a runtime constant.
126     bool ScalableType = false;
127     if (isa<ScalableVectorType>(GTI.getIndexedType()))
128       ScalableType = true;
129 
130     Value *V = GTI.getOperand();
131     StructType *STy = GTI.getStructTypeOrNull();
132     // Handle ConstantInt if possible.
133     if (auto ConstOffset = dyn_cast<ConstantInt>(V)) {
134       if (ConstOffset->isZero())
135         continue;
136       // if the type is scalable and the constant is not zero (vscale * n * 0 =
137       // 0) bailout.
138       if (ScalableType)
139         return false;
140       // Handle a struct index, which adds its field offset to the pointer.
141       if (STy) {
142         unsigned ElementIdx = ConstOffset->getZExtValue();
143         const StructLayout *SL = DL.getStructLayout(STy);
144         // Element offset is in bytes.
145         if (!AccumulateOffset(
146                 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx)),
147                 1))
148           return false;
149         continue;
150       }
151       if (!AccumulateOffset(ConstOffset->getValue(),
152                             DL.getTypeAllocSize(GTI.getIndexedType())))
153         return false;
154       continue;
155     }
156 
157     // The operand is not constant, check if an external analysis was provided.
158     // External analsis is not applicable to a struct type.
159     if (!ExternalAnalysis || STy || ScalableType)
160       return false;
161     APInt AnalysisIndex;
162     if (!ExternalAnalysis(*V, AnalysisIndex))
163       return false;
164     UsedExternalAnalysis = true;
165     if (!AccumulateOffset(AnalysisIndex,
166                           DL.getTypeAllocSize(GTI.getIndexedType())))
167       return false;
168   }
169   return true;
170 }
171 
172 bool GEPOperator::collectOffset(
173     const DataLayout &DL, unsigned BitWidth,
174     MapVector<Value *, APInt> &VariableOffsets,
175     APInt &ConstantOffset) const {
176   assert(BitWidth == DL.getIndexSizeInBits(getPointerAddressSpace()) &&
177          "The offset bit width does not match DL specification.");
178 
179   auto CollectConstantOffset = [&](APInt Index, uint64_t Size) {
180     Index = Index.sextOrTrunc(BitWidth);
181     APInt IndexedSize = APInt(BitWidth, Size);
182     ConstantOffset += Index * IndexedSize;
183   };
184 
185   for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
186        GTI != GTE; ++GTI) {
187     // Scalable vectors are multiplied by a runtime constant.
188     bool ScalableType = isa<ScalableVectorType>(GTI.getIndexedType());
189 
190     Value *V = GTI.getOperand();
191     StructType *STy = GTI.getStructTypeOrNull();
192     // Handle ConstantInt if possible.
193     if (auto ConstOffset = dyn_cast<ConstantInt>(V)) {
194       if (ConstOffset->isZero())
195         continue;
196       // If the type is scalable and the constant is not zero (vscale * n * 0 =
197       // 0) bailout.
198       // TODO: If the runtime value is accessible at any point before DWARF
199       // emission, then we could potentially keep a forward reference to it
200       // in the debug value to be filled in later.
201       if (ScalableType)
202         return false;
203       // Handle a struct index, which adds its field offset to the pointer.
204       if (STy) {
205         unsigned ElementIdx = ConstOffset->getZExtValue();
206         const StructLayout *SL = DL.getStructLayout(STy);
207         // Element offset is in bytes.
208         CollectConstantOffset(APInt(BitWidth, SL->getElementOffset(ElementIdx)),
209                               1);
210         continue;
211       }
212       CollectConstantOffset(ConstOffset->getValue(),
213                             DL.getTypeAllocSize(GTI.getIndexedType()));
214       continue;
215     }
216 
217     if (STy || ScalableType)
218       return false;
219     APInt IndexedSize =
220         APInt(BitWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
221     // Insert an initial offset of 0 for V iff none exists already, then
222     // increment the offset by IndexedSize.
223     if (!IndexedSize.isZero()) {
224       VariableOffsets.insert({V, APInt(BitWidth, 0)});
225       VariableOffsets[V] += IndexedSize;
226     }
227   }
228   return true;
229 }
230 
231 void FastMathFlags::print(raw_ostream &O) const {
232   if (all())
233     O << " fast";
234   else {
235     if (allowReassoc())
236       O << " reassoc";
237     if (noNaNs())
238       O << " nnan";
239     if (noInfs())
240       O << " ninf";
241     if (noSignedZeros())
242       O << " nsz";
243     if (allowReciprocal())
244       O << " arcp";
245     if (allowContract())
246       O << " contract";
247     if (approxFunc())
248       O << " afn";
249   }
250 }
251 } // namespace llvm
252