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