1//===-- llvm/Operator.h - Operator utility subclass -------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines various classes for working with Instructions and
11// ConstantExprs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_OPERATOR_H
16#define LLVM_IR_OPERATOR_H
17
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/DataLayout.h"
20#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/GetElementPtrTypeIterator.h"
22#include "llvm/IR/Instruction.h"
23#include "llvm/IR/Type.h"
24
25namespace llvm {
26
27class GetElementPtrInst;
28class BinaryOperator;
29class ConstantExpr;
30
31/// This is a utility class that provides an abstraction for the common
32/// functionality between Instructions and ConstantExprs.
33class Operator : public User {
34private:
35  // The Operator class is intended to be used as a utility, and is never itself
36  // instantiated.
37  void *operator new(size_t, unsigned) = delete;
38  void *operator new(size_t s) = delete;
39  Operator() = delete;
40
41protected:
42  // NOTE: Cannot use = delete because it's not legal to delete
43  // an overridden method that's not deleted in the base class. Cannot leave
44  // this unimplemented because that leads to an ODR-violation.
45  ~Operator() override;
46
47public:
48  /// Return the opcode for this Instruction or ConstantExpr.
49  unsigned getOpcode() const {
50    if (const Instruction *I = dyn_cast<Instruction>(this))
51      return I->getOpcode();
52    return cast<ConstantExpr>(this)->getOpcode();
53  }
54
55  /// If V is an Instruction or ConstantExpr, return its opcode.
56  /// Otherwise return UserOp1.
57  static unsigned getOpcode(const Value *V) {
58    if (const Instruction *I = dyn_cast<Instruction>(V))
59      return I->getOpcode();
60    if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
61      return CE->getOpcode();
62    return Instruction::UserOp1;
63  }
64
65  static inline bool classof(const Instruction *) { return true; }
66  static inline bool classof(const ConstantExpr *) { return true; }
67  static inline bool classof(const Value *V) {
68    return isa<Instruction>(V) || isa<ConstantExpr>(V);
69  }
70};
71
72/// Utility class for integer arithmetic operators which may exhibit overflow -
73/// Add, Sub, and Mul. It does not include SDiv, despite that operator having
74/// the potential for overflow.
75class OverflowingBinaryOperator : public Operator {
76public:
77  enum {
78    NoUnsignedWrap = (1 << 0),
79    NoSignedWrap   = (1 << 1)
80  };
81
82private:
83  friend class BinaryOperator;
84  friend class ConstantExpr;
85  void setHasNoUnsignedWrap(bool B) {
86    SubclassOptionalData =
87      (SubclassOptionalData & ~NoUnsignedWrap) | (B * NoUnsignedWrap);
88  }
89  void setHasNoSignedWrap(bool B) {
90    SubclassOptionalData =
91      (SubclassOptionalData & ~NoSignedWrap) | (B * NoSignedWrap);
92  }
93
94public:
95  /// Test whether this operation is known to never
96  /// undergo unsigned overflow, aka the nuw property.
97  bool hasNoUnsignedWrap() const {
98    return SubclassOptionalData & NoUnsignedWrap;
99  }
100
101  /// Test whether this operation is known to never
102  /// undergo signed overflow, aka the nsw property.
103  bool hasNoSignedWrap() const {
104    return (SubclassOptionalData & NoSignedWrap) != 0;
105  }
106
107  static inline bool classof(const Instruction *I) {
108    return I->getOpcode() == Instruction::Add ||
109           I->getOpcode() == Instruction::Sub ||
110           I->getOpcode() == Instruction::Mul ||
111           I->getOpcode() == Instruction::Shl;
112  }
113  static inline bool classof(const ConstantExpr *CE) {
114    return CE->getOpcode() == Instruction::Add ||
115           CE->getOpcode() == Instruction::Sub ||
116           CE->getOpcode() == Instruction::Mul ||
117           CE->getOpcode() == Instruction::Shl;
118  }
119  static inline bool classof(const Value *V) {
120    return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
121           (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
122  }
123};
124
125/// A udiv or sdiv instruction, which can be marked as "exact",
126/// indicating that no bits are destroyed.
127class PossiblyExactOperator : public Operator {
128public:
129  enum {
130    IsExact = (1 << 0)
131  };
132
133private:
134  friend class BinaryOperator;
135  friend class ConstantExpr;
136  void setIsExact(bool B) {
137    SubclassOptionalData = (SubclassOptionalData & ~IsExact) | (B * IsExact);
138  }
139
140public:
141  /// Test whether this division is known to be exact, with zero remainder.
142  bool isExact() const {
143    return SubclassOptionalData & IsExact;
144  }
145
146  static bool isPossiblyExactOpcode(unsigned OpC) {
147    return OpC == Instruction::SDiv ||
148           OpC == Instruction::UDiv ||
149           OpC == Instruction::AShr ||
150           OpC == Instruction::LShr;
151  }
152  static inline bool classof(const ConstantExpr *CE) {
153    return isPossiblyExactOpcode(CE->getOpcode());
154  }
155  static inline bool classof(const Instruction *I) {
156    return isPossiblyExactOpcode(I->getOpcode());
157  }
158  static inline bool classof(const Value *V) {
159    return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
160           (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
161  }
162};
163
164/// Convenience struct for specifying and reasoning about fast-math flags.
165class FastMathFlags {
166private:
167  friend class FPMathOperator;
168  unsigned Flags;
169  FastMathFlags(unsigned F) : Flags(F) { }
170
171public:
172  enum {
173    UnsafeAlgebra   = (1 << 0),
174    NoNaNs          = (1 << 1),
175    NoInfs          = (1 << 2),
176    NoSignedZeros   = (1 << 3),
177    AllowReciprocal = (1 << 4)
178  };
179
180  FastMathFlags() : Flags(0)
181  { }
182
183  /// Whether any flag is set
184  bool any() const { return Flags != 0; }
185
186  /// Set all the flags to false
187  void clear() { Flags = 0; }
188
189  /// Flag queries
190  bool noNaNs() const          { return 0 != (Flags & NoNaNs); }
191  bool noInfs() const          { return 0 != (Flags & NoInfs); }
192  bool noSignedZeros() const   { return 0 != (Flags & NoSignedZeros); }
193  bool allowReciprocal() const { return 0 != (Flags & AllowReciprocal); }
194  bool unsafeAlgebra() const   { return 0 != (Flags & UnsafeAlgebra); }
195
196  /// Flag setters
197  void setNoNaNs()          { Flags |= NoNaNs; }
198  void setNoInfs()          { Flags |= NoInfs; }
199  void setNoSignedZeros()   { Flags |= NoSignedZeros; }
200  void setAllowReciprocal() { Flags |= AllowReciprocal; }
201  void setUnsafeAlgebra() {
202    Flags |= UnsafeAlgebra;
203    setNoNaNs();
204    setNoInfs();
205    setNoSignedZeros();
206    setAllowReciprocal();
207  }
208
209  void operator&=(const FastMathFlags &OtherFlags) {
210    Flags &= OtherFlags.Flags;
211  }
212};
213
214
215/// Utility class for floating point operations which can have
216/// information about relaxed accuracy requirements attached to them.
217class FPMathOperator : public Operator {
218private:
219  friend class Instruction;
220
221  void setHasUnsafeAlgebra(bool B) {
222    SubclassOptionalData =
223      (SubclassOptionalData & ~FastMathFlags::UnsafeAlgebra) |
224      (B * FastMathFlags::UnsafeAlgebra);
225
226    // Unsafe algebra implies all the others
227    if (B) {
228      setHasNoNaNs(true);
229      setHasNoInfs(true);
230      setHasNoSignedZeros(true);
231      setHasAllowReciprocal(true);
232    }
233  }
234  void setHasNoNaNs(bool B) {
235    SubclassOptionalData =
236      (SubclassOptionalData & ~FastMathFlags::NoNaNs) |
237      (B * FastMathFlags::NoNaNs);
238  }
239  void setHasNoInfs(bool B) {
240    SubclassOptionalData =
241      (SubclassOptionalData & ~FastMathFlags::NoInfs) |
242      (B * FastMathFlags::NoInfs);
243  }
244  void setHasNoSignedZeros(bool B) {
245    SubclassOptionalData =
246      (SubclassOptionalData & ~FastMathFlags::NoSignedZeros) |
247      (B * FastMathFlags::NoSignedZeros);
248  }
249  void setHasAllowReciprocal(bool B) {
250    SubclassOptionalData =
251      (SubclassOptionalData & ~FastMathFlags::AllowReciprocal) |
252      (B * FastMathFlags::AllowReciprocal);
253  }
254
255  /// Convenience function for setting multiple fast-math flags.
256  /// FMF is a mask of the bits to set.
257  void setFastMathFlags(FastMathFlags FMF) {
258    SubclassOptionalData |= FMF.Flags;
259  }
260
261  /// Convenience function for copying all fast-math flags.
262  /// All values in FMF are transferred to this operator.
263  void copyFastMathFlags(FastMathFlags FMF) {
264    SubclassOptionalData = FMF.Flags;
265  }
266
267public:
268  /// Test whether this operation is permitted to be
269  /// algebraically transformed, aka the 'A' fast-math property.
270  bool hasUnsafeAlgebra() const {
271    return (SubclassOptionalData & FastMathFlags::UnsafeAlgebra) != 0;
272  }
273
274  /// Test whether this operation's arguments and results are to be
275  /// treated as non-NaN, aka the 'N' fast-math property.
276  bool hasNoNaNs() const {
277    return (SubclassOptionalData & FastMathFlags::NoNaNs) != 0;
278  }
279
280  /// Test whether this operation's arguments and results are to be
281  /// treated as NoN-Inf, aka the 'I' fast-math property.
282  bool hasNoInfs() const {
283    return (SubclassOptionalData & FastMathFlags::NoInfs) != 0;
284  }
285
286  /// Test whether this operation can treat the sign of zero
287  /// as insignificant, aka the 'S' fast-math property.
288  bool hasNoSignedZeros() const {
289    return (SubclassOptionalData & FastMathFlags::NoSignedZeros) != 0;
290  }
291
292  /// Test whether this operation is permitted to use
293  /// reciprocal instead of division, aka the 'R' fast-math property.
294  bool hasAllowReciprocal() const {
295    return (SubclassOptionalData & FastMathFlags::AllowReciprocal) != 0;
296  }
297
298  /// Convenience function for getting all the fast-math flags
299  FastMathFlags getFastMathFlags() const {
300    return FastMathFlags(SubclassOptionalData);
301  }
302
303  /// \brief Get the maximum error permitted by this operation in ULPs.  An
304  /// accuracy of 0.0 means that the operation should be performed with the
305  /// default precision.
306  float getFPAccuracy() const;
307
308  static inline bool classof(const Instruction *I) {
309    return I->getType()->isFPOrFPVectorTy();
310  }
311  static inline bool classof(const Value *V) {
312    return isa<Instruction>(V) && classof(cast<Instruction>(V));
313  }
314};
315
316
317/// A helper template for defining operators for individual opcodes.
318template<typename SuperClass, unsigned Opc>
319class ConcreteOperator : public SuperClass {
320public:
321  static inline bool classof(const Instruction *I) {
322    return I->getOpcode() == Opc;
323  }
324  static inline bool classof(const ConstantExpr *CE) {
325    return CE->getOpcode() == Opc;
326  }
327  static inline bool classof(const Value *V) {
328    return (isa<Instruction>(V) && classof(cast<Instruction>(V))) ||
329           (isa<ConstantExpr>(V) && classof(cast<ConstantExpr>(V)));
330  }
331};
332
333class AddOperator
334  : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Add> {
335};
336class SubOperator
337  : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Sub> {
338};
339class MulOperator
340  : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Mul> {
341};
342class ShlOperator
343  : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Shl> {
344};
345
346
347class SDivOperator
348  : public ConcreteOperator<PossiblyExactOperator, Instruction::SDiv> {
349};
350class UDivOperator
351  : public ConcreteOperator<PossiblyExactOperator, Instruction::UDiv> {
352};
353class AShrOperator
354  : public ConcreteOperator<PossiblyExactOperator, Instruction::AShr> {
355};
356class LShrOperator
357  : public ConcreteOperator<PossiblyExactOperator, Instruction::LShr> {
358};
359
360
361class ZExtOperator : public ConcreteOperator<Operator, Instruction::ZExt> {};
362
363
364class GEPOperator
365  : public ConcreteOperator<Operator, Instruction::GetElementPtr> {
366  enum {
367    IsInBounds = (1 << 0)
368  };
369
370  friend class GetElementPtrInst;
371  friend class ConstantExpr;
372  void setIsInBounds(bool B) {
373    SubclassOptionalData =
374      (SubclassOptionalData & ~IsInBounds) | (B * IsInBounds);
375  }
376
377public:
378  /// Test whether this is an inbounds GEP, as defined by LangRef.html.
379  bool isInBounds() const {
380    return SubclassOptionalData & IsInBounds;
381  }
382
383  inline op_iterator       idx_begin()       { return op_begin()+1; }
384  inline const_op_iterator idx_begin() const { return op_begin()+1; }
385  inline op_iterator       idx_end()         { return op_end(); }
386  inline const_op_iterator idx_end()   const { return op_end(); }
387
388  Value *getPointerOperand() {
389    return getOperand(0);
390  }
391  const Value *getPointerOperand() const {
392    return getOperand(0);
393  }
394  static unsigned getPointerOperandIndex() {
395    return 0U;                      // get index for modifying correct operand
396  }
397
398  /// Method to return the pointer operand as a PointerType.
399  Type *getPointerOperandType() const {
400    return getPointerOperand()->getType();
401  }
402
403  Type *getSourceElementType() const {
404    return cast<SequentialType>(getPointerOperandType()->getScalarType())
405        ->getElementType();
406  }
407
408  /// Method to return the address space of the pointer operand.
409  unsigned getPointerAddressSpace() const {
410    return getPointerOperandType()->getPointerAddressSpace();
411  }
412
413  unsigned getNumIndices() const {  // Note: always non-negative
414    return getNumOperands() - 1;
415  }
416
417  bool hasIndices() const {
418    return getNumOperands() > 1;
419  }
420
421  /// Return true if all of the indices of this GEP are zeros.
422  /// If so, the result pointer and the first operand have the same
423  /// value, just potentially different types.
424  bool hasAllZeroIndices() const {
425    for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
426      if (ConstantInt *C = dyn_cast<ConstantInt>(I))
427        if (C->isZero())
428          continue;
429      return false;
430    }
431    return true;
432  }
433
434  /// Return true if all of the indices of this GEP are constant integers.
435  /// If so, the result pointer and the first operand have
436  /// a constant offset between them.
437  bool hasAllConstantIndices() const {
438    for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
439      if (!isa<ConstantInt>(I))
440        return false;
441    }
442    return true;
443  }
444
445  /// \brief Accumulate the constant address offset of this GEP if possible.
446  ///
447  /// This routine accepts an APInt into which it will accumulate the constant
448  /// offset of this GEP if the GEP is in fact constant. If the GEP is not
449  /// all-constant, it returns false and the value of the offset APInt is
450  /// undefined (it is *not* preserved!). The APInt passed into this routine
451  /// must be at exactly as wide as the IntPtr type for the address space of the
452  /// base GEP pointer.
453  bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const {
454    assert(Offset.getBitWidth() ==
455           DL.getPointerSizeInBits(getPointerAddressSpace()) &&
456           "The offset must have exactly as many bits as our pointer.");
457
458    for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
459         GTI != GTE; ++GTI) {
460      ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
461      if (!OpC)
462        return false;
463      if (OpC->isZero())
464        continue;
465
466      // Handle a struct index, which adds its field offset to the pointer.
467      if (StructType *STy = dyn_cast<StructType>(*GTI)) {
468        unsigned ElementIdx = OpC->getZExtValue();
469        const StructLayout *SL = DL.getStructLayout(STy);
470        Offset += APInt(Offset.getBitWidth(),
471                        SL->getElementOffset(ElementIdx));
472        continue;
473      }
474
475      // For array or vector indices, scale the index by the size of the type.
476      APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
477      Offset += Index * APInt(Offset.getBitWidth(),
478                              DL.getTypeAllocSize(GTI.getIndexedType()));
479    }
480    return true;
481  }
482
483};
484
485class PtrToIntOperator
486    : public ConcreteOperator<Operator, Instruction::PtrToInt> {
487  friend class PtrToInt;
488  friend class ConstantExpr;
489
490public:
491  Value *getPointerOperand() {
492    return getOperand(0);
493  }
494  const Value *getPointerOperand() const {
495    return getOperand(0);
496  }
497  static unsigned getPointerOperandIndex() {
498    return 0U;                      // get index for modifying correct operand
499  }
500
501  /// Method to return the pointer operand as a PointerType.
502  Type *getPointerOperandType() const {
503    return getPointerOperand()->getType();
504  }
505
506  /// Method to return the address space of the pointer operand.
507  unsigned getPointerAddressSpace() const {
508    return cast<PointerType>(getPointerOperandType())->getAddressSpace();
509  }
510};
511
512class BitCastOperator
513    : public ConcreteOperator<Operator, Instruction::BitCast> {
514  friend class BitCastInst;
515  friend class ConstantExpr;
516
517public:
518  Type *getSrcTy() const {
519    return getOperand(0)->getType();
520  }
521
522  Type *getDestTy() const {
523    return getType();
524  }
525};
526
527} // End llvm namespace
528
529#endif
530