LLVM 18.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"
17
18#include "ConstantsContext.h"
19
20namespace llvm {
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::UDiv:
31 case Instruction::SDiv:
32 case Instruction::AShr:
33 case Instruction::LShr:
34 return cast<PossiblyExactOperator>(this)->isExact();
35 case Instruction::GetElementPtr: {
36 auto *GEP = cast<GEPOperator>(this);
37 // Note: inrange exists on constexpr only
38 return GEP->isInBounds() || GEP->getInRangeIndex() != std::nullopt;
39 }
40 default:
41 if (const auto *FP = dyn_cast<FPMathOperator>(this))
42 return FP->hasNoNaNs() || FP->hasNoInfs();
43 return false;
44 }
45}
46
49 return true;
50 auto *I = dyn_cast<Instruction>(this);
51 return I && I->hasPoisonGeneratingMetadata();
52}
53
55 if (auto *I = dyn_cast<GetElementPtrInst>(this))
56 return I->getSourceElementType();
57 return cast<GetElementPtrConstantExpr>(this)->getSourceElementType();
58}
59
61 if (auto *I = dyn_cast<GetElementPtrInst>(this))
62 return I->getResultElementType();
63 return cast<GetElementPtrConstantExpr>(this)->getResultElementType();
64}
65
67 /// compute the worse possible offset for every level of the GEP et accumulate
68 /// the minimum alignment into Result.
69
71 for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
72 GTI != GTE; ++GTI) {
74 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
75
76 if (StructType *STy = GTI.getStructTypeOrNull()) {
77 const StructLayout *SL = DL.getStructLayout(STy);
79 } else {
80 assert(GTI.isSequential() && "should be sequencial");
81 /// If the index isn't known, we take 1 because it is the index that will
82 /// give the worse alignment of the offset.
83 const uint64_t ElemCount = OpC ? OpC->getZExtValue() : 1;
84 Offset = DL.getTypeAllocSize(GTI.getIndexedType()) * ElemCount;
85 }
86 Result = Align(MinAlign(Offset, Result.value()));
87 }
88 return Result;
89}
90
92 const DataLayout &DL, APInt &Offset,
93 function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
94 assert(Offset.getBitWidth() ==
95 DL.getIndexSizeInBits(getPointerAddressSpace()) &&
96 "The offset bit width does not match DL specification.");
99 DL, Offset, ExternalAnalysis);
100}
101
103 Type *SourceType, ArrayRef<const Value *> Index, const DataLayout &DL,
104 APInt &Offset, function_ref<bool(Value &, APInt &)> ExternalAnalysis) {
105 bool UsedExternalAnalysis = false;
106 auto AccumulateOffset = [&](APInt Index, uint64_t Size) -> bool {
107 Index = Index.sextOrTrunc(Offset.getBitWidth());
108 APInt IndexedSize = APInt(Offset.getBitWidth(), Size);
109 // For array or vector indices, scale the index by the size of the type.
110 if (!UsedExternalAnalysis) {
111 Offset += Index * IndexedSize;
112 } else {
113 // External Analysis can return a result higher/lower than the value
114 // represents. We need to detect overflow/underflow.
115 bool Overflow = false;
116 APInt OffsetPlus = Index.smul_ov(IndexedSize, Overflow);
117 if (Overflow)
118 return false;
119 Offset = Offset.sadd_ov(OffsetPlus, Overflow);
120 if (Overflow)
121 return false;
122 }
123 return true;
124 };
125 auto begin = generic_gep_type_iterator<decltype(Index.begin())>::begin(
126 SourceType, Index.begin());
127 auto end = generic_gep_type_iterator<decltype(Index.end())>::end(Index.end());
128 for (auto GTI = begin, GTE = end; GTI != GTE; ++GTI) {
129 // Scalable vectors are multiplied by a runtime constant.
130 bool ScalableType = GTI.getIndexedType()->isScalableTy();
131
132 Value *V = GTI.getOperand();
133 StructType *STy = GTI.getStructTypeOrNull();
134 // Handle ConstantInt if possible.
135 if (auto ConstOffset = dyn_cast<ConstantInt>(V)) {
136 if (ConstOffset->isZero())
137 continue;
138 // if the type is scalable and the constant is not zero (vscale * n * 0 =
139 // 0) bailout.
140 if (ScalableType)
141 return false;
142 // Handle a struct index, which adds its field offset to the pointer.
143 if (STy) {
144 unsigned ElementIdx = ConstOffset->getZExtValue();
145 const StructLayout *SL = DL.getStructLayout(STy);
146 // Element offset is in bytes.
147 if (!AccumulateOffset(
148 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx)),
149 1))
150 return false;
151 continue;
152 }
153 if (!AccumulateOffset(ConstOffset->getValue(),
154 DL.getTypeAllocSize(GTI.getIndexedType())))
155 return false;
156 continue;
157 }
158
159 // The operand is not constant, check if an external analysis was provided.
160 // External analsis is not applicable to a struct type.
161 if (!ExternalAnalysis || STy || ScalableType)
162 return false;
163 APInt AnalysisIndex;
164 if (!ExternalAnalysis(*V, AnalysisIndex))
165 return false;
166 UsedExternalAnalysis = true;
167 if (!AccumulateOffset(AnalysisIndex,
168 DL.getTypeAllocSize(GTI.getIndexedType())))
169 return false;
170 }
171 return true;
172}
173
175 const DataLayout &DL, unsigned BitWidth,
176 MapVector<Value *, APInt> &VariableOffsets,
177 APInt &ConstantOffset) const {
178 assert(BitWidth == DL.getIndexSizeInBits(getPointerAddressSpace()) &&
179 "The offset bit width does not match DL specification.");
180
181 auto CollectConstantOffset = [&](APInt Index, uint64_t Size) {
182 Index = Index.sextOrTrunc(BitWidth);
183 APInt IndexedSize = APInt(BitWidth, Size);
184 ConstantOffset += Index * IndexedSize;
185 };
186
187 for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
188 GTI != GTE; ++GTI) {
189 // Scalable vectors are multiplied by a runtime constant.
190 bool ScalableType = GTI.getIndexedType()->isScalableTy();
191
192 Value *V = GTI.getOperand();
193 StructType *STy = GTI.getStructTypeOrNull();
194 // Handle ConstantInt if possible.
195 if (auto ConstOffset = dyn_cast<ConstantInt>(V)) {
196 if (ConstOffset->isZero())
197 continue;
198 // If the type is scalable and the constant is not zero (vscale * n * 0 =
199 // 0) bailout.
200 // TODO: If the runtime value is accessible at any point before DWARF
201 // emission, then we could potentially keep a forward reference to it
202 // in the debug value to be filled in later.
203 if (ScalableType)
204 return false;
205 // Handle a struct index, which adds its field offset to the pointer.
206 if (STy) {
207 unsigned ElementIdx = ConstOffset->getZExtValue();
208 const StructLayout *SL = DL.getStructLayout(STy);
209 // Element offset is in bytes.
210 CollectConstantOffset(APInt(BitWidth, SL->getElementOffset(ElementIdx)),
211 1);
212 continue;
213 }
214 CollectConstantOffset(ConstOffset->getValue(),
215 DL.getTypeAllocSize(GTI.getIndexedType()));
216 continue;
217 }
218
219 if (STy || ScalableType)
220 return false;
221 APInt IndexedSize =
222 APInt(BitWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
223 // Insert an initial offset of 0 for V iff none exists already, then
224 // increment the offset by IndexedSize.
225 if (!IndexedSize.isZero()) {
226 VariableOffsets.insert({V, APInt(BitWidth, 0)});
227 VariableOffsets[V] += IndexedSize;
228 }
229 }
230 return true;
231}
232
234 if (all())
235 O << " fast";
236 else {
237 if (allowReassoc())
238 O << " reassoc";
239 if (noNaNs())
240 O << " nnan";
241 if (noInfs())
242 O << " ninf";
243 if (noSignedZeros())
244 O << " nsz";
245 if (allowReciprocal())
246 O << " arcp";
247 if (allowContract())
248 O << " contract";
249 if (approxFunc())
250 O << " afn";
251 }
252}
253} // namespace llvm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
uint64_t Size
Hexagon Common GEP
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Class for arbitrary precision integers.
Definition: APInt.h:76
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:358
APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1966
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:145
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
bool noSignedZeros() const
Definition: FMF.h:68
bool noInfs() const
Definition: FMF.h:67
bool all() const
Definition: FMF.h:59
bool allowReciprocal() const
Definition: FMF.h:69
void print(raw_ostream &O) const
Print fast-math flags to O.
Definition: Operator.cpp:233
bool allowReassoc() const
Flag queries.
Definition: FMF.h:65
bool approxFunc() const
Definition: FMF.h:71
bool noNaNs() const
Definition: FMF.h:66
bool allowContract() const
Definition: FMF.h:70
bool collectOffset(const DataLayout &DL, unsigned BitWidth, MapVector< Value *, APInt > &VariableOffsets, APInt &ConstantOffset) const
Collect the offset of this GEP as a map of Values to their associated APInt multipliers,...
Definition: Operator.cpp:174
Type * getSourceElementType() const
Definition: Operator.cpp:54
Type * getResultElementType() const
Definition: Operator.cpp:60
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:91
Align getMaxPreservedAlignment(const DataLayout &DL) const
Compute the maximum alignment that this GEP is garranteed to preserve.
Definition: Operator.cpp:66
unsigned getPointerAddressSpace() const
Method to return the address space of the pointer operand.
Definition: Operator.h:433
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: MapVector.h:117
bool hasPoisonGeneratingFlags() const
Return true if this operator has flags which may cause this operator to evaluate to poison despite ha...
Definition: Operator.cpp:21
bool hasPoisonGeneratingFlagsOrMetadata() const
Return true if this operator has poison-generating flags or metadata.
Definition: Operator.cpp:47
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition: Operator.h:41
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:622
TypeSize getElementOffset(unsigned Idx) const
Definition: DataLayout.h:651
Class to represent struct types.
Definition: DerivedTypes.h:213
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
iterator_range< value_op_iterator > operand_values()
Definition: User.h:266
LLVM Value Representation.
Definition: Value.h:74
static constexpr uint64_t MaximumAlignment
Definition: Value.h:795
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:52
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:330
@ Offset
Definition: DWP.cpp:440
gep_type_iterator gep_type_end(const User *GEP)
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
Definition: MathExtras.h:338
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:184
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