Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGExprConstant.cpp
35234 views
//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This contains code to emit Constant Expr nodes as LLVM code.9//10//===----------------------------------------------------------------------===//1112#include "ABIInfoImpl.h"13#include "CGCXXABI.h"14#include "CGObjCRuntime.h"15#include "CGRecordLayout.h"16#include "CodeGenFunction.h"17#include "CodeGenModule.h"18#include "ConstantEmitter.h"19#include "TargetInfo.h"20#include "clang/AST/APValue.h"21#include "clang/AST/ASTContext.h"22#include "clang/AST/Attr.h"23#include "clang/AST/RecordLayout.h"24#include "clang/AST/StmtVisitor.h"25#include "clang/Basic/Builtins.h"26#include "llvm/ADT/STLExtras.h"27#include "llvm/ADT/Sequence.h"28#include "llvm/Analysis/ConstantFolding.h"29#include "llvm/IR/Constants.h"30#include "llvm/IR/DataLayout.h"31#include "llvm/IR/Function.h"32#include "llvm/IR/GlobalVariable.h"33#include <optional>34using namespace clang;35using namespace CodeGen;3637//===----------------------------------------------------------------------===//38// ConstantAggregateBuilder39//===----------------------------------------------------------------------===//4041namespace {42class ConstExprEmitter;4344struct ConstantAggregateBuilderUtils {45CodeGenModule &CGM;4647ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}4849CharUnits getAlignment(const llvm::Constant *C) const {50return CharUnits::fromQuantity(51CGM.getDataLayout().getABITypeAlign(C->getType()));52}5354CharUnits getSize(llvm::Type *Ty) const {55return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));56}5758CharUnits getSize(const llvm::Constant *C) const {59return getSize(C->getType());60}6162llvm::Constant *getPadding(CharUnits PadSize) const {63llvm::Type *Ty = CGM.CharTy;64if (PadSize > CharUnits::One())65Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());66return llvm::UndefValue::get(Ty);67}6869llvm::Constant *getZeroes(CharUnits ZeroSize) const {70llvm::Type *Ty = llvm::ArrayType::get(CGM.CharTy, ZeroSize.getQuantity());71return llvm::ConstantAggregateZero::get(Ty);72}73};7475/// Incremental builder for an llvm::Constant* holding a struct or array76/// constant.77class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {78/// The elements of the constant. These two arrays must have the same size;79/// Offsets[i] describes the offset of Elems[i] within the constant. The80/// elements are kept in increasing offset order, and we ensure that there81/// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).82///83/// This may contain explicit padding elements (in order to create a84/// natural layout), but need not. Gaps between elements are implicitly85/// considered to be filled with undef.86llvm::SmallVector<llvm::Constant*, 32> Elems;87llvm::SmallVector<CharUnits, 32> Offsets;8889/// The size of the constant (the maximum end offset of any added element).90/// May be larger than the end of Elems.back() if we split the last element91/// and removed some trailing undefs.92CharUnits Size = CharUnits::Zero();9394/// This is true only if laying out Elems in order as the elements of a95/// non-packed LLVM struct will give the correct layout.96bool NaturalLayout = true;9798bool split(size_t Index, CharUnits Hint);99std::optional<size_t> splitAt(CharUnits Pos);100101static llvm::Constant *buildFrom(CodeGenModule &CGM,102ArrayRef<llvm::Constant *> Elems,103ArrayRef<CharUnits> Offsets,104CharUnits StartOffset, CharUnits Size,105bool NaturalLayout, llvm::Type *DesiredTy,106bool AllowOversized);107108public:109ConstantAggregateBuilder(CodeGenModule &CGM)110: ConstantAggregateBuilderUtils(CGM) {}111112/// Update or overwrite the value starting at \p Offset with \c C.113///114/// \param AllowOverwrite If \c true, this constant might overwrite (part of)115/// a constant that has already been added. This flag is only used to116/// detect bugs.117bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);118119/// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.120bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);121122/// Attempt to condense the value starting at \p Offset to a constant of type123/// \p DesiredTy.124void condense(CharUnits Offset, llvm::Type *DesiredTy);125126/// Produce a constant representing the entire accumulated value, ideally of127/// the specified type. If \p AllowOversized, the constant might be larger128/// than implied by \p DesiredTy (eg, if there is a flexible array member).129/// Otherwise, the constant will be of exactly the same size as \p DesiredTy130/// even if we can't represent it as that type.131llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {132return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,133NaturalLayout, DesiredTy, AllowOversized);134}135};136137template<typename Container, typename Range = std::initializer_list<138typename Container::value_type>>139static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {140assert(BeginOff <= EndOff && "invalid replacement range");141llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);142}143144bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,145bool AllowOverwrite) {146// Common case: appending to a layout.147if (Offset >= Size) {148CharUnits Align = getAlignment(C);149CharUnits AlignedSize = Size.alignTo(Align);150if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)151NaturalLayout = false;152else if (AlignedSize < Offset) {153Elems.push_back(getPadding(Offset - Size));154Offsets.push_back(Size);155}156Elems.push_back(C);157Offsets.push_back(Offset);158Size = Offset + getSize(C);159return true;160}161162// Uncommon case: constant overlaps what we've already created.163std::optional<size_t> FirstElemToReplace = splitAt(Offset);164if (!FirstElemToReplace)165return false;166167CharUnits CSize = getSize(C);168std::optional<size_t> LastElemToReplace = splitAt(Offset + CSize);169if (!LastElemToReplace)170return false;171172assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&173"unexpectedly overwriting field");174175replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});176replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});177Size = std::max(Size, Offset + CSize);178NaturalLayout = false;179return true;180}181182bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,183bool AllowOverwrite) {184const ASTContext &Context = CGM.getContext();185const uint64_t CharWidth = CGM.getContext().getCharWidth();186187// Offset of where we want the first bit to go within the bits of the188// current char.189unsigned OffsetWithinChar = OffsetInBits % CharWidth;190191// We split bit-fields up into individual bytes. Walk over the bytes and192// update them.193for (CharUnits OffsetInChars =194Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar);195/**/; ++OffsetInChars) {196// Number of bits we want to fill in this char.197unsigned WantedBits =198std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);199200// Get a char containing the bits we want in the right places. The other201// bits have unspecified values.202llvm::APInt BitsThisChar = Bits;203if (BitsThisChar.getBitWidth() < CharWidth)204BitsThisChar = BitsThisChar.zext(CharWidth);205if (CGM.getDataLayout().isBigEndian()) {206// Figure out how much to shift by. We may need to left-shift if we have207// less than one byte of Bits left.208int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;209if (Shift > 0)210BitsThisChar.lshrInPlace(Shift);211else if (Shift < 0)212BitsThisChar = BitsThisChar.shl(-Shift);213} else {214BitsThisChar = BitsThisChar.shl(OffsetWithinChar);215}216if (BitsThisChar.getBitWidth() > CharWidth)217BitsThisChar = BitsThisChar.trunc(CharWidth);218219if (WantedBits == CharWidth) {220// Got a full byte: just add it directly.221add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),222OffsetInChars, AllowOverwrite);223} else {224// Partial byte: update the existing integer if there is one. If we225// can't split out a 1-CharUnit range to update, then we can't add226// these bits and fail the entire constant emission.227std::optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);228if (!FirstElemToUpdate)229return false;230std::optional<size_t> LastElemToUpdate =231splitAt(OffsetInChars + CharUnits::One());232if (!LastElemToUpdate)233return false;234assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&235"should have at most one element covering one byte");236237// Figure out which bits we want and discard the rest.238llvm::APInt UpdateMask(CharWidth, 0);239if (CGM.getDataLayout().isBigEndian())240UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,241CharWidth - OffsetWithinChar);242else243UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);244BitsThisChar &= UpdateMask;245246if (*FirstElemToUpdate == *LastElemToUpdate ||247Elems[*FirstElemToUpdate]->isNullValue() ||248isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {249// All existing bits are either zero or undef.250add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),251OffsetInChars, /*AllowOverwrite*/ true);252} else {253llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];254// In order to perform a partial update, we need the existing bitwise255// value, which we can only extract for a constant int.256auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);257if (!CI)258return false;259// Because this is a 1-CharUnit range, the constant occupying it must260// be exactly one CharUnit wide.261assert(CI->getBitWidth() == CharWidth && "splitAt failed");262assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&263"unexpectedly overwriting bitfield");264BitsThisChar |= (CI->getValue() & ~UpdateMask);265ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);266}267}268269// Stop if we've added all the bits.270if (WantedBits == Bits.getBitWidth())271break;272273// Remove the consumed bits from Bits.274if (!CGM.getDataLayout().isBigEndian())275Bits.lshrInPlace(WantedBits);276Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);277278// The remanining bits go at the start of the following bytes.279OffsetWithinChar = 0;280}281282return true;283}284285/// Returns a position within Elems and Offsets such that all elements286/// before the returned index end before Pos and all elements at or after287/// the returned index begin at or after Pos. Splits elements as necessary288/// to ensure this. Returns std::nullopt if we find something we can't split.289std::optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {290if (Pos >= Size)291return Offsets.size();292293while (true) {294auto FirstAfterPos = llvm::upper_bound(Offsets, Pos);295if (FirstAfterPos == Offsets.begin())296return 0;297298// If we already have an element starting at Pos, we're done.299size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;300if (Offsets[LastAtOrBeforePosIndex] == Pos)301return LastAtOrBeforePosIndex;302303// We found an element starting before Pos. Check for overlap.304if (Offsets[LastAtOrBeforePosIndex] +305getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)306return LastAtOrBeforePosIndex + 1;307308// Try to decompose it into smaller constants.309if (!split(LastAtOrBeforePosIndex, Pos))310return std::nullopt;311}312}313314/// Split the constant at index Index, if possible. Return true if we did.315/// Hint indicates the location at which we'd like to split, but may be316/// ignored.317bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {318NaturalLayout = false;319llvm::Constant *C = Elems[Index];320CharUnits Offset = Offsets[Index];321322if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {323// Expand the sequence into its contained elements.324// FIXME: This assumes vector elements are byte-sized.325replace(Elems, Index, Index + 1,326llvm::map_range(llvm::seq(0u, CA->getNumOperands()),327[&](unsigned Op) { return CA->getOperand(Op); }));328if (isa<llvm::ArrayType>(CA->getType()) ||329isa<llvm::VectorType>(CA->getType())) {330// Array or vector.331llvm::Type *ElemTy =332llvm::GetElementPtrInst::getTypeAtIndex(CA->getType(), (uint64_t)0);333CharUnits ElemSize = getSize(ElemTy);334replace(335Offsets, Index, Index + 1,336llvm::map_range(llvm::seq(0u, CA->getNumOperands()),337[&](unsigned Op) { return Offset + Op * ElemSize; }));338} else {339// Must be a struct.340auto *ST = cast<llvm::StructType>(CA->getType());341const llvm::StructLayout *Layout =342CGM.getDataLayout().getStructLayout(ST);343replace(Offsets, Index, Index + 1,344llvm::map_range(345llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {346return Offset + CharUnits::fromQuantity(347Layout->getElementOffset(Op));348}));349}350return true;351}352353if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {354// Expand the sequence into its contained elements.355// FIXME: This assumes vector elements are byte-sized.356// FIXME: If possible, split into two ConstantDataSequentials at Hint.357CharUnits ElemSize = getSize(CDS->getElementType());358replace(Elems, Index, Index + 1,359llvm::map_range(llvm::seq(0u, CDS->getNumElements()),360[&](unsigned Elem) {361return CDS->getElementAsConstant(Elem);362}));363replace(Offsets, Index, Index + 1,364llvm::map_range(365llvm::seq(0u, CDS->getNumElements()),366[&](unsigned Elem) { return Offset + Elem * ElemSize; }));367return true;368}369370if (isa<llvm::ConstantAggregateZero>(C)) {371// Split into two zeros at the hinted offset.372CharUnits ElemSize = getSize(C);373assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");374replace(Elems, Index, Index + 1,375{getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});376replace(Offsets, Index, Index + 1, {Offset, Hint});377return true;378}379380if (isa<llvm::UndefValue>(C)) {381// Drop undef; it doesn't contribute to the final layout.382replace(Elems, Index, Index + 1, {});383replace(Offsets, Index, Index + 1, {});384return true;385}386387// FIXME: We could split a ConstantInt if the need ever arose.388// We don't need to do this to handle bit-fields because we always eagerly389// split them into 1-byte chunks.390391return false;392}393394static llvm::Constant *395EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,396llvm::Type *CommonElementType, uint64_t ArrayBound,397SmallVectorImpl<llvm::Constant *> &Elements,398llvm::Constant *Filler);399400llvm::Constant *ConstantAggregateBuilder::buildFrom(401CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,402ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,403bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {404ConstantAggregateBuilderUtils Utils(CGM);405406if (Elems.empty())407return llvm::UndefValue::get(DesiredTy);408409auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };410411// If we want an array type, see if all the elements are the same type and412// appropriately spaced.413if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {414assert(!AllowOversized && "oversized array emission not supported");415416bool CanEmitArray = true;417llvm::Type *CommonType = Elems[0]->getType();418llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);419CharUnits ElemSize = Utils.getSize(ATy->getElementType());420SmallVector<llvm::Constant*, 32> ArrayElements;421for (size_t I = 0; I != Elems.size(); ++I) {422// Skip zeroes; we'll use a zero value as our array filler.423if (Elems[I]->isNullValue())424continue;425426// All remaining elements must be the same type.427if (Elems[I]->getType() != CommonType ||428Offset(I) % ElemSize != 0) {429CanEmitArray = false;430break;431}432ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);433ArrayElements.back() = Elems[I];434}435436if (CanEmitArray) {437return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),438ArrayElements, Filler);439}440441// Can't emit as an array, carry on to emit as a struct.442}443444// The size of the constant we plan to generate. This is usually just445// the size of the initialized type, but in AllowOversized mode (i.e.446// flexible array init), it can be larger.447CharUnits DesiredSize = Utils.getSize(DesiredTy);448if (Size > DesiredSize) {449assert(AllowOversized && "Elems are oversized");450DesiredSize = Size;451}452453// The natural alignment of an unpacked LLVM struct with the given elements.454CharUnits Align = CharUnits::One();455for (llvm::Constant *C : Elems)456Align = std::max(Align, Utils.getAlignment(C));457458// The natural size of an unpacked LLVM struct with the given elements.459CharUnits AlignedSize = Size.alignTo(Align);460461bool Packed = false;462ArrayRef<llvm::Constant*> UnpackedElems = Elems;463llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;464if (DesiredSize < AlignedSize || DesiredSize.alignTo(Align) != DesiredSize) {465// The natural layout would be too big; force use of a packed layout.466NaturalLayout = false;467Packed = true;468} else if (DesiredSize > AlignedSize) {469// The natural layout would be too small. Add padding to fix it. (This470// is ignored if we choose a packed layout.)471UnpackedElemStorage.assign(Elems.begin(), Elems.end());472UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));473UnpackedElems = UnpackedElemStorage;474}475476// If we don't have a natural layout, insert padding as necessary.477// As we go, double-check to see if we can actually just emit Elems478// as a non-packed struct and do so opportunistically if possible.479llvm::SmallVector<llvm::Constant*, 32> PackedElems;480if (!NaturalLayout) {481CharUnits SizeSoFar = CharUnits::Zero();482for (size_t I = 0; I != Elems.size(); ++I) {483CharUnits Align = Utils.getAlignment(Elems[I]);484CharUnits NaturalOffset = SizeSoFar.alignTo(Align);485CharUnits DesiredOffset = Offset(I);486assert(DesiredOffset >= SizeSoFar && "elements out of order");487488if (DesiredOffset != NaturalOffset)489Packed = true;490if (DesiredOffset != SizeSoFar)491PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));492PackedElems.push_back(Elems[I]);493SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);494}495// If we're using the packed layout, pad it out to the desired size if496// necessary.497if (Packed) {498assert(SizeSoFar <= DesiredSize &&499"requested size is too small for contents");500if (SizeSoFar < DesiredSize)501PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));502}503}504505llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(506CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);507508// Pick the type to use. If the type is layout identical to the desired509// type then use it, otherwise use whatever the builder produced for us.510if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {511if (DesiredSTy->isLayoutIdentical(STy))512STy = DesiredSTy;513}514515return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);516}517518void ConstantAggregateBuilder::condense(CharUnits Offset,519llvm::Type *DesiredTy) {520CharUnits Size = getSize(DesiredTy);521522std::optional<size_t> FirstElemToReplace = splitAt(Offset);523if (!FirstElemToReplace)524return;525size_t First = *FirstElemToReplace;526527std::optional<size_t> LastElemToReplace = splitAt(Offset + Size);528if (!LastElemToReplace)529return;530size_t Last = *LastElemToReplace;531532size_t Length = Last - First;533if (Length == 0)534return;535536if (Length == 1 && Offsets[First] == Offset &&537getSize(Elems[First]) == Size) {538// Re-wrap single element structs if necessary. Otherwise, leave any single539// element constant of the right size alone even if it has the wrong type.540auto *STy = dyn_cast<llvm::StructType>(DesiredTy);541if (STy && STy->getNumElements() == 1 &&542STy->getElementType(0) == Elems[First]->getType())543Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);544return;545}546547llvm::Constant *Replacement = buildFrom(548CGM, ArrayRef(Elems).slice(First, Length),549ArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),550/*known to have natural layout=*/false, DesiredTy, false);551replace(Elems, First, Last, {Replacement});552replace(Offsets, First, Last, {Offset});553}554555//===----------------------------------------------------------------------===//556// ConstStructBuilder557//===----------------------------------------------------------------------===//558559class ConstStructBuilder {560CodeGenModule &CGM;561ConstantEmitter &Emitter;562ConstantAggregateBuilder &Builder;563CharUnits StartOffset;564565public:566static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,567const InitListExpr *ILE,568QualType StructTy);569static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,570const APValue &Value, QualType ValTy);571static bool UpdateStruct(ConstantEmitter &Emitter,572ConstantAggregateBuilder &Const, CharUnits Offset,573const InitListExpr *Updater);574575private:576ConstStructBuilder(ConstantEmitter &Emitter,577ConstantAggregateBuilder &Builder, CharUnits StartOffset)578: CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),579StartOffset(StartOffset) {}580581bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,582llvm::Constant *InitExpr, bool AllowOverwrite = false);583584bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,585bool AllowOverwrite = false);586587bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,588llvm::Constant *InitExpr, bool AllowOverwrite = false);589590bool Build(const InitListExpr *ILE, bool AllowOverwrite);591bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,592const CXXRecordDecl *VTableClass, CharUnits BaseOffset);593llvm::Constant *Finalize(QualType Ty);594};595596bool ConstStructBuilder::AppendField(597const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,598bool AllowOverwrite) {599const ASTContext &Context = CGM.getContext();600601CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);602603return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);604}605606bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,607llvm::Constant *InitCst,608bool AllowOverwrite) {609return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);610}611612bool ConstStructBuilder::AppendBitField(const FieldDecl *Field,613uint64_t FieldOffset, llvm::Constant *C,614bool AllowOverwrite) {615616llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C);617if (!CI) {618// Constants for long _BitInt types are sometimes split into individual619// bytes. Try to fold these back into an integer constant. If that doesn't620// work out, then we are trying to initialize a bitfield with a non-trivial621// constant, this must require run-time code.622llvm::Type *LoadType =623CGM.getTypes().convertTypeForLoadStore(Field->getType(), C->getType());624llvm::Constant *FoldedConstant = llvm::ConstantFoldLoadFromConst(625C, LoadType, llvm::APInt::getZero(32), CGM.getDataLayout());626CI = dyn_cast_if_present<llvm::ConstantInt>(FoldedConstant);627if (!CI)628return false;629}630631const CGRecordLayout &RL =632CGM.getTypes().getCGRecordLayout(Field->getParent());633const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);634llvm::APInt FieldValue = CI->getValue();635636// Promote the size of FieldValue if necessary637// FIXME: This should never occur, but currently it can because initializer638// constants are cast to bool, and because clang is not enforcing bitfield639// width limits.640if (Info.Size > FieldValue.getBitWidth())641FieldValue = FieldValue.zext(Info.Size);642643// Truncate the size of FieldValue to the bit field size.644if (Info.Size < FieldValue.getBitWidth())645FieldValue = FieldValue.trunc(Info.Size);646647return Builder.addBits(FieldValue,648CGM.getContext().toBits(StartOffset) + FieldOffset,649AllowOverwrite);650}651652static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,653ConstantAggregateBuilder &Const,654CharUnits Offset, QualType Type,655const InitListExpr *Updater) {656if (Type->isRecordType())657return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);658659auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);660if (!CAT)661return false;662QualType ElemType = CAT->getElementType();663CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);664llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);665666llvm::Constant *FillC = nullptr;667if (const Expr *Filler = Updater->getArrayFiller()) {668if (!isa<NoInitExpr>(Filler)) {669FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);670if (!FillC)671return false;672}673}674675unsigned NumElementsToUpdate =676FillC ? CAT->getZExtSize() : Updater->getNumInits();677for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {678const Expr *Init = nullptr;679if (I < Updater->getNumInits())680Init = Updater->getInit(I);681682if (!Init && FillC) {683if (!Const.add(FillC, Offset, true))684return false;685} else if (!Init || isa<NoInitExpr>(Init)) {686continue;687} else if (const auto *ChildILE = dyn_cast<InitListExpr>(Init)) {688if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,689ChildILE))690return false;691// Attempt to reduce the array element to a single constant if necessary.692Const.condense(Offset, ElemTy);693} else {694llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);695if (!Const.add(Val, Offset, true))696return false;697}698}699700return true;701}702703bool ConstStructBuilder::Build(const InitListExpr *ILE, bool AllowOverwrite) {704RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();705const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);706707unsigned FieldNo = -1;708unsigned ElementNo = 0;709710// Bail out if we have base classes. We could support these, but they only711// arise in C++1z where we will have already constant folded most interesting712// cases. FIXME: There are still a few more cases we can handle this way.713if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))714if (CXXRD->getNumBases())715return false;716717for (FieldDecl *Field : RD->fields()) {718++FieldNo;719720// If this is a union, skip all the fields that aren't being initialized.721if (RD->isUnion() &&722!declaresSameEntity(ILE->getInitializedFieldInUnion(), Field))723continue;724725// Don't emit anonymous bitfields.726if (Field->isUnnamedBitField())727continue;728729// Get the initializer. A struct can include fields without initializers,730// we just use explicit null values for them.731const Expr *Init = nullptr;732if (ElementNo < ILE->getNumInits())733Init = ILE->getInit(ElementNo++);734if (isa_and_nonnull<NoInitExpr>(Init))735continue;736737// Zero-sized fields are not emitted, but their initializers may still738// prevent emission of this struct as a constant.739if (isEmptyFieldForLayout(CGM.getContext(), Field)) {740if (Init->HasSideEffects(CGM.getContext()))741return false;742continue;743}744745// When emitting a DesignatedInitUpdateExpr, a nested InitListExpr746// represents additional overwriting of our current constant value, and not747// a new constant to emit independently.748if (AllowOverwrite &&749(Field->getType()->isArrayType() || Field->getType()->isRecordType())) {750if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {751CharUnits Offset = CGM.getContext().toCharUnitsFromBits(752Layout.getFieldOffset(FieldNo));753if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,754Field->getType(), SubILE))755return false;756// If we split apart the field's value, try to collapse it down to a757// single value now.758Builder.condense(StartOffset + Offset,759CGM.getTypes().ConvertTypeForMem(Field->getType()));760continue;761}762}763764llvm::Constant *EltInit =765Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())766: Emitter.emitNullForMemory(Field->getType());767if (!EltInit)768return false;769770if (!Field->isBitField()) {771// Handle non-bitfield members.772if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,773AllowOverwrite))774return false;775// After emitting a non-empty field with [[no_unique_address]], we may776// need to overwrite its tail padding.777if (Field->hasAttr<NoUniqueAddressAttr>())778AllowOverwrite = true;779} else {780// Otherwise we have a bitfield.781if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), EltInit,782AllowOverwrite))783return false;784}785}786787return true;788}789790namespace {791struct BaseInfo {792BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)793: Decl(Decl), Offset(Offset), Index(Index) {794}795796const CXXRecordDecl *Decl;797CharUnits Offset;798unsigned Index;799800bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }801};802}803804bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,805bool IsPrimaryBase,806const CXXRecordDecl *VTableClass,807CharUnits Offset) {808const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);809810if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {811// Add a vtable pointer, if we need one and it hasn't already been added.812if (Layout.hasOwnVFPtr()) {813llvm::Constant *VTableAddressPoint =814CGM.getCXXABI().getVTableAddressPoint(BaseSubobject(CD, Offset),815VTableClass);816if (auto Authentication = CGM.getVTablePointerAuthentication(CD)) {817VTableAddressPoint = Emitter.tryEmitConstantSignedPointer(818VTableAddressPoint, *Authentication);819if (!VTableAddressPoint)820return false;821}822if (!AppendBytes(Offset, VTableAddressPoint))823return false;824}825826// Accumulate and sort bases, in order to visit them in address order, which827// may not be the same as declaration order.828SmallVector<BaseInfo, 8> Bases;829Bases.reserve(CD->getNumBases());830unsigned BaseNo = 0;831for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),832BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {833assert(!Base->isVirtual() && "should not have virtual bases here");834const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();835CharUnits BaseOffset = Layout.getBaseClassOffset(BD);836Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));837}838llvm::stable_sort(Bases);839840for (unsigned I = 0, N = Bases.size(); I != N; ++I) {841BaseInfo &Base = Bases[I];842843bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;844Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,845VTableClass, Offset + Base.Offset);846}847}848849unsigned FieldNo = 0;850uint64_t OffsetBits = CGM.getContext().toBits(Offset);851852bool AllowOverwrite = false;853for (RecordDecl::field_iterator Field = RD->field_begin(),854FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {855// If this is a union, skip all the fields that aren't being initialized.856if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))857continue;858859// Don't emit anonymous bitfields or zero-sized fields.860if (Field->isUnnamedBitField() ||861isEmptyFieldForLayout(CGM.getContext(), *Field))862continue;863864// Emit the value of the initializer.865const APValue &FieldValue =866RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);867llvm::Constant *EltInit =868Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());869if (!EltInit)870return false;871872if (!Field->isBitField()) {873// Handle non-bitfield members.874if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,875EltInit, AllowOverwrite))876return false;877// After emitting a non-empty field with [[no_unique_address]], we may878// need to overwrite its tail padding.879if (Field->hasAttr<NoUniqueAddressAttr>())880AllowOverwrite = true;881} else {882// Otherwise we have a bitfield.883if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,884EltInit, AllowOverwrite))885return false;886}887}888889return true;890}891892llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {893Type = Type.getNonReferenceType();894RecordDecl *RD = Type->castAs<RecordType>()->getDecl();895llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);896return Builder.build(ValTy, RD->hasFlexibleArrayMember());897}898899llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,900const InitListExpr *ILE,901QualType ValTy) {902ConstantAggregateBuilder Const(Emitter.CGM);903ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());904905if (!Builder.Build(ILE, /*AllowOverwrite*/false))906return nullptr;907908return Builder.Finalize(ValTy);909}910911llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,912const APValue &Val,913QualType ValTy) {914ConstantAggregateBuilder Const(Emitter.CGM);915ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());916917const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();918const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);919if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))920return nullptr;921922return Builder.Finalize(ValTy);923}924925bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,926ConstantAggregateBuilder &Const,927CharUnits Offset,928const InitListExpr *Updater) {929return ConstStructBuilder(Emitter, Const, Offset)930.Build(Updater, /*AllowOverwrite*/ true);931}932933//===----------------------------------------------------------------------===//934// ConstExprEmitter935//===----------------------------------------------------------------------===//936937static ConstantAddress938tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter,939const CompoundLiteralExpr *E) {940CodeGenModule &CGM = emitter.CGM;941CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());942if (llvm::GlobalVariable *Addr =943CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))944return ConstantAddress(Addr, Addr->getValueType(), Align);945946LangAS addressSpace = E->getType().getAddressSpace();947llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),948addressSpace, E->getType());949if (!C) {950assert(!E->isFileScope() &&951"file-scope compound literal did not have constant initializer!");952return ConstantAddress::invalid();953}954955auto GV = new llvm::GlobalVariable(956CGM.getModule(), C->getType(),957E->getType().isConstantStorage(CGM.getContext(), true, false),958llvm::GlobalValue::InternalLinkage, C, ".compoundliteral", nullptr,959llvm::GlobalVariable::NotThreadLocal,960CGM.getContext().getTargetAddressSpace(addressSpace));961emitter.finalize(GV);962GV->setAlignment(Align.getAsAlign());963CGM.setAddrOfConstantCompoundLiteral(E, GV);964return ConstantAddress(GV, GV->getValueType(), Align);965}966967static llvm::Constant *968EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,969llvm::Type *CommonElementType, uint64_t ArrayBound,970SmallVectorImpl<llvm::Constant *> &Elements,971llvm::Constant *Filler) {972// Figure out how long the initial prefix of non-zero elements is.973uint64_t NonzeroLength = ArrayBound;974if (Elements.size() < NonzeroLength && Filler->isNullValue())975NonzeroLength = Elements.size();976if (NonzeroLength == Elements.size()) {977while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())978--NonzeroLength;979}980981if (NonzeroLength == 0)982return llvm::ConstantAggregateZero::get(DesiredType);983984// Add a zeroinitializer array filler if we have lots of trailing zeroes.985uint64_t TrailingZeroes = ArrayBound - NonzeroLength;986if (TrailingZeroes >= 8) {987assert(Elements.size() >= NonzeroLength &&988"missing initializer for non-zero element");989990// If all the elements had the same type up to the trailing zeroes, emit a991// struct of two arrays (the nonzero data and the zeroinitializer).992if (CommonElementType && NonzeroLength >= 8) {993llvm::Constant *Initial = llvm::ConstantArray::get(994llvm::ArrayType::get(CommonElementType, NonzeroLength),995ArrayRef(Elements).take_front(NonzeroLength));996Elements.resize(2);997Elements[0] = Initial;998} else {999Elements.resize(NonzeroLength + 1);1000}10011002auto *FillerType =1003CommonElementType ? CommonElementType : DesiredType->getElementType();1004FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);1005Elements.back() = llvm::ConstantAggregateZero::get(FillerType);1006CommonElementType = nullptr;1007} else if (Elements.size() != ArrayBound) {1008// Otherwise pad to the right size with the filler if necessary.1009Elements.resize(ArrayBound, Filler);1010if (Filler->getType() != CommonElementType)1011CommonElementType = nullptr;1012}10131014// If all elements have the same type, just emit an array constant.1015if (CommonElementType)1016return llvm::ConstantArray::get(1017llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);10181019// We have mixed types. Use a packed struct.1020llvm::SmallVector<llvm::Type *, 16> Types;1021Types.reserve(Elements.size());1022for (llvm::Constant *Elt : Elements)1023Types.push_back(Elt->getType());1024llvm::StructType *SType =1025llvm::StructType::get(CGM.getLLVMContext(), Types, true);1026return llvm::ConstantStruct::get(SType, Elements);1027}10281029// This class only needs to handle arrays, structs and unions. Outside C++111030// mode, we don't currently constant fold those types. All other types are1031// handled by constant folding.1032//1033// Constant folding is currently missing support for a few features supported1034// here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.1035class ConstExprEmitter1036: public ConstStmtVisitor<ConstExprEmitter, llvm::Constant *, QualType> {1037CodeGenModule &CGM;1038ConstantEmitter &Emitter;1039llvm::LLVMContext &VMContext;1040public:1041ConstExprEmitter(ConstantEmitter &emitter)1042: CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {1043}10441045//===--------------------------------------------------------------------===//1046// Visitor Methods1047//===--------------------------------------------------------------------===//10481049llvm::Constant *VisitStmt(const Stmt *S, QualType T) { return nullptr; }10501051llvm::Constant *VisitConstantExpr(const ConstantExpr *CE, QualType T) {1052if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(CE))1053return Result;1054return Visit(CE->getSubExpr(), T);1055}10561057llvm::Constant *VisitParenExpr(const ParenExpr *PE, QualType T) {1058return Visit(PE->getSubExpr(), T);1059}10601061llvm::Constant *1062VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *PE,1063QualType T) {1064return Visit(PE->getReplacement(), T);1065}10661067llvm::Constant *VisitGenericSelectionExpr(const GenericSelectionExpr *GE,1068QualType T) {1069return Visit(GE->getResultExpr(), T);1070}10711072llvm::Constant *VisitChooseExpr(const ChooseExpr *CE, QualType T) {1073return Visit(CE->getChosenSubExpr(), T);1074}10751076llvm::Constant *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E,1077QualType T) {1078return Visit(E->getInitializer(), T);1079}10801081llvm::Constant *ProduceIntToIntCast(const Expr *E, QualType DestType) {1082QualType FromType = E->getType();1083// See also HandleIntToIntCast in ExprConstant.cpp1084if (FromType->isIntegerType())1085if (llvm::Constant *C = Visit(E, FromType))1086if (auto *CI = dyn_cast<llvm::ConstantInt>(C)) {1087unsigned SrcWidth = CGM.getContext().getIntWidth(FromType);1088unsigned DstWidth = CGM.getContext().getIntWidth(DestType);1089if (DstWidth == SrcWidth)1090return CI;1091llvm::APInt A = FromType->isSignedIntegerType()1092? CI->getValue().sextOrTrunc(DstWidth)1093: CI->getValue().zextOrTrunc(DstWidth);1094return llvm::ConstantInt::get(CGM.getLLVMContext(), A);1095}1096return nullptr;1097}10981099llvm::Constant *VisitCastExpr(const CastExpr *E, QualType destType) {1100if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))1101CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);1102const Expr *subExpr = E->getSubExpr();11031104switch (E->getCastKind()) {1105case CK_ToUnion: {1106// GCC cast to union extension1107assert(E->getType()->isUnionType() &&1108"Destination type is not union type!");11091110auto field = E->getTargetUnionField();11111112auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());1113if (!C) return nullptr;11141115auto destTy = ConvertType(destType);1116if (C->getType() == destTy) return C;11171118// Build a struct with the union sub-element as the first member,1119// and padded to the appropriate size.1120SmallVector<llvm::Constant*, 2> Elts;1121SmallVector<llvm::Type*, 2> Types;1122Elts.push_back(C);1123Types.push_back(C->getType());1124unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());1125unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);11261127assert(CurSize <= TotalSize && "Union size mismatch!");1128if (unsigned NumPadBytes = TotalSize - CurSize) {1129llvm::Type *Ty = CGM.CharTy;1130if (NumPadBytes > 1)1131Ty = llvm::ArrayType::get(Ty, NumPadBytes);11321133Elts.push_back(llvm::UndefValue::get(Ty));1134Types.push_back(Ty);1135}11361137llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);1138return llvm::ConstantStruct::get(STy, Elts);1139}11401141case CK_AddressSpaceConversion: {1142auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());1143if (!C) return nullptr;1144LangAS destAS = E->getType()->getPointeeType().getAddressSpace();1145LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();1146llvm::Type *destTy = ConvertType(E->getType());1147return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,1148destAS, destTy);1149}11501151case CK_LValueToRValue: {1152// We don't really support doing lvalue-to-rvalue conversions here; any1153// interesting conversions should be done in Evaluate(). But as a1154// special case, allow compound literals to support the gcc extension1155// allowing "struct x {int x;} x = (struct x) {};".1156if (const auto *E =1157dyn_cast<CompoundLiteralExpr>(subExpr->IgnoreParens()))1158return Visit(E->getInitializer(), destType);1159return nullptr;1160}11611162case CK_AtomicToNonAtomic:1163case CK_NonAtomicToAtomic:1164case CK_NoOp:1165case CK_ConstructorConversion:1166return Visit(subExpr, destType);11671168case CK_ArrayToPointerDecay:1169if (const auto *S = dyn_cast<StringLiteral>(subExpr))1170return CGM.GetAddrOfConstantStringFromLiteral(S).getPointer();1171return nullptr;1172case CK_NullToPointer:1173if (Visit(subExpr, destType))1174return CGM.EmitNullConstant(destType);1175return nullptr;11761177case CK_IntToOCLSampler:1178llvm_unreachable("global sampler variables are not generated");11791180case CK_IntegralCast:1181return ProduceIntToIntCast(subExpr, destType);11821183case CK_Dependent: llvm_unreachable("saw dependent cast!");11841185case CK_BuiltinFnToFnPtr:1186llvm_unreachable("builtin functions are handled elsewhere");11871188case CK_ReinterpretMemberPointer:1189case CK_DerivedToBaseMemberPointer:1190case CK_BaseToDerivedMemberPointer: {1191auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());1192if (!C) return nullptr;1193return CGM.getCXXABI().EmitMemberPointerConversion(E, C);1194}11951196// These will never be supported.1197case CK_ObjCObjectLValueCast:1198case CK_ARCProduceObject:1199case CK_ARCConsumeObject:1200case CK_ARCReclaimReturnedObject:1201case CK_ARCExtendBlockObject:1202case CK_CopyAndAutoreleaseBlockObject:1203return nullptr;12041205// These don't need to be handled here because Evaluate knows how to1206// evaluate them in the cases where they can be folded.1207case CK_BitCast:1208case CK_ToVoid:1209case CK_Dynamic:1210case CK_LValueBitCast:1211case CK_LValueToRValueBitCast:1212case CK_NullToMemberPointer:1213case CK_UserDefinedConversion:1214case CK_CPointerToObjCPointerCast:1215case CK_BlockPointerToObjCPointerCast:1216case CK_AnyPointerToBlockPointerCast:1217case CK_FunctionToPointerDecay:1218case CK_BaseToDerived:1219case CK_DerivedToBase:1220case CK_UncheckedDerivedToBase:1221case CK_MemberPointerToBoolean:1222case CK_VectorSplat:1223case CK_FloatingRealToComplex:1224case CK_FloatingComplexToReal:1225case CK_FloatingComplexToBoolean:1226case CK_FloatingComplexCast:1227case CK_FloatingComplexToIntegralComplex:1228case CK_IntegralRealToComplex:1229case CK_IntegralComplexToReal:1230case CK_IntegralComplexToBoolean:1231case CK_IntegralComplexCast:1232case CK_IntegralComplexToFloatingComplex:1233case CK_PointerToIntegral:1234case CK_PointerToBoolean:1235case CK_BooleanToSignedIntegral:1236case CK_IntegralToPointer:1237case CK_IntegralToBoolean:1238case CK_IntegralToFloating:1239case CK_FloatingToIntegral:1240case CK_FloatingToBoolean:1241case CK_FloatingCast:1242case CK_FloatingToFixedPoint:1243case CK_FixedPointToFloating:1244case CK_FixedPointCast:1245case CK_FixedPointToBoolean:1246case CK_FixedPointToIntegral:1247case CK_IntegralToFixedPoint:1248case CK_ZeroToOCLOpaqueType:1249case CK_MatrixCast:1250case CK_HLSLVectorTruncation:1251case CK_HLSLArrayRValue:1252return nullptr;1253}1254llvm_unreachable("Invalid CastKind");1255}12561257llvm::Constant *VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *DIE,1258QualType T) {1259// No need for a DefaultInitExprScope: we don't handle 'this' in a1260// constant expression.1261return Visit(DIE->getExpr(), T);1262}12631264llvm::Constant *VisitExprWithCleanups(const ExprWithCleanups *E, QualType T) {1265return Visit(E->getSubExpr(), T);1266}12671268llvm::Constant *VisitIntegerLiteral(const IntegerLiteral *I, QualType T) {1269return llvm::ConstantInt::get(CGM.getLLVMContext(), I->getValue());1270}12711272static APValue withDestType(ASTContext &Ctx, const Expr *E, QualType SrcType,1273QualType DestType, const llvm::APSInt &Value) {1274if (!Ctx.hasSameType(SrcType, DestType)) {1275if (DestType->isFloatingType()) {1276llvm::APFloat Result =1277llvm::APFloat(Ctx.getFloatTypeSemantics(DestType), 1);1278llvm::RoundingMode RM =1279E->getFPFeaturesInEffect(Ctx.getLangOpts()).getRoundingMode();1280if (RM == llvm::RoundingMode::Dynamic)1281RM = llvm::RoundingMode::NearestTiesToEven;1282Result.convertFromAPInt(Value, Value.isSigned(), RM);1283return APValue(Result);1284}1285}1286return APValue(Value);1287}12881289llvm::Constant *EmitArrayInitialization(const InitListExpr *ILE, QualType T) {1290auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());1291assert(CAT && "can't emit array init for non-constant-bound array");1292uint64_t NumInitElements = ILE->getNumInits();1293const uint64_t NumElements = CAT->getZExtSize();1294for (const auto *Init : ILE->inits()) {1295if (const auto *Embed =1296dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {1297NumInitElements += Embed->getDataElementCount() - 1;1298if (NumInitElements > NumElements) {1299NumInitElements = NumElements;1300break;1301}1302}1303}13041305// Initialising an array requires us to automatically1306// initialise any elements that have not been initialised explicitly1307uint64_t NumInitableElts = std::min<uint64_t>(NumInitElements, NumElements);13081309QualType EltType = CAT->getElementType();13101311// Initialize remaining array elements.1312llvm::Constant *fillC = nullptr;1313if (const Expr *filler = ILE->getArrayFiller()) {1314fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);1315if (!fillC)1316return nullptr;1317}13181319// Copy initializer elements.1320SmallVector<llvm::Constant *, 16> Elts;1321if (fillC && fillC->isNullValue())1322Elts.reserve(NumInitableElts + 1);1323else1324Elts.reserve(NumElements);13251326llvm::Type *CommonElementType = nullptr;1327auto Emit = [&](const Expr *Init, unsigned ArrayIndex) {1328llvm::Constant *C = nullptr;1329C = Emitter.tryEmitPrivateForMemory(Init, EltType);1330if (!C)1331return false;1332if (ArrayIndex == 0)1333CommonElementType = C->getType();1334else if (C->getType() != CommonElementType)1335CommonElementType = nullptr;1336Elts.push_back(C);1337return true;1338};13391340unsigned ArrayIndex = 0;1341QualType DestTy = CAT->getElementType();1342for (unsigned i = 0; i < ILE->getNumInits(); ++i) {1343const Expr *Init = ILE->getInit(i);1344if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {1345StringLiteral *SL = EmbedS->getDataStringLiteral();1346llvm::APSInt Value(CGM.getContext().getTypeSize(DestTy),1347DestTy->isUnsignedIntegerType());1348llvm::Constant *C;1349for (unsigned I = EmbedS->getStartingElementPos(),1350N = EmbedS->getDataElementCount();1351I != EmbedS->getStartingElementPos() + N; ++I) {1352Value = SL->getCodeUnit(I);1353if (DestTy->isIntegerType()) {1354C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value);1355} else {1356C = Emitter.tryEmitPrivateForMemory(1357withDestType(CGM.getContext(), Init, EmbedS->getType(), DestTy,1358Value),1359EltType);1360}1361if (!C)1362return nullptr;1363Elts.push_back(C);1364ArrayIndex++;1365}1366if ((ArrayIndex - EmbedS->getDataElementCount()) == 0)1367CommonElementType = C->getType();1368else if (C->getType() != CommonElementType)1369CommonElementType = nullptr;1370} else {1371if (!Emit(Init, ArrayIndex))1372return nullptr;1373ArrayIndex++;1374}1375}13761377llvm::ArrayType *Desired =1378cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));1379return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,1380fillC);1381}13821383llvm::Constant *EmitRecordInitialization(const InitListExpr *ILE,1384QualType T) {1385return ConstStructBuilder::BuildStruct(Emitter, ILE, T);1386}13871388llvm::Constant *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E,1389QualType T) {1390return CGM.EmitNullConstant(T);1391}13921393llvm::Constant *VisitInitListExpr(const InitListExpr *ILE, QualType T) {1394if (ILE->isTransparent())1395return Visit(ILE->getInit(0), T);13961397if (ILE->getType()->isArrayType())1398return EmitArrayInitialization(ILE, T);13991400if (ILE->getType()->isRecordType())1401return EmitRecordInitialization(ILE, T);14021403return nullptr;1404}14051406llvm::Constant *1407VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E,1408QualType destType) {1409auto C = Visit(E->getBase(), destType);1410if (!C)1411return nullptr;14121413ConstantAggregateBuilder Const(CGM);1414Const.add(C, CharUnits::Zero(), false);14151416if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,1417E->getUpdater()))1418return nullptr;14191420llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);1421bool HasFlexibleArray = false;1422if (const auto *RT = destType->getAs<RecordType>())1423HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();1424return Const.build(ValTy, HasFlexibleArray);1425}14261427llvm::Constant *VisitCXXConstructExpr(const CXXConstructExpr *E,1428QualType Ty) {1429if (!E->getConstructor()->isTrivial())1430return nullptr;14311432// Only default and copy/move constructors can be trivial.1433if (E->getNumArgs()) {1434assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");1435assert(E->getConstructor()->isCopyOrMoveConstructor() &&1436"trivial ctor has argument but isn't a copy/move ctor");14371438const Expr *Arg = E->getArg(0);1439assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&1440"argument to copy ctor is of wrong type");14411442// Look through the temporary; it's just converting the value to an1443// lvalue to pass it to the constructor.1444if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Arg))1445return Visit(MTE->getSubExpr(), Ty);1446// Don't try to support arbitrary lvalue-to-rvalue conversions for now.1447return nullptr;1448}14491450return CGM.EmitNullConstant(Ty);1451}14521453llvm::Constant *VisitStringLiteral(const StringLiteral *E, QualType T) {1454// This is a string literal initializing an array in an initializer.1455return CGM.GetConstantArrayFromStringLiteral(E);1456}14571458llvm::Constant *VisitObjCEncodeExpr(const ObjCEncodeExpr *E, QualType T) {1459// This must be an @encode initializing an array in a static initializer.1460// Don't emit it as the address of the string, emit the string data itself1461// as an inline array.1462std::string Str;1463CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);1464const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);1465assert(CAT && "String data not of constant array type!");14661467// Resize the string to the right size, adding zeros at the end, or1468// truncating as needed.1469Str.resize(CAT->getZExtSize(), '\0');1470return llvm::ConstantDataArray::getString(VMContext, Str, false);1471}14721473llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {1474return Visit(E->getSubExpr(), T);1475}14761477llvm::Constant *VisitUnaryMinus(const UnaryOperator *U, QualType T) {1478if (llvm::Constant *C = Visit(U->getSubExpr(), T))1479if (auto *CI = dyn_cast<llvm::ConstantInt>(C))1480return llvm::ConstantInt::get(CGM.getLLVMContext(), -CI->getValue());1481return nullptr;1482}14831484llvm::Constant *VisitPackIndexingExpr(const PackIndexingExpr *E, QualType T) {1485return Visit(E->getSelectedExpr(), T);1486}14871488// Utility methods1489llvm::Type *ConvertType(QualType T) {1490return CGM.getTypes().ConvertType(T);1491}1492};14931494} // end anonymous namespace.14951496llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,1497AbstractState saved) {1498Abstract = saved.OldValue;14991500assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&1501"created a placeholder while doing an abstract emission?");15021503// No validation necessary for now.1504// No cleanup to do for now.1505return C;1506}15071508llvm::Constant *1509ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {1510auto state = pushAbstract();1511auto C = tryEmitPrivateForVarInit(D);1512return validateAndPopAbstract(C, state);1513}15141515llvm::Constant *1516ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {1517auto state = pushAbstract();1518auto C = tryEmitPrivate(E, destType);1519return validateAndPopAbstract(C, state);1520}15211522llvm::Constant *1523ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {1524auto state = pushAbstract();1525auto C = tryEmitPrivate(value, destType);1526return validateAndPopAbstract(C, state);1527}15281529llvm::Constant *ConstantEmitter::tryEmitConstantExpr(const ConstantExpr *CE) {1530if (!CE->hasAPValueResult())1531return nullptr;15321533QualType RetType = CE->getType();1534if (CE->isGLValue())1535RetType = CGM.getContext().getLValueReferenceType(RetType);15361537return emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), RetType);1538}15391540llvm::Constant *1541ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {1542auto state = pushAbstract();1543auto C = tryEmitPrivate(E, destType);1544C = validateAndPopAbstract(C, state);1545if (!C) {1546CGM.Error(E->getExprLoc(),1547"internal error: could not emit constant value \"abstractly\"");1548C = CGM.EmitNullConstant(destType);1549}1550return C;1551}15521553llvm::Constant *1554ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,1555QualType destType,1556bool EnablePtrAuthFunctionTypeDiscrimination) {1557auto state = pushAbstract();1558auto C =1559tryEmitPrivate(value, destType, EnablePtrAuthFunctionTypeDiscrimination);1560C = validateAndPopAbstract(C, state);1561if (!C) {1562CGM.Error(loc,1563"internal error: could not emit constant value \"abstractly\"");1564C = CGM.EmitNullConstant(destType);1565}1566return C;1567}15681569llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {1570initializeNonAbstract(D.getType().getAddressSpace());1571return markIfFailed(tryEmitPrivateForVarInit(D));1572}15731574llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,1575LangAS destAddrSpace,1576QualType destType) {1577initializeNonAbstract(destAddrSpace);1578return markIfFailed(tryEmitPrivateForMemory(E, destType));1579}15801581llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,1582LangAS destAddrSpace,1583QualType destType) {1584initializeNonAbstract(destAddrSpace);1585auto C = tryEmitPrivateForMemory(value, destType);1586assert(C && "couldn't emit constant value non-abstractly?");1587return C;1588}15891590llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {1591assert(!Abstract && "cannot get current address for abstract constant");1592159315941595// Make an obviously ill-formed global that should blow up compilation1596// if it survives.1597auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,1598llvm::GlobalValue::PrivateLinkage,1599/*init*/ nullptr,1600/*name*/ "",1601/*before*/ nullptr,1602llvm::GlobalVariable::NotThreadLocal,1603CGM.getContext().getTargetAddressSpace(DestAddressSpace));16041605PlaceholderAddresses.push_back(std::make_pair(nullptr, global));16061607return global;1608}16091610void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,1611llvm::GlobalValue *placeholder) {1612assert(!PlaceholderAddresses.empty());1613assert(PlaceholderAddresses.back().first == nullptr);1614assert(PlaceholderAddresses.back().second == placeholder);1615PlaceholderAddresses.back().first = signal;1616}16171618namespace {1619struct ReplacePlaceholders {1620CodeGenModule &CGM;16211622/// The base address of the global.1623llvm::Constant *Base;1624llvm::Type *BaseValueTy = nullptr;16251626/// The placeholder addresses that were registered during emission.1627llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;16281629/// The locations of the placeholder signals.1630llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;16311632/// The current index stack. We use a simple unsigned stack because1633/// we assume that placeholders will be relatively sparse in the1634/// initializer, but we cache the index values we find just in case.1635llvm::SmallVector<unsigned, 8> Indices;1636llvm::SmallVector<llvm::Constant*, 8> IndexValues;16371638ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,1639ArrayRef<std::pair<llvm::Constant*,1640llvm::GlobalVariable*>> addresses)1641: CGM(CGM), Base(base),1642PlaceholderAddresses(addresses.begin(), addresses.end()) {1643}16441645void replaceInInitializer(llvm::Constant *init) {1646// Remember the type of the top-most initializer.1647BaseValueTy = init->getType();16481649// Initialize the stack.1650Indices.push_back(0);1651IndexValues.push_back(nullptr);16521653// Recurse into the initializer.1654findLocations(init);16551656// Check invariants.1657assert(IndexValues.size() == Indices.size() && "mismatch");1658assert(Indices.size() == 1 && "didn't pop all indices");16591660// Do the replacement; this basically invalidates 'init'.1661assert(Locations.size() == PlaceholderAddresses.size() &&1662"missed a placeholder?");16631664// We're iterating over a hashtable, so this would be a source of1665// non-determinism in compiler output *except* that we're just1666// messing around with llvm::Constant structures, which never itself1667// does anything that should be visible in compiler output.1668for (auto &entry : Locations) {1669assert(entry.first->getName() == "" && "not a placeholder!");1670entry.first->replaceAllUsesWith(entry.second);1671entry.first->eraseFromParent();1672}1673}16741675private:1676void findLocations(llvm::Constant *init) {1677// Recurse into aggregates.1678if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {1679for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {1680Indices.push_back(i);1681IndexValues.push_back(nullptr);16821683findLocations(agg->getOperand(i));16841685IndexValues.pop_back();1686Indices.pop_back();1687}1688return;1689}16901691// Otherwise, check for registered constants.1692while (true) {1693auto it = PlaceholderAddresses.find(init);1694if (it != PlaceholderAddresses.end()) {1695setLocation(it->second);1696break;1697}16981699// Look through bitcasts or other expressions.1700if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {1701init = expr->getOperand(0);1702} else {1703break;1704}1705}1706}17071708void setLocation(llvm::GlobalVariable *placeholder) {1709assert(!Locations.contains(placeholder) &&1710"already found location for placeholder!");17111712// Lazily fill in IndexValues with the values from Indices.1713// We do this in reverse because we should always have a strict1714// prefix of indices from the start.1715assert(Indices.size() == IndexValues.size());1716for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {1717if (IndexValues[i]) {1718#ifndef NDEBUG1719for (size_t j = 0; j != i + 1; ++j) {1720assert(IndexValues[j] &&1721isa<llvm::ConstantInt>(IndexValues[j]) &&1722cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()1723== Indices[j]);1724}1725#endif1726break;1727}17281729IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);1730}17311732llvm::Constant *location = llvm::ConstantExpr::getInBoundsGetElementPtr(1733BaseValueTy, Base, IndexValues);17341735Locations.insert({placeholder, location});1736}1737};1738}17391740void ConstantEmitter::finalize(llvm::GlobalVariable *global) {1741assert(InitializedNonAbstract &&1742"finalizing emitter that was used for abstract emission?");1743assert(!Finalized && "finalizing emitter multiple times");1744assert(global->getInitializer());17451746// Note that we might also be Failed.1747Finalized = true;17481749if (!PlaceholderAddresses.empty()) {1750ReplacePlaceholders(CGM, global, PlaceholderAddresses)1751.replaceInInitializer(global->getInitializer());1752PlaceholderAddresses.clear(); // satisfy1753}1754}17551756ConstantEmitter::~ConstantEmitter() {1757assert((!InitializedNonAbstract || Finalized || Failed) &&1758"not finalized after being initialized for non-abstract emission");1759assert(PlaceholderAddresses.empty() && "unhandled placeholders");1760}17611762static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {1763if (auto AT = type->getAs<AtomicType>()) {1764return CGM.getContext().getQualifiedType(AT->getValueType(),1765type.getQualifiers());1766}1767return type;1768}17691770llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {1771// Make a quick check if variable can be default NULL initialized1772// and avoid going through rest of code which may do, for c++11,1773// initialization of memory to all NULLs.1774if (!D.hasLocalStorage()) {1775QualType Ty = CGM.getContext().getBaseElementType(D.getType());1776if (Ty->isRecordType())1777if (const CXXConstructExpr *E =1778dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {1779const CXXConstructorDecl *CD = E->getConstructor();1780if (CD->isTrivial() && CD->isDefaultConstructor())1781return CGM.EmitNullConstant(D.getType());1782}1783}1784InConstantContext = D.hasConstantInitialization();17851786QualType destType = D.getType();1787const Expr *E = D.getInit();1788assert(E && "No initializer to emit");17891790if (!destType->isReferenceType()) {1791QualType nonMemoryDestType = getNonMemoryType(CGM, destType);1792if (llvm::Constant *C = ConstExprEmitter(*this).Visit(E, nonMemoryDestType))1793return emitForMemory(C, destType);1794}17951796// Try to emit the initializer. Note that this can allow some things that1797// are not allowed by tryEmitPrivateForMemory alone.1798if (APValue *value = D.evaluateValue())1799return tryEmitPrivateForMemory(*value, destType);18001801return nullptr;1802}18031804llvm::Constant *1805ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {1806auto nonMemoryDestType = getNonMemoryType(CGM, destType);1807auto C = tryEmitAbstract(E, nonMemoryDestType);1808return (C ? emitForMemory(C, destType) : nullptr);1809}18101811llvm::Constant *1812ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,1813QualType destType) {1814auto nonMemoryDestType = getNonMemoryType(CGM, destType);1815auto C = tryEmitAbstract(value, nonMemoryDestType);1816return (C ? emitForMemory(C, destType) : nullptr);1817}18181819llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,1820QualType destType) {1821auto nonMemoryDestType = getNonMemoryType(CGM, destType);1822llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);1823return (C ? emitForMemory(C, destType) : nullptr);1824}18251826llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,1827QualType destType) {1828auto nonMemoryDestType = getNonMemoryType(CGM, destType);1829auto C = tryEmitPrivate(value, nonMemoryDestType);1830return (C ? emitForMemory(C, destType) : nullptr);1831}18321833/// Try to emit a constant signed pointer, given a raw pointer and the1834/// destination ptrauth qualifier.1835///1836/// This can fail if the qualifier needs address discrimination and the1837/// emitter is in an abstract mode.1838llvm::Constant *1839ConstantEmitter::tryEmitConstantSignedPointer(llvm::Constant *UnsignedPointer,1840PointerAuthQualifier Schema) {1841assert(Schema && "applying trivial ptrauth schema");18421843if (Schema.hasKeyNone())1844return UnsignedPointer;18451846unsigned Key = Schema.getKey();18471848// Create an address placeholder if we're using address discrimination.1849llvm::GlobalValue *StorageAddress = nullptr;1850if (Schema.isAddressDiscriminated()) {1851// We can't do this if the emitter is in an abstract state.1852if (isAbstract())1853return nullptr;18541855StorageAddress = getCurrentAddrPrivate();1856}18571858llvm::ConstantInt *Discriminator =1859llvm::ConstantInt::get(CGM.IntPtrTy, Schema.getExtraDiscriminator());18601861llvm::Constant *SignedPointer = CGM.getConstantSignedPointer(1862UnsignedPointer, Key, StorageAddress, Discriminator);18631864if (Schema.isAddressDiscriminated())1865registerCurrentAddrPrivate(SignedPointer, StorageAddress);18661867return SignedPointer;1868}18691870llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,1871llvm::Constant *C,1872QualType destType) {1873// For an _Atomic-qualified constant, we may need to add tail padding.1874if (auto AT = destType->getAs<AtomicType>()) {1875QualType destValueType = AT->getValueType();1876C = emitForMemory(CGM, C, destValueType);18771878uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);1879uint64_t outerSize = CGM.getContext().getTypeSize(destType);1880if (innerSize == outerSize)1881return C;18821883assert(innerSize < outerSize && "emitted over-large constant for atomic");1884llvm::Constant *elts[] = {1885C,1886llvm::ConstantAggregateZero::get(1887llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))1888};1889return llvm::ConstantStruct::getAnon(elts);1890}18911892// Zero-extend bool.1893if (C->getType()->isIntegerTy(1) && !destType->isBitIntType()) {1894llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);1895llvm::Constant *Res = llvm::ConstantFoldCastOperand(1896llvm::Instruction::ZExt, C, boolTy, CGM.getDataLayout());1897assert(Res && "Constant folding must succeed");1898return Res;1899}19001901if (destType->isBitIntType()) {1902ConstantAggregateBuilder Builder(CGM);1903llvm::Type *LoadStoreTy = CGM.getTypes().convertTypeForLoadStore(destType);1904// ptrtoint/inttoptr should not involve _BitInt in constant expressions, so1905// casting to ConstantInt is safe here.1906auto *CI = cast<llvm::ConstantInt>(C);1907llvm::Constant *Res = llvm::ConstantFoldCastOperand(1908destType->isSignedIntegerOrEnumerationType() ? llvm::Instruction::SExt1909: llvm::Instruction::ZExt,1910CI, LoadStoreTy, CGM.getDataLayout());1911if (CGM.getTypes().typeRequiresSplitIntoByteArray(destType, C->getType())) {1912// Long _BitInt has array of bytes as in-memory type.1913// So, split constant into individual bytes.1914llvm::Type *DesiredTy = CGM.getTypes().ConvertTypeForMem(destType);1915llvm::APInt Value = cast<llvm::ConstantInt>(Res)->getValue();1916Builder.addBits(Value, /*OffsetInBits=*/0, /*AllowOverwrite=*/false);1917return Builder.build(DesiredTy, /*AllowOversized*/ false);1918}1919return Res;1920}19211922return C;1923}19241925llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,1926QualType destType) {1927assert(!destType->isVoidType() && "can't emit a void constant");19281929if (!destType->isReferenceType())1930if (llvm::Constant *C = ConstExprEmitter(*this).Visit(E, destType))1931return C;19321933Expr::EvalResult Result;19341935bool Success = false;19361937if (destType->isReferenceType())1938Success = E->EvaluateAsLValue(Result, CGM.getContext());1939else1940Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);19411942if (Success && !Result.HasSideEffects)1943return tryEmitPrivate(Result.Val, destType);19441945return nullptr;1946}19471948llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {1949return getTargetCodeGenInfo().getNullPointer(*this, T, QT);1950}19511952namespace {1953/// A struct which can be used to peephole certain kinds of finalization1954/// that normally happen during l-value emission.1955struct ConstantLValue {1956llvm::Constant *Value;1957bool HasOffsetApplied;19581959/*implicit*/ ConstantLValue(llvm::Constant *value,1960bool hasOffsetApplied = false)1961: Value(value), HasOffsetApplied(hasOffsetApplied) {}19621963/*implicit*/ ConstantLValue(ConstantAddress address)1964: ConstantLValue(address.getPointer()) {}1965};19661967/// A helper class for emitting constant l-values.1968class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,1969ConstantLValue> {1970CodeGenModule &CGM;1971ConstantEmitter &Emitter;1972const APValue &Value;1973QualType DestType;1974bool EnablePtrAuthFunctionTypeDiscrimination;19751976// Befriend StmtVisitorBase so that we don't have to expose Visit*.1977friend StmtVisitorBase;19781979public:1980ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,1981QualType destType,1982bool EnablePtrAuthFunctionTypeDiscrimination = true)1983: CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType),1984EnablePtrAuthFunctionTypeDiscrimination(1985EnablePtrAuthFunctionTypeDiscrimination) {}19861987llvm::Constant *tryEmit();19881989private:1990llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);1991ConstantLValue tryEmitBase(const APValue::LValueBase &base);19921993ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }1994ConstantLValue VisitConstantExpr(const ConstantExpr *E);1995ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);1996ConstantLValue VisitStringLiteral(const StringLiteral *E);1997ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);1998ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);1999ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);2000ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);2001ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);2002ConstantLValue VisitCallExpr(const CallExpr *E);2003ConstantLValue VisitBlockExpr(const BlockExpr *E);2004ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);2005ConstantLValue VisitMaterializeTemporaryExpr(2006const MaterializeTemporaryExpr *E);20072008ConstantLValue emitPointerAuthSignConstant(const CallExpr *E);2009llvm::Constant *emitPointerAuthPointer(const Expr *E);2010unsigned emitPointerAuthKey(const Expr *E);2011std::pair<llvm::Constant *, llvm::ConstantInt *>2012emitPointerAuthDiscriminator(const Expr *E);20132014bool hasNonZeroOffset() const {2015return !Value.getLValueOffset().isZero();2016}20172018/// Return the value offset.2019llvm::Constant *getOffset() {2020return llvm::ConstantInt::get(CGM.Int64Ty,2021Value.getLValueOffset().getQuantity());2022}20232024/// Apply the value offset to the given constant.2025llvm::Constant *applyOffset(llvm::Constant *C) {2026if (!hasNonZeroOffset())2027return C;20282029return llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());2030}2031};20322033}20342035llvm::Constant *ConstantLValueEmitter::tryEmit() {2036const APValue::LValueBase &base = Value.getLValueBase();20372038// The destination type should be a pointer or reference2039// type, but it might also be a cast thereof.2040//2041// FIXME: the chain of casts required should be reflected in the APValue.2042// We need this in order to correctly handle things like a ptrtoint of a2043// non-zero null pointer and addrspace casts that aren't trivially2044// represented in LLVM IR.2045auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);2046assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));20472048// If there's no base at all, this is a null or absolute pointer,2049// possibly cast back to an integer type.2050if (!base) {2051return tryEmitAbsolute(destTy);2052}20532054// Otherwise, try to emit the base.2055ConstantLValue result = tryEmitBase(base);20562057// If that failed, we're done.2058llvm::Constant *value = result.Value;2059if (!value) return nullptr;20602061// Apply the offset if necessary and not already done.2062if (!result.HasOffsetApplied) {2063value = applyOffset(value);2064}20652066// Convert to the appropriate type; this could be an lvalue for2067// an integer. FIXME: performAddrSpaceCast2068if (isa<llvm::PointerType>(destTy))2069return llvm::ConstantExpr::getPointerCast(value, destTy);20702071return llvm::ConstantExpr::getPtrToInt(value, destTy);2072}20732074/// Try to emit an absolute l-value, such as a null pointer or an integer2075/// bitcast to pointer type.2076llvm::Constant *2077ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {2078// If we're producing a pointer, this is easy.2079auto destPtrTy = cast<llvm::PointerType>(destTy);2080if (Value.isNullPointer()) {2081// FIXME: integer offsets from non-zero null pointers.2082return CGM.getNullPointer(destPtrTy, DestType);2083}20842085// Convert the integer to a pointer-sized integer before converting it2086// to a pointer.2087// FIXME: signedness depends on the original integer type.2088auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);2089llvm::Constant *C;2090C = llvm::ConstantFoldIntegerCast(getOffset(), intptrTy, /*isSigned*/ false,2091CGM.getDataLayout());2092assert(C && "Must have folded, as Offset is a ConstantInt");2093C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);2094return C;2095}20962097ConstantLValue2098ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {2099// Handle values.2100if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {2101// The constant always points to the canonical declaration. We want to look2102// at properties of the most recent declaration at the point of emission.2103D = cast<ValueDecl>(D->getMostRecentDecl());21042105if (D->hasAttr<WeakRefAttr>())2106return CGM.GetWeakRefReference(D).getPointer();21072108auto PtrAuthSign = [&](llvm::Constant *C) {2109CGPointerAuthInfo AuthInfo;21102111if (EnablePtrAuthFunctionTypeDiscrimination)2112AuthInfo = CGM.getFunctionPointerAuthInfo(DestType);21132114if (AuthInfo) {2115if (hasNonZeroOffset())2116return ConstantLValue(nullptr);21172118C = applyOffset(C);2119C = CGM.getConstantSignedPointer(2120C, AuthInfo.getKey(), nullptr,2121cast_or_null<llvm::ConstantInt>(AuthInfo.getDiscriminator()));2122return ConstantLValue(C, /*applied offset*/ true);2123}21242125return ConstantLValue(C);2126};21272128if (const auto *FD = dyn_cast<FunctionDecl>(D))2129return PtrAuthSign(CGM.getRawFunctionPointer(FD));21302131if (const auto *VD = dyn_cast<VarDecl>(D)) {2132// We can never refer to a variable with local storage.2133if (!VD->hasLocalStorage()) {2134if (VD->isFileVarDecl() || VD->hasExternalStorage())2135return CGM.GetAddrOfGlobalVar(VD);21362137if (VD->isLocalVarDecl()) {2138return CGM.getOrCreateStaticVarDecl(2139*VD, CGM.getLLVMLinkageVarDefinition(VD));2140}2141}2142}21432144if (const auto *GD = dyn_cast<MSGuidDecl>(D))2145return CGM.GetAddrOfMSGuidDecl(GD);21462147if (const auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D))2148return CGM.GetAddrOfUnnamedGlobalConstantDecl(GCD);21492150if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D))2151return CGM.GetAddrOfTemplateParamObject(TPO);21522153return nullptr;2154}21552156// Handle typeid(T).2157if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>())2158return CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));21592160// Otherwise, it must be an expression.2161return Visit(base.get<const Expr*>());2162}21632164ConstantLValue2165ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {2166if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(E))2167return Result;2168return Visit(E->getSubExpr());2169}21702171ConstantLValue2172ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {2173ConstantEmitter CompoundLiteralEmitter(CGM, Emitter.CGF);2174CompoundLiteralEmitter.setInConstantContext(Emitter.isInConstantContext());2175return tryEmitGlobalCompoundLiteral(CompoundLiteralEmitter, E);2176}21772178ConstantLValue2179ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {2180return CGM.GetAddrOfConstantStringFromLiteral(E);2181}21822183ConstantLValue2184ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {2185return CGM.GetAddrOfConstantStringFromObjCEncode(E);2186}21872188static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,2189QualType T,2190CodeGenModule &CGM) {2191auto C = CGM.getObjCRuntime().GenerateConstantString(S);2192return C.withElementType(CGM.getTypes().ConvertTypeForMem(T));2193}21942195ConstantLValue2196ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {2197return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);2198}21992200ConstantLValue2201ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {2202assert(E->isExpressibleAsConstantInitializer() &&2203"this boxed expression can't be emitted as a compile-time constant");2204const auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());2205return emitConstantObjCStringLiteral(SL, E->getType(), CGM);2206}22072208ConstantLValue2209ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {2210return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());2211}22122213ConstantLValue2214ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {2215assert(Emitter.CGF && "Invalid address of label expression outside function");2216llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());2217return Ptr;2218}22192220ConstantLValue2221ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {2222unsigned builtin = E->getBuiltinCallee();2223if (builtin == Builtin::BI__builtin_function_start)2224return CGM.GetFunctionStart(2225E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext()));22262227if (builtin == Builtin::BI__builtin_ptrauth_sign_constant)2228return emitPointerAuthSignConstant(E);22292230if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&2231builtin != Builtin::BI__builtin___NSStringMakeConstantString)2232return nullptr;22332234const auto *Literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());2235if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {2236return CGM.getObjCRuntime().GenerateConstantString(Literal);2237} else {2238// FIXME: need to deal with UCN conversion issues.2239return CGM.GetAddrOfConstantCFString(Literal);2240}2241}22422243ConstantLValue2244ConstantLValueEmitter::emitPointerAuthSignConstant(const CallExpr *E) {2245llvm::Constant *UnsignedPointer = emitPointerAuthPointer(E->getArg(0));2246unsigned Key = emitPointerAuthKey(E->getArg(1));2247auto [StorageAddress, OtherDiscriminator] =2248emitPointerAuthDiscriminator(E->getArg(2));22492250llvm::Constant *SignedPointer = CGM.getConstantSignedPointer(2251UnsignedPointer, Key, StorageAddress, OtherDiscriminator);2252return SignedPointer;2253}22542255llvm::Constant *ConstantLValueEmitter::emitPointerAuthPointer(const Expr *E) {2256Expr::EvalResult Result;2257bool Succeeded = E->EvaluateAsRValue(Result, CGM.getContext());2258assert(Succeeded);2259(void)Succeeded;22602261// The assertions here are all checked by Sema.2262assert(Result.Val.isLValue());2263if (isa<FunctionDecl>(Result.Val.getLValueBase().get<const ValueDecl *>()))2264assert(Result.Val.getLValueOffset().isZero());2265return ConstantEmitter(CGM, Emitter.CGF)2266.emitAbstract(E->getExprLoc(), Result.Val, E->getType(), false);2267}22682269unsigned ConstantLValueEmitter::emitPointerAuthKey(const Expr *E) {2270return E->EvaluateKnownConstInt(CGM.getContext()).getZExtValue();2271}22722273std::pair<llvm::Constant *, llvm::ConstantInt *>2274ConstantLValueEmitter::emitPointerAuthDiscriminator(const Expr *E) {2275E = E->IgnoreParens();22762277if (const auto *Call = dyn_cast<CallExpr>(E)) {2278if (Call->getBuiltinCallee() ==2279Builtin::BI__builtin_ptrauth_blend_discriminator) {2280llvm::Constant *Pointer = ConstantEmitter(CGM).emitAbstract(2281Call->getArg(0), Call->getArg(0)->getType());2282auto *Extra = cast<llvm::ConstantInt>(ConstantEmitter(CGM).emitAbstract(2283Call->getArg(1), Call->getArg(1)->getType()));2284return {Pointer, Extra};2285}2286}22872288llvm::Constant *Result = ConstantEmitter(CGM).emitAbstract(E, E->getType());2289if (Result->getType()->isPointerTy())2290return {Result, nullptr};2291return {nullptr, cast<llvm::ConstantInt>(Result)};2292}22932294ConstantLValue2295ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {2296StringRef functionName;2297if (auto CGF = Emitter.CGF)2298functionName = CGF->CurFn->getName();2299else2300functionName = "global";23012302return CGM.GetAddrOfGlobalBlock(E, functionName);2303}23042305ConstantLValue2306ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {2307QualType T;2308if (E->isTypeOperand())2309T = E->getTypeOperand(CGM.getContext());2310else2311T = E->getExprOperand()->getType();2312return CGM.GetAddrOfRTTIDescriptor(T);2313}23142315ConstantLValue2316ConstantLValueEmitter::VisitMaterializeTemporaryExpr(2317const MaterializeTemporaryExpr *E) {2318assert(E->getStorageDuration() == SD_Static);2319const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();2320return CGM.GetAddrOfGlobalTemporary(E, Inner);2321}23222323llvm::Constant *2324ConstantEmitter::tryEmitPrivate(const APValue &Value, QualType DestType,2325bool EnablePtrAuthFunctionTypeDiscrimination) {2326switch (Value.getKind()) {2327case APValue::None:2328case APValue::Indeterminate:2329// Out-of-lifetime and indeterminate values can be modeled as 'undef'.2330return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));2331case APValue::LValue:2332return ConstantLValueEmitter(*this, Value, DestType,2333EnablePtrAuthFunctionTypeDiscrimination)2334.tryEmit();2335case APValue::Int:2336return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());2337case APValue::FixedPoint:2338return llvm::ConstantInt::get(CGM.getLLVMContext(),2339Value.getFixedPoint().getValue());2340case APValue::ComplexInt: {2341llvm::Constant *Complex[2];23422343Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),2344Value.getComplexIntReal());2345Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),2346Value.getComplexIntImag());23472348// FIXME: the target may want to specify that this is packed.2349llvm::StructType *STy =2350llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());2351return llvm::ConstantStruct::get(STy, Complex);2352}2353case APValue::Float: {2354const llvm::APFloat &Init = Value.getFloat();2355if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&2356!CGM.getContext().getLangOpts().NativeHalfType &&2357CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())2358return llvm::ConstantInt::get(CGM.getLLVMContext(),2359Init.bitcastToAPInt());2360else2361return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);2362}2363case APValue::ComplexFloat: {2364llvm::Constant *Complex[2];23652366Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),2367Value.getComplexFloatReal());2368Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),2369Value.getComplexFloatImag());23702371// FIXME: the target may want to specify that this is packed.2372llvm::StructType *STy =2373llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());2374return llvm::ConstantStruct::get(STy, Complex);2375}2376case APValue::Vector: {2377unsigned NumElts = Value.getVectorLength();2378SmallVector<llvm::Constant *, 4> Inits(NumElts);23792380for (unsigned I = 0; I != NumElts; ++I) {2381const APValue &Elt = Value.getVectorElt(I);2382if (Elt.isInt())2383Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());2384else if (Elt.isFloat())2385Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());2386else if (Elt.isIndeterminate())2387Inits[I] = llvm::UndefValue::get(CGM.getTypes().ConvertType(2388DestType->castAs<VectorType>()->getElementType()));2389else2390llvm_unreachable("unsupported vector element type");2391}2392return llvm::ConstantVector::get(Inits);2393}2394case APValue::AddrLabelDiff: {2395const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();2396const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();2397llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());2398llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());2399if (!LHS || !RHS) return nullptr;24002401// Compute difference2402llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);2403LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);2404RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);2405llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);24062407// LLVM is a bit sensitive about the exact format of the2408// address-of-label difference; make sure to truncate after2409// the subtraction.2410return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);2411}2412case APValue::Struct:2413case APValue::Union:2414return ConstStructBuilder::BuildStruct(*this, Value, DestType);2415case APValue::Array: {2416const ArrayType *ArrayTy = CGM.getContext().getAsArrayType(DestType);2417unsigned NumElements = Value.getArraySize();2418unsigned NumInitElts = Value.getArrayInitializedElts();24192420// Emit array filler, if there is one.2421llvm::Constant *Filler = nullptr;2422if (Value.hasArrayFiller()) {2423Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),2424ArrayTy->getElementType());2425if (!Filler)2426return nullptr;2427}24282429// Emit initializer elements.2430SmallVector<llvm::Constant*, 16> Elts;2431if (Filler && Filler->isNullValue())2432Elts.reserve(NumInitElts + 1);2433else2434Elts.reserve(NumElements);24352436llvm::Type *CommonElementType = nullptr;2437for (unsigned I = 0; I < NumInitElts; ++I) {2438llvm::Constant *C = tryEmitPrivateForMemory(2439Value.getArrayInitializedElt(I), ArrayTy->getElementType());2440if (!C) return nullptr;24412442if (I == 0)2443CommonElementType = C->getType();2444else if (C->getType() != CommonElementType)2445CommonElementType = nullptr;2446Elts.push_back(C);2447}24482449llvm::ArrayType *Desired =2450cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));24512452// Fix the type of incomplete arrays if the initializer isn't empty.2453if (DestType->isIncompleteArrayType() && !Elts.empty())2454Desired = llvm::ArrayType::get(Desired->getElementType(), Elts.size());24552456return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,2457Filler);2458}2459case APValue::MemberPointer:2460return CGM.getCXXABI().EmitMemberPointer(Value, DestType);2461}2462llvm_unreachable("Unknown APValue kind");2463}24642465llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(2466const CompoundLiteralExpr *E) {2467return EmittedCompoundLiterals.lookup(E);2468}24692470void CodeGenModule::setAddrOfConstantCompoundLiteral(2471const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {2472bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;2473(void)Ok;2474assert(Ok && "CLE has already been emitted!");2475}24762477ConstantAddress2478CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {2479assert(E->isFileScope() && "not a file-scope compound literal expr");2480ConstantEmitter emitter(*this);2481return tryEmitGlobalCompoundLiteral(emitter, E);2482}24832484llvm::Constant *2485CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {2486// Member pointer constants always have a very particular form.2487const MemberPointerType *type = cast<MemberPointerType>(uo->getType());2488const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();24892490// A member function pointer.2491if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))2492return getCXXABI().EmitMemberFunctionPointer(method);24932494// Otherwise, a member data pointer.2495uint64_t fieldOffset = getContext().getFieldOffset(decl);2496CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);2497return getCXXABI().EmitMemberDataPointer(type, chars);2498}24992500static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,2501llvm::Type *baseType,2502const CXXRecordDecl *base);25032504static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,2505const RecordDecl *record,2506bool asCompleteObject) {2507const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);2508llvm::StructType *structure =2509(asCompleteObject ? layout.getLLVMType()2510: layout.getBaseSubobjectLLVMType());25112512unsigned numElements = structure->getNumElements();2513std::vector<llvm::Constant *> elements(numElements);25142515auto CXXR = dyn_cast<CXXRecordDecl>(record);2516// Fill in all the bases.2517if (CXXR) {2518for (const auto &I : CXXR->bases()) {2519if (I.isVirtual()) {2520// Ignore virtual bases; if we're laying out for a complete2521// object, we'll lay these out later.2522continue;2523}25242525const CXXRecordDecl *base =2526cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());25272528// Ignore empty bases.2529if (isEmptyRecordForLayout(CGM.getContext(), I.getType()) ||2530CGM.getContext()2531.getASTRecordLayout(base)2532.getNonVirtualSize()2533.isZero())2534continue;25352536unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);2537llvm::Type *baseType = structure->getElementType(fieldIndex);2538elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);2539}2540}25412542// Fill in all the fields.2543for (const auto *Field : record->fields()) {2544// Fill in non-bitfields. (Bitfields always use a zero pattern, which we2545// will fill in later.)2546if (!Field->isBitField() &&2547!isEmptyFieldForLayout(CGM.getContext(), Field)) {2548unsigned fieldIndex = layout.getLLVMFieldNo(Field);2549elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());2550}25512552// For unions, stop after the first named field.2553if (record->isUnion()) {2554if (Field->getIdentifier())2555break;2556if (const auto *FieldRD = Field->getType()->getAsRecordDecl())2557if (FieldRD->findFirstNamedDataMember())2558break;2559}2560}25612562// Fill in the virtual bases, if we're working with the complete object.2563if (CXXR && asCompleteObject) {2564for (const auto &I : CXXR->vbases()) {2565const CXXRecordDecl *base =2566cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());25672568// Ignore empty bases.2569if (isEmptyRecordForLayout(CGM.getContext(), I.getType()))2570continue;25712572unsigned fieldIndex = layout.getVirtualBaseIndex(base);25732574// We might have already laid this field out.2575if (elements[fieldIndex]) continue;25762577llvm::Type *baseType = structure->getElementType(fieldIndex);2578elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);2579}2580}25812582// Now go through all other fields and zero them out.2583for (unsigned i = 0; i != numElements; ++i) {2584if (!elements[i])2585elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));2586}25872588return llvm::ConstantStruct::get(structure, elements);2589}25902591/// Emit the null constant for a base subobject.2592static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,2593llvm::Type *baseType,2594const CXXRecordDecl *base) {2595const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);25962597// Just zero out bases that don't have any pointer to data members.2598if (baseLayout.isZeroInitializableAsBase())2599return llvm::Constant::getNullValue(baseType);26002601// Otherwise, we can just use its null constant.2602return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);2603}26042605llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,2606QualType T) {2607return emitForMemory(CGM, CGM.EmitNullConstant(T), T);2608}26092610llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {2611if (T->getAs<PointerType>())2612return getNullPointer(2613cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);26142615if (getTypes().isZeroInitializable(T))2616return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));26172618if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {2619llvm::ArrayType *ATy =2620cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));26212622QualType ElementTy = CAT->getElementType();26232624llvm::Constant *Element =2625ConstantEmitter::emitNullForMemory(*this, ElementTy);2626unsigned NumElements = CAT->getZExtSize();2627SmallVector<llvm::Constant *, 8> Array(NumElements, Element);2628return llvm::ConstantArray::get(ATy, Array);2629}26302631if (const RecordType *RT = T->getAs<RecordType>())2632return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);26332634assert(T->isMemberDataPointerType() &&2635"Should only see pointers to data members here!");26362637return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());2638}26392640llvm::Constant *2641CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {2642return ::EmitNullConstant(*this, Record, false);2643}264426452646