]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/CodeGen/CGValue.h
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / CodeGen / CGValue.h
1 //===-- CGValue.h - LLVM CodeGen wrappers for llvm::Value* ------*- C++ -*-===//
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 // These classes implement wrappers around llvm::Value in order to
10 // fully represent the range of values for C L- and R- values.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGVALUE_H
15 #define LLVM_CLANG_LIB_CODEGEN_CGVALUE_H
16
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Type.h"
19 #include "llvm/IR/Value.h"
20 #include "llvm/IR/Type.h"
21 #include "Address.h"
22 #include "CodeGenTBAA.h"
23
24 namespace llvm {
25   class Constant;
26   class MDNode;
27 }
28
29 namespace clang {
30 namespace CodeGen {
31   class AggValueSlot;
32   struct CGBitFieldInfo;
33
34 /// RValue - This trivial value class is used to represent the result of an
35 /// expression that is evaluated.  It can be one of three things: either a
36 /// simple LLVM SSA value, a pair of SSA values for complex numbers, or the
37 /// address of an aggregate value in memory.
38 class RValue {
39   enum Flavor { Scalar, Complex, Aggregate };
40
41   // The shift to make to an aggregate's alignment to make it look
42   // like a pointer.
43   enum { AggAlignShift = 4 };
44
45   // Stores first value and flavor.
46   llvm::PointerIntPair<llvm::Value *, 2, Flavor> V1;
47   // Stores second value and volatility.
48   llvm::PointerIntPair<llvm::Value *, 1, bool> V2;
49
50 public:
51   bool isScalar() const { return V1.getInt() == Scalar; }
52   bool isComplex() const { return V1.getInt() == Complex; }
53   bool isAggregate() const { return V1.getInt() == Aggregate; }
54
55   bool isVolatileQualified() const { return V2.getInt(); }
56
57   /// getScalarVal() - Return the Value* of this scalar value.
58   llvm::Value *getScalarVal() const {
59     assert(isScalar() && "Not a scalar!");
60     return V1.getPointer();
61   }
62
63   /// getComplexVal - Return the real/imag components of this complex value.
64   ///
65   std::pair<llvm::Value *, llvm::Value *> getComplexVal() const {
66     return std::make_pair(V1.getPointer(), V2.getPointer());
67   }
68
69   /// getAggregateAddr() - Return the Value* of the address of the aggregate.
70   Address getAggregateAddress() const {
71     assert(isAggregate() && "Not an aggregate!");
72     auto align = reinterpret_cast<uintptr_t>(V2.getPointer()) >> AggAlignShift;
73     return Address(V1.getPointer(), CharUnits::fromQuantity(align));
74   }
75   llvm::Value *getAggregatePointer() const {
76     assert(isAggregate() && "Not an aggregate!");
77     return V1.getPointer();
78   }
79
80   static RValue getIgnored() {
81     // FIXME: should we make this a more explicit state?
82     return get(nullptr);
83   }
84
85   static RValue get(llvm::Value *V) {
86     RValue ER;
87     ER.V1.setPointer(V);
88     ER.V1.setInt(Scalar);
89     ER.V2.setInt(false);
90     return ER;
91   }
92   static RValue getComplex(llvm::Value *V1, llvm::Value *V2) {
93     RValue ER;
94     ER.V1.setPointer(V1);
95     ER.V2.setPointer(V2);
96     ER.V1.setInt(Complex);
97     ER.V2.setInt(false);
98     return ER;
99   }
100   static RValue getComplex(const std::pair<llvm::Value *, llvm::Value *> &C) {
101     return getComplex(C.first, C.second);
102   }
103   // FIXME: Aggregate rvalues need to retain information about whether they are
104   // volatile or not.  Remove default to find all places that probably get this
105   // wrong.
106   static RValue getAggregate(Address addr, bool isVolatile = false) {
107     RValue ER;
108     ER.V1.setPointer(addr.getPointer());
109     ER.V1.setInt(Aggregate);
110
111     auto align = static_cast<uintptr_t>(addr.getAlignment().getQuantity());
112     ER.V2.setPointer(reinterpret_cast<llvm::Value*>(align << AggAlignShift));
113     ER.V2.setInt(isVolatile);
114     return ER;
115   }
116 };
117
118 /// Does an ARC strong l-value have precise lifetime?
119 enum ARCPreciseLifetime_t {
120   ARCImpreciseLifetime, ARCPreciseLifetime
121 };
122
123 /// The source of the alignment of an l-value; an expression of
124 /// confidence in the alignment actually matching the estimate.
125 enum class AlignmentSource {
126   /// The l-value was an access to a declared entity or something
127   /// equivalently strong, like the address of an array allocated by a
128   /// language runtime.
129   Decl,
130
131   /// The l-value was considered opaque, so the alignment was
132   /// determined from a type, but that type was an explicitly-aligned
133   /// typedef.
134   AttributedType,
135
136   /// The l-value was considered opaque, so the alignment was
137   /// determined from a type.
138   Type
139 };
140
141 /// Given that the base address has the given alignment source, what's
142 /// our confidence in the alignment of the field?
143 static inline AlignmentSource getFieldAlignmentSource(AlignmentSource Source) {
144   // For now, we don't distinguish fields of opaque pointers from
145   // top-level declarations, but maybe we should.
146   return AlignmentSource::Decl;
147 }
148
149 class LValueBaseInfo {
150   AlignmentSource AlignSource;
151
152 public:
153   explicit LValueBaseInfo(AlignmentSource Source = AlignmentSource::Type)
154     : AlignSource(Source) {}
155   AlignmentSource getAlignmentSource() const { return AlignSource; }
156   void setAlignmentSource(AlignmentSource Source) { AlignSource = Source; }
157
158   void mergeForCast(const LValueBaseInfo &Info) {
159     setAlignmentSource(Info.getAlignmentSource());
160   }
161 };
162
163 /// LValue - This represents an lvalue references.  Because C/C++ allow
164 /// bitfields, this is not a simple LLVM pointer, it may be a pointer plus a
165 /// bitrange.
166 class LValue {
167   enum {
168     Simple,       // This is a normal l-value, use getAddress().
169     VectorElt,    // This is a vector element l-value (V[i]), use getVector*
170     BitField,     // This is a bitfield l-value, use getBitfield*.
171     ExtVectorElt, // This is an extended vector subset, use getExtVectorComp
172     GlobalReg     // This is a register l-value, use getGlobalReg()
173   } LVType;
174
175   llvm::Value *V;
176
177   union {
178     // Index into a vector subscript: V[i]
179     llvm::Value *VectorIdx;
180
181     // ExtVector element subset: V.xyx
182     llvm::Constant *VectorElts;
183
184     // BitField start bit and size
185     const CGBitFieldInfo *BitFieldInfo;
186   };
187
188   QualType Type;
189
190   // 'const' is unused here
191   Qualifiers Quals;
192
193   // The alignment to use when accessing this lvalue.  (For vector elements,
194   // this is the alignment of the whole vector.)
195   unsigned Alignment;
196
197   // objective-c's ivar
198   bool Ivar:1;
199
200   // objective-c's ivar is an array
201   bool ObjIsArray:1;
202
203   // LValue is non-gc'able for any reason, including being a parameter or local
204   // variable.
205   bool NonGC: 1;
206
207   // Lvalue is a global reference of an objective-c object
208   bool GlobalObjCRef : 1;
209
210   // Lvalue is a thread local reference
211   bool ThreadLocalRef : 1;
212
213   // Lvalue has ARC imprecise lifetime.  We store this inverted to try
214   // to make the default bitfield pattern all-zeroes.
215   bool ImpreciseLifetime : 1;
216
217   // This flag shows if a nontemporal load/stores should be used when accessing
218   // this lvalue.
219   bool Nontemporal : 1;
220
221   LValueBaseInfo BaseInfo;
222   TBAAAccessInfo TBAAInfo;
223
224   Expr *BaseIvarExp;
225
226 private:
227   void Initialize(QualType Type, Qualifiers Quals, CharUnits Alignment,
228                   LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
229     assert((!Alignment.isZero() || Type->isIncompleteType()) &&
230            "initializing l-value with zero alignment!");
231     this->Type = Type;
232     this->Quals = Quals;
233     const unsigned MaxAlign = 1U << 31;
234     this->Alignment = Alignment.getQuantity() <= MaxAlign
235                           ? Alignment.getQuantity()
236                           : MaxAlign;
237     assert(this->Alignment == Alignment.getQuantity() &&
238            "Alignment exceeds allowed max!");
239     this->BaseInfo = BaseInfo;
240     this->TBAAInfo = TBAAInfo;
241
242     // Initialize Objective-C flags.
243     this->Ivar = this->ObjIsArray = this->NonGC = this->GlobalObjCRef = false;
244     this->ImpreciseLifetime = false;
245     this->Nontemporal = false;
246     this->ThreadLocalRef = false;
247     this->BaseIvarExp = nullptr;
248   }
249
250 public:
251   bool isSimple() const { return LVType == Simple; }
252   bool isVectorElt() const { return LVType == VectorElt; }
253   bool isBitField() const { return LVType == BitField; }
254   bool isExtVectorElt() const { return LVType == ExtVectorElt; }
255   bool isGlobalReg() const { return LVType == GlobalReg; }
256
257   bool isVolatileQualified() const { return Quals.hasVolatile(); }
258   bool isRestrictQualified() const { return Quals.hasRestrict(); }
259   unsigned getVRQualifiers() const {
260     return Quals.getCVRQualifiers() & ~Qualifiers::Const;
261   }
262
263   QualType getType() const { return Type; }
264
265   Qualifiers::ObjCLifetime getObjCLifetime() const {
266     return Quals.getObjCLifetime();
267   }
268
269   bool isObjCIvar() const { return Ivar; }
270   void setObjCIvar(bool Value) { Ivar = Value; }
271
272   bool isObjCArray() const { return ObjIsArray; }
273   void setObjCArray(bool Value) { ObjIsArray = Value; }
274
275   bool isNonGC () const { return NonGC; }
276   void setNonGC(bool Value) { NonGC = Value; }
277
278   bool isGlobalObjCRef() const { return GlobalObjCRef; }
279   void setGlobalObjCRef(bool Value) { GlobalObjCRef = Value; }
280
281   bool isThreadLocalRef() const { return ThreadLocalRef; }
282   void setThreadLocalRef(bool Value) { ThreadLocalRef = Value;}
283
284   ARCPreciseLifetime_t isARCPreciseLifetime() const {
285     return ARCPreciseLifetime_t(!ImpreciseLifetime);
286   }
287   void setARCPreciseLifetime(ARCPreciseLifetime_t value) {
288     ImpreciseLifetime = (value == ARCImpreciseLifetime);
289   }
290   bool isNontemporal() const { return Nontemporal; }
291   void setNontemporal(bool Value) { Nontemporal = Value; }
292
293   bool isObjCWeak() const {
294     return Quals.getObjCGCAttr() == Qualifiers::Weak;
295   }
296   bool isObjCStrong() const {
297     return Quals.getObjCGCAttr() == Qualifiers::Strong;
298   }
299
300   bool isVolatile() const {
301     return Quals.hasVolatile();
302   }
303
304   Expr *getBaseIvarExp() const { return BaseIvarExp; }
305   void setBaseIvarExp(Expr *V) { BaseIvarExp = V; }
306
307   TBAAAccessInfo getTBAAInfo() const { return TBAAInfo; }
308   void setTBAAInfo(TBAAAccessInfo Info) { TBAAInfo = Info; }
309
310   const Qualifiers &getQuals() const { return Quals; }
311   Qualifiers &getQuals() { return Quals; }
312
313   LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
314
315   CharUnits getAlignment() const { return CharUnits::fromQuantity(Alignment); }
316   void setAlignment(CharUnits A) { Alignment = A.getQuantity(); }
317
318   LValueBaseInfo getBaseInfo() const { return BaseInfo; }
319   void setBaseInfo(LValueBaseInfo Info) { BaseInfo = Info; }
320
321   // simple lvalue
322   llvm::Value *getPointer() const {
323     assert(isSimple());
324     return V;
325   }
326   Address getAddress() const { return Address(getPointer(), getAlignment()); }
327   void setAddress(Address address) {
328     assert(isSimple());
329     V = address.getPointer();
330     Alignment = address.getAlignment().getQuantity();
331   }
332
333   // vector elt lvalue
334   Address getVectorAddress() const {
335     return Address(getVectorPointer(), getAlignment());
336   }
337   llvm::Value *getVectorPointer() const { assert(isVectorElt()); return V; }
338   llvm::Value *getVectorIdx() const { assert(isVectorElt()); return VectorIdx; }
339
340   // extended vector elements.
341   Address getExtVectorAddress() const {
342     return Address(getExtVectorPointer(), getAlignment());
343   }
344   llvm::Value *getExtVectorPointer() const {
345     assert(isExtVectorElt());
346     return V;
347   }
348   llvm::Constant *getExtVectorElts() const {
349     assert(isExtVectorElt());
350     return VectorElts;
351   }
352
353   // bitfield lvalue
354   Address getBitFieldAddress() const {
355     return Address(getBitFieldPointer(), getAlignment());
356   }
357   llvm::Value *getBitFieldPointer() const { assert(isBitField()); return V; }
358   const CGBitFieldInfo &getBitFieldInfo() const {
359     assert(isBitField());
360     return *BitFieldInfo;
361   }
362
363   // global register lvalue
364   llvm::Value *getGlobalReg() const { assert(isGlobalReg()); return V; }
365
366   static LValue MakeAddr(Address address, QualType type, ASTContext &Context,
367                          LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
368     Qualifiers qs = type.getQualifiers();
369     qs.setObjCGCAttr(Context.getObjCGCAttrKind(type));
370
371     LValue R;
372     R.LVType = Simple;
373     assert(address.getPointer()->getType()->isPointerTy());
374     R.V = address.getPointer();
375     R.Initialize(type, qs, address.getAlignment(), BaseInfo, TBAAInfo);
376     return R;
377   }
378
379   static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx,
380                               QualType type, LValueBaseInfo BaseInfo,
381                               TBAAAccessInfo TBAAInfo) {
382     LValue R;
383     R.LVType = VectorElt;
384     R.V = vecAddress.getPointer();
385     R.VectorIdx = Idx;
386     R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
387                  BaseInfo, TBAAInfo);
388     return R;
389   }
390
391   static LValue MakeExtVectorElt(Address vecAddress, llvm::Constant *Elts,
392                                  QualType type, LValueBaseInfo BaseInfo,
393                                  TBAAAccessInfo TBAAInfo) {
394     LValue R;
395     R.LVType = ExtVectorElt;
396     R.V = vecAddress.getPointer();
397     R.VectorElts = Elts;
398     R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
399                  BaseInfo, TBAAInfo);
400     return R;
401   }
402
403   /// Create a new object to represent a bit-field access.
404   ///
405   /// \param Addr - The base address of the bit-field sequence this
406   /// bit-field refers to.
407   /// \param Info - The information describing how to perform the bit-field
408   /// access.
409   static LValue MakeBitfield(Address Addr, const CGBitFieldInfo &Info,
410                              QualType type, LValueBaseInfo BaseInfo,
411                              TBAAAccessInfo TBAAInfo) {
412     LValue R;
413     R.LVType = BitField;
414     R.V = Addr.getPointer();
415     R.BitFieldInfo = &Info;
416     R.Initialize(type, type.getQualifiers(), Addr.getAlignment(), BaseInfo,
417                  TBAAInfo);
418     return R;
419   }
420
421   static LValue MakeGlobalReg(Address Reg, QualType type) {
422     LValue R;
423     R.LVType = GlobalReg;
424     R.V = Reg.getPointer();
425     R.Initialize(type, type.getQualifiers(), Reg.getAlignment(),
426                  LValueBaseInfo(AlignmentSource::Decl), TBAAAccessInfo());
427     return R;
428   }
429
430   RValue asAggregateRValue() const {
431     return RValue::getAggregate(getAddress(), isVolatileQualified());
432   }
433 };
434
435 /// An aggregate value slot.
436 class AggValueSlot {
437   /// The address.
438   llvm::Value *Addr;
439
440   // Qualifiers
441   Qualifiers Quals;
442
443   unsigned Alignment;
444
445   /// DestructedFlag - This is set to true if some external code is
446   /// responsible for setting up a destructor for the slot.  Otherwise
447   /// the code which constructs it should push the appropriate cleanup.
448   bool DestructedFlag : 1;
449
450   /// ObjCGCFlag - This is set to true if writing to the memory in the
451   /// slot might require calling an appropriate Objective-C GC
452   /// barrier.  The exact interaction here is unnecessarily mysterious.
453   bool ObjCGCFlag : 1;
454
455   /// ZeroedFlag - This is set to true if the memory in the slot is
456   /// known to be zero before the assignment into it.  This means that
457   /// zero fields don't need to be set.
458   bool ZeroedFlag : 1;
459
460   /// AliasedFlag - This is set to true if the slot might be aliased
461   /// and it's not undefined behavior to access it through such an
462   /// alias.  Note that it's always undefined behavior to access a C++
463   /// object that's under construction through an alias derived from
464   /// outside the construction process.
465   ///
466   /// This flag controls whether calls that produce the aggregate
467   /// value may be evaluated directly into the slot, or whether they
468   /// must be evaluated into an unaliased temporary and then memcpy'ed
469   /// over.  Since it's invalid in general to memcpy a non-POD C++
470   /// object, it's important that this flag never be set when
471   /// evaluating an expression which constructs such an object.
472   bool AliasedFlag : 1;
473
474   /// This is set to true if the tail padding of this slot might overlap
475   /// another object that may have already been initialized (and whose
476   /// value must be preserved by this initialization). If so, we may only
477   /// store up to the dsize of the type. Otherwise we can widen stores to
478   /// the size of the type.
479   bool OverlapFlag : 1;
480
481   /// If is set to true, sanitizer checks are already generated for this address
482   /// or not required. For instance, if this address represents an object
483   /// created in 'new' expression, sanitizer checks for memory is made as a part
484   /// of 'operator new' emission and object constructor should not generate
485   /// them.
486   bool SanitizerCheckedFlag : 1;
487
488 public:
489   enum IsAliased_t { IsNotAliased, IsAliased };
490   enum IsDestructed_t { IsNotDestructed, IsDestructed };
491   enum IsZeroed_t { IsNotZeroed, IsZeroed };
492   enum Overlap_t { DoesNotOverlap, MayOverlap };
493   enum NeedsGCBarriers_t { DoesNotNeedGCBarriers, NeedsGCBarriers };
494   enum IsSanitizerChecked_t { IsNotSanitizerChecked, IsSanitizerChecked };
495
496   /// ignored - Returns an aggregate value slot indicating that the
497   /// aggregate value is being ignored.
498   static AggValueSlot ignored() {
499     return forAddr(Address::invalid(), Qualifiers(), IsNotDestructed,
500                    DoesNotNeedGCBarriers, IsNotAliased, DoesNotOverlap);
501   }
502
503   /// forAddr - Make a slot for an aggregate value.
504   ///
505   /// \param quals - The qualifiers that dictate how the slot should
506   /// be initialied. Only 'volatile' and the Objective-C lifetime
507   /// qualifiers matter.
508   ///
509   /// \param isDestructed - true if something else is responsible
510   ///   for calling destructors on this object
511   /// \param needsGC - true if the slot is potentially located
512   ///   somewhere that ObjC GC calls should be emitted for
513   static AggValueSlot forAddr(Address addr,
514                               Qualifiers quals,
515                               IsDestructed_t isDestructed,
516                               NeedsGCBarriers_t needsGC,
517                               IsAliased_t isAliased,
518                               Overlap_t mayOverlap,
519                               IsZeroed_t isZeroed = IsNotZeroed,
520                        IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) {
521     AggValueSlot AV;
522     if (addr.isValid()) {
523       AV.Addr = addr.getPointer();
524       AV.Alignment = addr.getAlignment().getQuantity();
525     } else {
526       AV.Addr = nullptr;
527       AV.Alignment = 0;
528     }
529     AV.Quals = quals;
530     AV.DestructedFlag = isDestructed;
531     AV.ObjCGCFlag = needsGC;
532     AV.ZeroedFlag = isZeroed;
533     AV.AliasedFlag = isAliased;
534     AV.OverlapFlag = mayOverlap;
535     AV.SanitizerCheckedFlag = isChecked;
536     return AV;
537   }
538
539   static AggValueSlot forLValue(const LValue &LV,
540                                 IsDestructed_t isDestructed,
541                                 NeedsGCBarriers_t needsGC,
542                                 IsAliased_t isAliased,
543                                 Overlap_t mayOverlap,
544                                 IsZeroed_t isZeroed = IsNotZeroed,
545                        IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) {
546     return forAddr(LV.getAddress(), LV.getQuals(), isDestructed, needsGC,
547                    isAliased, mayOverlap, isZeroed, isChecked);
548   }
549
550   IsDestructed_t isExternallyDestructed() const {
551     return IsDestructed_t(DestructedFlag);
552   }
553   void setExternallyDestructed(bool destructed = true) {
554     DestructedFlag = destructed;
555   }
556
557   Qualifiers getQualifiers() const { return Quals; }
558
559   bool isVolatile() const {
560     return Quals.hasVolatile();
561   }
562
563   void setVolatile(bool flag) {
564     if (flag)
565       Quals.addVolatile();
566     else
567       Quals.removeVolatile();
568   }
569
570   Qualifiers::ObjCLifetime getObjCLifetime() const {
571     return Quals.getObjCLifetime();
572   }
573
574   NeedsGCBarriers_t requiresGCollection() const {
575     return NeedsGCBarriers_t(ObjCGCFlag);
576   }
577
578   llvm::Value *getPointer() const {
579     return Addr;
580   }
581
582   Address getAddress() const {
583     return Address(Addr, getAlignment());
584   }
585
586   bool isIgnored() const {
587     return Addr == nullptr;
588   }
589
590   CharUnits getAlignment() const {
591     return CharUnits::fromQuantity(Alignment);
592   }
593
594   IsAliased_t isPotentiallyAliased() const {
595     return IsAliased_t(AliasedFlag);
596   }
597
598   Overlap_t mayOverlap() const {
599     return Overlap_t(OverlapFlag);
600   }
601
602   bool isSanitizerChecked() const {
603     return SanitizerCheckedFlag;
604   }
605
606   RValue asRValue() const {
607     if (isIgnored()) {
608       return RValue::getIgnored();
609     } else {
610       return RValue::getAggregate(getAddress(), isVolatile());
611     }
612   }
613
614   void setZeroed(bool V = true) { ZeroedFlag = V; }
615   IsZeroed_t isZeroed() const {
616     return IsZeroed_t(ZeroedFlag);
617   }
618
619   /// Get the preferred size to use when storing a value to this slot. This
620   /// is the type size unless that might overlap another object, in which
621   /// case it's the dsize.
622   CharUnits getPreferredSize(ASTContext &Ctx, QualType Type) const {
623     return mayOverlap() ? Ctx.getTypeInfoDataSizeInChars(Type).first
624                         : Ctx.getTypeSizeInChars(Type);
625   }
626 };
627
628 }  // end namespace CodeGen
629 }  // end namespace clang
630
631 #endif