[opaque pointer type] Explicit pointee type for GEPOperator/GEPConstantExpr.
[oota-llvm.git] / include / llvm / IR / Operator.h
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
25 namespace llvm {
26
27 class GetElementPtrInst;
28 class BinaryOperator;
29 class ConstantExpr;
30
31 /// This is a utility class that provides an abstraction for the common
32 /// functionality between Instructions and ConstantExprs.
33 class Operator : public User {
34 private:
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
41 protected:
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
47 public:
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.
75 class OverflowingBinaryOperator : public Operator {
76 public:
77   enum {
78     NoUnsignedWrap = (1 << 0),
79     NoSignedWrap   = (1 << 1)
80   };
81
82 private:
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
94 public:
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.
127 class PossiblyExactOperator : public Operator {
128 public:
129   enum {
130     IsExact = (1 << 0)
131   };
132
133 private:
134   friend class BinaryOperator;
135   friend class ConstantExpr;
136   void setIsExact(bool B) {
137     SubclassOptionalData = (SubclassOptionalData & ~IsExact) | (B * IsExact);
138   }
139
140 public:
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.
165 class FastMathFlags {
166 private:
167   friend class FPMathOperator;
168   unsigned Flags;
169   FastMathFlags(unsigned F) : Flags(F) { }
170
171 public:
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.
217 class FPMathOperator : public Operator {
218 private:
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
267 public:
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.
318 template<typename SuperClass, unsigned Opc>
319 class ConcreteOperator : public SuperClass {
320 public:
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
333 class AddOperator
334   : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Add> {
335 };
336 class SubOperator
337   : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Sub> {
338 };
339 class MulOperator
340   : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Mul> {
341 };
342 class ShlOperator
343   : public ConcreteOperator<OverflowingBinaryOperator, Instruction::Shl> {
344 };
345
346
347 class SDivOperator
348   : public ConcreteOperator<PossiblyExactOperator, Instruction::SDiv> {
349 };
350 class UDivOperator
351   : public ConcreteOperator<PossiblyExactOperator, Instruction::UDiv> {
352 };
353 class AShrOperator
354   : public ConcreteOperator<PossiblyExactOperator, Instruction::AShr> {
355 };
356 class LShrOperator
357   : public ConcreteOperator<PossiblyExactOperator, Instruction::LShr> {
358 };
359
360
361 class ZExtOperator : public ConcreteOperator<Operator, Instruction::ZExt> {};
362
363
364 class 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
377 public:
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
405   /// Method to return the address space of the pointer operand.
406   unsigned getPointerAddressSpace() const {
407     return getPointerOperandType()->getPointerAddressSpace();
408   }
409
410   unsigned getNumIndices() const {  // Note: always non-negative
411     return getNumOperands() - 1;
412   }
413
414   bool hasIndices() const {
415     return getNumOperands() > 1;
416   }
417
418   /// Return true if all of the indices of this GEP are zeros.
419   /// If so, the result pointer and the first operand have the same
420   /// value, just potentially different types.
421   bool hasAllZeroIndices() const {
422     for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
423       if (ConstantInt *C = dyn_cast<ConstantInt>(I))
424         if (C->isZero())
425           continue;
426       return false;
427     }
428     return true;
429   }
430
431   /// Return true if all of the indices of this GEP are constant integers.
432   /// If so, the result pointer and the first operand have
433   /// a constant offset between them.
434   bool hasAllConstantIndices() const {
435     for (const_op_iterator I = idx_begin(), E = idx_end(); I != E; ++I) {
436       if (!isa<ConstantInt>(I))
437         return false;
438     }
439     return true;
440   }
441
442   /// \brief Accumulate the constant address offset of this GEP if possible.
443   ///
444   /// This routine accepts an APInt into which it will accumulate the constant
445   /// offset of this GEP if the GEP is in fact constant. If the GEP is not
446   /// all-constant, it returns false and the value of the offset APInt is
447   /// undefined (it is *not* preserved!). The APInt passed into this routine
448   /// must be at exactly as wide as the IntPtr type for the address space of the
449   /// base GEP pointer.
450   bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const {
451     assert(Offset.getBitWidth() ==
452            DL.getPointerSizeInBits(getPointerAddressSpace()) &&
453            "The offset must have exactly as many bits as our pointer.");
454
455     for (gep_type_iterator GTI = gep_type_begin(this), GTE = gep_type_end(this);
456          GTI != GTE; ++GTI) {
457       ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
458       if (!OpC)
459         return false;
460       if (OpC->isZero())
461         continue;
462
463       // Handle a struct index, which adds its field offset to the pointer.
464       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
465         unsigned ElementIdx = OpC->getZExtValue();
466         const StructLayout *SL = DL.getStructLayout(STy);
467         Offset += APInt(Offset.getBitWidth(),
468                         SL->getElementOffset(ElementIdx));
469         continue;
470       }
471
472       // For array or vector indices, scale the index by the size of the type.
473       APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
474       Offset += Index * APInt(Offset.getBitWidth(),
475                               DL.getTypeAllocSize(GTI.getIndexedType()));
476     }
477     return true;
478   }
479
480 };
481
482 class PtrToIntOperator
483     : public ConcreteOperator<Operator, Instruction::PtrToInt> {
484   friend class PtrToInt;
485   friend class ConstantExpr;
486
487 public:
488   Value *getPointerOperand() {
489     return getOperand(0);
490   }
491   const Value *getPointerOperand() const {
492     return getOperand(0);
493   }
494   static unsigned getPointerOperandIndex() {
495     return 0U;                      // get index for modifying correct operand
496   }
497
498   /// Method to return the pointer operand as a PointerType.
499   Type *getPointerOperandType() const {
500     return getPointerOperand()->getType();
501   }
502
503   /// Method to return the address space of the pointer operand.
504   unsigned getPointerAddressSpace() const {
505     return cast<PointerType>(getPointerOperandType())->getAddressSpace();
506   }
507 };
508
509 class BitCastOperator
510     : public ConcreteOperator<Operator, Instruction::BitCast> {
511   friend class BitCastInst;
512   friend class ConstantExpr;
513
514 public:
515   Type *getSrcTy() const {
516     return getOperand(0)->getType();
517   }
518
519   Type *getDestTy() const {
520     return getType();
521   }
522 };
523
524 } // End llvm namespace
525
526 #endif