LLVM 23.0.0git
Operator.cpp
Go to the documentation of this file.
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"
18
19#include "ConstantsContext.h"
20
21using namespace llvm;
22
24 switch (getOpcode()) {
25 case Instruction::Add:
26 case Instruction::Sub:
27 case Instruction::Mul:
28 case Instruction::Shl: {
29 auto *OBO = cast<OverflowingBinaryOperator>(this);
30 return OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap();
31 }
32 case Instruction::Trunc: {
33 if (auto *TI = dyn_cast<TruncInst>(this))
34 return TI->hasNoUnsignedWrap() || TI->hasNoSignedWrap();
35 return false;
36 }
37 case Instruction::UDiv:
38 case Instruction::SDiv:
39 case Instruction::AShr:
40 case Instruction::LShr:
41 return cast<PossiblyExactOperator>(this)->isExact();
42 case Instruction::Or:
43 return cast<PossiblyDisjointInst>(this)->isDisjoint();
44 case Instruction::GetElementPtr: {
45 auto *GEP = cast<GEPOperator>(this);
46 // Note: inrange exists on constexpr only
47 return GEP->getNoWrapFlags() != GEPNoWrapFlags::none() ||
48 GEP->getInRange() != std::nullopt;
49 }
50 case Instruction::UIToFP:
51 case Instruction::ZExt:
52 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(this))
53 return NNI->hasNonNeg();
54 return false;
55 case Instruction::ICmp:
56 return cast<ICmpInst>(this)->hasSameSign();
57 case Instruction::Call:
58 if (auto *II = dyn_cast<IntrinsicInst>(this)) {
59 switch (II->getIntrinsicID()) {
60 case Intrinsic::ctlz:
61 case Intrinsic::cttz:
62 case Intrinsic::abs:
63 return cast<ConstantInt>(II->getArgOperand(1))->isOneValue();
64 }
65 }
66 [[fallthrough]];
67 default:
68 if (const auto *FP = dyn_cast<FPMathOperator>(this))
69 return FP->hasNoNaNs() || FP->hasNoInfs();
70 return false;
71 }
72}
73
76 return true;
77 auto *I = dyn_cast<Instruction>(this);
78 return I && (I->hasPoisonGeneratingAttributes() ||
79 I->hasPoisonGeneratingMetadata());
80}
81
83 if (auto *I = dyn_cast<GetElementPtrInst>(this))
84 return I->getSourceElementType();
85 return cast<GetElementPtrConstantExpr>(this)->getSourceElementType();
86}
87
89 if (auto *I = dyn_cast<GetElementPtrInst>(this))
90 return I->getResultElementType();
91 return cast<GetElementPtrConstantExpr>(this)->getResultElementType();
92}
93
94std::optional<ConstantRange> GEPOperator::getInRange() const {
95 if (auto *CE = dyn_cast<GetElementPtrConstantExpr>(this))
96 return CE->getInRange();
97 return std::nullopt;
98}
99
101 /// compute the worse possible offset for every level of the GEP et accumulate
102 /// the minimum alignment into Result.
103
105 for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
106 GTI != GTE; ++GTI) {
108 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
109
110 if (StructType *STy = GTI.getStructTypeOrNull()) {
111 const StructLayout *SL = DL.getStructLayout(STy);
112 Offset =
114 } else {
115 assert(GTI.isSequential() && "should be sequencial");
116 /// If the index isn't known, we take 1 because it is the index that will
117 /// give the worse alignment of the offset.
118 const uint64_t ElemCount = OpC ? OpC->getLimitedValue() : 1;
119 Offset = GTI.getSequentialElementStride(DL) * ElemCount;
120 }
121 Result = Align(MinAlign(Offset, Result.value()));
122 }
123 return Result;
124}
125
127 const DataLayout &DL, APInt &Offset,
128 function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
129 assert(Offset.getBitWidth() ==
130 DL.getIndexSizeInBits(getPointerAddressSpace()) &&
131 "The offset bit width does not match DL specification.");
134 DL, Offset, ExternalAnalysis);
135}
136
138 Type *SourceType, ArrayRef<const Value *> Index, const DataLayout &DL,
139 APInt &Offset, function_ref<bool(Value &, APInt &)> ExternalAnalysis) {
140 // Fast path for canonical getelementptr i8 form.
141 if (SourceType->isIntegerTy(8) && !Index.empty() && !ExternalAnalysis) {
142 auto *CI = dyn_cast<ConstantInt>(Index.front());
143 if (CI && CI->getType()->isIntegerTy()) {
144 Offset += CI->getValue().sextOrTrunc(Offset.getBitWidth());
145 return true;
146 }
147 return false;
148 }
149
150 bool UsedExternalAnalysis = false;
151 auto AccumulateOffset = [&](APInt Index, uint64_t Size) -> bool {
152 Index = Index.sextOrTrunc(Offset.getBitWidth());
153 // Truncate if type size exceeds index space.
154 APInt IndexedSize(Offset.getBitWidth(), Size, /*isSigned=*/false,
155 /*implcitTrunc=*/true);
156 // For array or vector indices, scale the index by the size of the type.
157 if (!UsedExternalAnalysis) {
158 Offset += Index * IndexedSize;
159 } else {
160 // External Analysis can return a result higher/lower than the value
161 // represents. We need to detect overflow/underflow.
162 bool Overflow = false;
163 APInt OffsetPlus = Index.smul_ov(IndexedSize, Overflow);
164 if (Overflow)
165 return false;
166 Offset = Offset.sadd_ov(OffsetPlus, Overflow);
167 if (Overflow)
168 return false;
169 }
170 return true;
171 };
172 auto begin = generic_gep_type_iterator<decltype(Index.begin())>::begin(
173 SourceType, Index.begin());
174 auto end = generic_gep_type_iterator<decltype(Index.end())>::end(Index.end());
175 for (auto GTI = begin, GTE = end; GTI != GTE; ++GTI) {
176 // Scalable vectors are multiplied by a runtime constant.
177 bool ScalableType = GTI.getIndexedType()->isScalableTy();
178
179 Value *V = GTI.getOperand();
180 StructType *STy = GTI.getStructTypeOrNull();
181 // Handle ConstantInt if possible.
182 auto *ConstOffset = dyn_cast<ConstantInt>(V);
183 if (ConstOffset && ConstOffset->getType()->isIntegerTy()) {
184 if (ConstOffset->isZero())
185 continue;
186 // if the type is scalable and the constant is not zero (vscale * n * 0 =
187 // 0) bailout.
188 if (ScalableType)
189 return false;
190 // Handle a struct index, which adds its field offset to the pointer.
191 if (STy) {
192 unsigned ElementIdx = ConstOffset->getZExtValue();
193 const StructLayout *SL = DL.getStructLayout(STy);
194 // Element offset is in bytes.
195 if (!AccumulateOffset(
196 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx)),
197 1))
198 return false;
199 continue;
200 }
201 if (!AccumulateOffset(ConstOffset->getValue(),
202 GTI.getSequentialElementStride(DL)))
203 return false;
204 continue;
205 }
206
207 // The operand is not constant, check if an external analysis was provided.
208 // External analsis is not applicable to a struct type.
209 if (!ExternalAnalysis || STy || ScalableType)
210 return false;
211 APInt AnalysisIndex;
212 if (!ExternalAnalysis(*V, AnalysisIndex))
213 return false;
214 UsedExternalAnalysis = true;
215 if (!AccumulateOffset(AnalysisIndex, GTI.getSequentialElementStride(DL)))
216 return false;
217 }
218 return true;
219}
220
222 const DataLayout &DL, unsigned BitWidth,
223 SmallMapVector<Value *, APInt, 4> &VariableOffsets,
224 APInt &ConstantOffset) const {
225 assert(BitWidth == DL.getIndexSizeInBits(getPointerAddressSpace()) &&
226 "The offset bit width does not match DL specification.");
227
228 auto CollectConstantOffset = [&](APInt Index, uint64_t Size) {
229 Index = Index.sextOrTrunc(BitWidth);
230 // Truncate if type size exceeds index space.
231 APInt IndexedSize(BitWidth, Size, /*isSigned=*/false,
232 /*implcitTrunc=*/true);
233 ConstantOffset += Index * IndexedSize;
234 };
235
236 for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
237 GTI != GTE; ++GTI) {
238 // Scalable vectors are multiplied by a runtime constant.
239 bool ScalableType = GTI.getIndexedType()->isScalableTy();
240
241 Value *V = GTI.getOperand();
242 StructType *STy = GTI.getStructTypeOrNull();
243 // Handle ConstantInt if possible.
244 auto *ConstOffset = dyn_cast<ConstantInt>(V);
245 if (ConstOffset && ConstOffset->getType()->isIntegerTy()) {
246 if (ConstOffset->isZero())
247 continue;
248 // If the type is scalable and the constant is not zero (vscale * n * 0 =
249 // 0) bailout.
250 // TODO: If the runtime value is accessible at any point before DWARF
251 // emission, then we could potentially keep a forward reference to it
252 // in the debug value to be filled in later.
253 if (ScalableType)
254 return false;
255 // Handle a struct index, which adds its field offset to the pointer.
256 if (STy) {
257 unsigned ElementIdx = ConstOffset->getZExtValue();
258 const StructLayout *SL = DL.getStructLayout(STy);
259 // Element offset is in bytes.
260 CollectConstantOffset(APInt(BitWidth, SL->getElementOffset(ElementIdx)),
261 1);
262 continue;
263 }
264 CollectConstantOffset(ConstOffset->getValue(),
265 GTI.getSequentialElementStride(DL));
266 continue;
267 }
268
269 if (STy || ScalableType)
270 return false;
271 // Truncate if type size exceeds index space.
272 APInt IndexedSize(BitWidth, GTI.getSequentialElementStride(DL),
273 /*isSigned=*/false, /*implicitTrunc=*/true);
274 // Insert an initial offset of 0 for V iff none exists already, then
275 // increment the offset by IndexedSize.
276 if (!IndexedSize.isZero()) {
277 auto *It = VariableOffsets.insert({V, APInt(BitWidth, 0)}).first;
278 It->second += IndexedSize;
279 }
280 }
281 return true;
282}
283
285 if (all())
286 O << " fast";
287 else {
288 if (allowReassoc())
289 O << " reassoc";
290 if (noNaNs())
291 O << " nnan";
292 if (noInfs())
293 O << " ninf";
294 if (noSignedZeros())
295 O << " nsz";
296 if (allowReciprocal())
297 O << " arcp";
298 if (allowContract())
299 O << " contract";
300 if (approxFunc())
301 O << " afn";
302 }
303}
304
305FastMathFlags &FPMathOperator::getFastMathFlagsImpl() {
306 auto *I = cast<Instruction>(this);
307
309 return Op->FMF;
311 return Op->FMF;
313 return Op->FMF;
315 return Op->FMF;
317 return Op->FMF;
319 return Op->FMF;
321 return Op->FMF;
323 return Op->FMF;
325 return Op->FMF;
327 return Op->FMF;
328
329 llvm_unreachable("Unknown FPMathOperator!");
330}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Hexagon Common GEP
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
Definition APInt.cpp:645
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1563
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1995
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Provide fast-math flags storage, instructions that support fast-math flags should inherit from this c...
Definition InstrTypes.h:56
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
LLVM_ABI void print(raw_ostream &O) const
Print fast-math flags to O.
Definition Operator.cpp:284
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
bool all() const
Definition FMF.h:58
bool allowReciprocal() const
Definition FMF.h:68
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
bool approxFunc() const
Definition FMF.h:70
bool noNaNs() const
Definition FMF.h:65
bool allowContract() const
Definition FMF.h:69
static GEPNoWrapFlags none()
LLVM_ABI std::optional< ConstantRange > getInRange() const
Returns the offset of the index with an inrange attachment, or std::nullopt if none.
Definition Operator.cpp:94
LLVM_ABI bool collectOffset(const DataLayout &DL, unsigned BitWidth, SmallMapVector< Value *, APInt, 4 > &VariableOffsets, APInt &ConstantOffset) const
Collect the offset of this GEP as a map of Values to their associated APInt multipliers,...
Definition Operator.cpp:221
LLVM_ABI Type * getResultElementType() const
Definition Operator.cpp:88
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:82
LLVM_ABI Align getMaxPreservedAlignment(const DataLayout &DL) const
Compute the maximum alignment that this GEP is garranteed to preserve.
Definition Operator.cpp:100
LLVM_ABI bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset, function_ref< bool(Value &, APInt &)> ExternalAnalysis=nullptr) const
Accumulate the constant address offset of this GEP if possible.
Definition Operator.cpp:126
unsigned getPointerAddressSpace() const
Method to return the address space of the pointer operand.
Definition Operator.h:436
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
LLVM_ABI bool hasPoisonGeneratingFlags() const
Return true if this operator has flags which may cause this operator to evaluate to poison despite ha...
Definition Operator.cpp:23
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
LLVM_ABI bool hasPoisonGeneratingAnnotations() const
Return true if this operator has poison-generating flags, return attributes or metadata.
Definition Operator.cpp:74
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
iterator_range< value_op_iterator > operand_values()
Definition User.h:291
LLVM Value Representation.
Definition Value.h:75
static constexpr uint64_t MaximumAlignment
Definition Value.h:799
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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:315
@ Offset
Definition DWP.cpp:558
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
gep_type_iterator gep_type_end(const User *GEP)
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:357
generic_gep_type_iterator<> gep_type_iterator
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342