1 //===-- CGValue.h - LLVM CodeGen wrappers for llvm::Value* ------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // These classes implement wrappers around llvm::Value in order to
10 // fully represent the range of values for C L- and R- values.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGVALUE_H
15 #define LLVM_CLANG_LIB_CODEGEN_CGVALUE_H
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Type.h"
19 #include "llvm/IR/Value.h"
20 #include "llvm/IR/Type.h"
22 #include "CodeGenTBAA.h"
32 struct CGBitFieldInfo;
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.
39 enum Flavor { Scalar, Complex, Aggregate };
41 // The shift to make to an aggregate's alignment to make it look
43 enum { AggAlignShift = 4 };
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;
51 bool isScalar() const { return V1.getInt() == Scalar; }
52 bool isComplex() const { return V1.getInt() == Complex; }
53 bool isAggregate() const { return V1.getInt() == Aggregate; }
55 bool isVolatileQualified() const { return V2.getInt(); }
57 /// getScalarVal() - Return the Value* of this scalar value.
58 llvm::Value *getScalarVal() const {
59 assert(isScalar() && "Not a scalar!");
60 return V1.getPointer();
63 /// getComplexVal - Return the real/imag components of this complex value.
65 std::pair<llvm::Value *, llvm::Value *> getComplexVal() const {
66 return std::make_pair(V1.getPointer(), V2.getPointer());
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));
75 llvm::Value *getAggregatePointer() const {
76 assert(isAggregate() && "Not an aggregate!");
77 return V1.getPointer();
80 static RValue getIgnored() {
81 // FIXME: should we make this a more explicit state?
85 static RValue get(llvm::Value *V) {
92 static RValue getComplex(llvm::Value *V1, llvm::Value *V2) {
96 ER.V1.setInt(Complex);
100 static RValue getComplex(const std::pair<llvm::Value *, llvm::Value *> &C) {
101 return getComplex(C.first, C.second);
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
106 static RValue getAggregate(Address addr, bool isVolatile = false) {
108 ER.V1.setPointer(addr.getPointer());
109 ER.V1.setInt(Aggregate);
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);
118 /// Does an ARC strong l-value have precise lifetime?
119 enum ARCPreciseLifetime_t {
120 ARCImpreciseLifetime, ARCPreciseLifetime
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.
131 /// The l-value was considered opaque, so the alignment was
132 /// determined from a type, but that type was an explicitly-aligned
136 /// The l-value was considered opaque, so the alignment was
137 /// determined from a type.
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;
149 class LValueBaseInfo {
150 AlignmentSource AlignSource;
153 explicit LValueBaseInfo(AlignmentSource Source = AlignmentSource::Type)
154 : AlignSource(Source) {}
155 AlignmentSource getAlignmentSource() const { return AlignSource; }
156 void setAlignmentSource(AlignmentSource Source) { AlignSource = Source; }
158 void mergeForCast(const LValueBaseInfo &Info) {
159 setAlignmentSource(Info.getAlignmentSource());
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
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()
178 // Index into a vector subscript: V[i]
179 llvm::Value *VectorIdx;
181 // ExtVector element subset: V.xyx
182 llvm::Constant *VectorElts;
184 // BitField start bit and size
185 const CGBitFieldInfo *BitFieldInfo;
190 // 'const' is unused here
193 // The alignment to use when accessing this lvalue. (For vector elements,
194 // this is the alignment of the whole vector.)
197 // objective-c's ivar
200 // objective-c's ivar is an array
203 // LValue is non-gc'able for any reason, including being a parameter or local
207 // Lvalue is a global reference of an objective-c object
208 bool GlobalObjCRef : 1;
210 // Lvalue is a thread local reference
211 bool ThreadLocalRef : 1;
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;
217 // This flag shows if a nontemporal load/stores should be used when accessing
219 bool Nontemporal : 1;
221 LValueBaseInfo BaseInfo;
222 TBAAAccessInfo TBAAInfo;
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!");
233 const unsigned MaxAlign = 1U << 31;
234 this->Alignment = Alignment.getQuantity() <= MaxAlign
235 ? Alignment.getQuantity()
237 assert(this->Alignment == Alignment.getQuantity() &&
238 "Alignment exceeds allowed max!");
239 this->BaseInfo = BaseInfo;
240 this->TBAAInfo = TBAAInfo;
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;
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; }
257 bool isVolatileQualified() const { return Quals.hasVolatile(); }
258 bool isRestrictQualified() const { return Quals.hasRestrict(); }
259 unsigned getVRQualifiers() const {
260 return Quals.getCVRQualifiers() & ~Qualifiers::Const;
263 QualType getType() const { return Type; }
265 Qualifiers::ObjCLifetime getObjCLifetime() const {
266 return Quals.getObjCLifetime();
269 bool isObjCIvar() const { return Ivar; }
270 void setObjCIvar(bool Value) { Ivar = Value; }
272 bool isObjCArray() const { return ObjIsArray; }
273 void setObjCArray(bool Value) { ObjIsArray = Value; }
275 bool isNonGC () const { return NonGC; }
276 void setNonGC(bool Value) { NonGC = Value; }
278 bool isGlobalObjCRef() const { return GlobalObjCRef; }
279 void setGlobalObjCRef(bool Value) { GlobalObjCRef = Value; }
281 bool isThreadLocalRef() const { return ThreadLocalRef; }
282 void setThreadLocalRef(bool Value) { ThreadLocalRef = Value;}
284 ARCPreciseLifetime_t isARCPreciseLifetime() const {
285 return ARCPreciseLifetime_t(!ImpreciseLifetime);
287 void setARCPreciseLifetime(ARCPreciseLifetime_t value) {
288 ImpreciseLifetime = (value == ARCImpreciseLifetime);
290 bool isNontemporal() const { return Nontemporal; }
291 void setNontemporal(bool Value) { Nontemporal = Value; }
293 bool isObjCWeak() const {
294 return Quals.getObjCGCAttr() == Qualifiers::Weak;
296 bool isObjCStrong() const {
297 return Quals.getObjCGCAttr() == Qualifiers::Strong;
300 bool isVolatile() const {
301 return Quals.hasVolatile();
304 Expr *getBaseIvarExp() const { return BaseIvarExp; }
305 void setBaseIvarExp(Expr *V) { BaseIvarExp = V; }
307 TBAAAccessInfo getTBAAInfo() const { return TBAAInfo; }
308 void setTBAAInfo(TBAAAccessInfo Info) { TBAAInfo = Info; }
310 const Qualifiers &getQuals() const { return Quals; }
311 Qualifiers &getQuals() { return Quals; }
313 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
315 CharUnits getAlignment() const { return CharUnits::fromQuantity(Alignment); }
316 void setAlignment(CharUnits A) { Alignment = A.getQuantity(); }
318 LValueBaseInfo getBaseInfo() const { return BaseInfo; }
319 void setBaseInfo(LValueBaseInfo Info) { BaseInfo = Info; }
322 llvm::Value *getPointer() const {
326 Address getAddress() const { return Address(getPointer(), getAlignment()); }
327 void setAddress(Address address) {
329 V = address.getPointer();
330 Alignment = address.getAlignment().getQuantity();
334 Address getVectorAddress() const {
335 return Address(getVectorPointer(), getAlignment());
337 llvm::Value *getVectorPointer() const { assert(isVectorElt()); return V; }
338 llvm::Value *getVectorIdx() const { assert(isVectorElt()); return VectorIdx; }
340 // extended vector elements.
341 Address getExtVectorAddress() const {
342 return Address(getExtVectorPointer(), getAlignment());
344 llvm::Value *getExtVectorPointer() const {
345 assert(isExtVectorElt());
348 llvm::Constant *getExtVectorElts() const {
349 assert(isExtVectorElt());
354 Address getBitFieldAddress() const {
355 return Address(getBitFieldPointer(), getAlignment());
357 llvm::Value *getBitFieldPointer() const { assert(isBitField()); return V; }
358 const CGBitFieldInfo &getBitFieldInfo() const {
359 assert(isBitField());
360 return *BitFieldInfo;
363 // global register lvalue
364 llvm::Value *getGlobalReg() const { assert(isGlobalReg()); return V; }
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));
373 assert(address.getPointer()->getType()->isPointerTy());
374 R.V = address.getPointer();
375 R.Initialize(type, qs, address.getAlignment(), BaseInfo, TBAAInfo);
379 static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx,
380 QualType type, LValueBaseInfo BaseInfo,
381 TBAAAccessInfo TBAAInfo) {
383 R.LVType = VectorElt;
384 R.V = vecAddress.getPointer();
386 R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
391 static LValue MakeExtVectorElt(Address vecAddress, llvm::Constant *Elts,
392 QualType type, LValueBaseInfo BaseInfo,
393 TBAAAccessInfo TBAAInfo) {
395 R.LVType = ExtVectorElt;
396 R.V = vecAddress.getPointer();
398 R.Initialize(type, type.getQualifiers(), vecAddress.getAlignment(),
403 /// Create a new object to represent a bit-field access.
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
409 static LValue MakeBitfield(Address Addr, const CGBitFieldInfo &Info,
410 QualType type, LValueBaseInfo BaseInfo,
411 TBAAAccessInfo TBAAInfo) {
414 R.V = Addr.getPointer();
415 R.BitFieldInfo = &Info;
416 R.Initialize(type, type.getQualifiers(), Addr.getAlignment(), BaseInfo,
421 static LValue MakeGlobalReg(Address Reg, QualType type) {
423 R.LVType = GlobalReg;
424 R.V = Reg.getPointer();
425 R.Initialize(type, type.getQualifiers(), Reg.getAlignment(),
426 LValueBaseInfo(AlignmentSource::Decl), TBAAAccessInfo());
430 RValue asAggregateRValue() const {
431 return RValue::getAggregate(getAddress(), isVolatileQualified());
435 /// An aggregate value slot.
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;
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.
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.
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.
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;
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;
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
486 bool SanitizerCheckedFlag : 1;
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 };
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);
503 /// forAddr - Make a slot for an aggregate value.
505 /// \param quals - The qualifiers that dictate how the slot should
506 /// be initialied. Only 'volatile' and the Objective-C lifetime
507 /// qualifiers matter.
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,
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) {
522 if (addr.isValid()) {
523 AV.Addr = addr.getPointer();
524 AV.Alignment = addr.getAlignment().getQuantity();
530 AV.DestructedFlag = isDestructed;
531 AV.ObjCGCFlag = needsGC;
532 AV.ZeroedFlag = isZeroed;
533 AV.AliasedFlag = isAliased;
534 AV.OverlapFlag = mayOverlap;
535 AV.SanitizerCheckedFlag = isChecked;
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);
550 IsDestructed_t isExternallyDestructed() const {
551 return IsDestructed_t(DestructedFlag);
553 void setExternallyDestructed(bool destructed = true) {
554 DestructedFlag = destructed;
557 Qualifiers getQualifiers() const { return Quals; }
559 bool isVolatile() const {
560 return Quals.hasVolatile();
563 void setVolatile(bool flag) {
567 Quals.removeVolatile();
570 Qualifiers::ObjCLifetime getObjCLifetime() const {
571 return Quals.getObjCLifetime();
574 NeedsGCBarriers_t requiresGCollection() const {
575 return NeedsGCBarriers_t(ObjCGCFlag);
578 llvm::Value *getPointer() const {
582 Address getAddress() const {
583 return Address(Addr, getAlignment());
586 bool isIgnored() const {
587 return Addr == nullptr;
590 CharUnits getAlignment() const {
591 return CharUnits::fromQuantity(Alignment);
594 IsAliased_t isPotentiallyAliased() const {
595 return IsAliased_t(AliasedFlag);
598 Overlap_t mayOverlap() const {
599 return Overlap_t(OverlapFlag);
602 bool isSanitizerChecked() const {
603 return SanitizerCheckedFlag;
606 RValue asRValue() const {
608 return RValue::getIgnored();
610 return RValue::getAggregate(getAddress(), isVolatile());
614 void setZeroed(bool V = true) { ZeroedFlag = V; }
615 IsZeroed_t isZeroed() const {
616 return IsZeroed_t(ZeroedFlag);
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);
628 } // end namespace CodeGen
629 } // end namespace clang