10b57cec5SDimitry Andric //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This contains code to emit Constant Expr nodes as LLVM code.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CGCXXABI.h"
140b57cec5SDimitry Andric #include "CGObjCRuntime.h"
150b57cec5SDimitry Andric #include "CGRecordLayout.h"
16480093f4SDimitry Andric #include "CodeGenFunction.h"
170b57cec5SDimitry Andric #include "CodeGenModule.h"
180b57cec5SDimitry Andric #include "ConstantEmitter.h"
190b57cec5SDimitry Andric #include "TargetInfo.h"
200b57cec5SDimitry Andric #include "clang/AST/APValue.h"
210b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
22480093f4SDimitry Andric #include "clang/AST/Attr.h"
230b57cec5SDimitry Andric #include "clang/AST/RecordLayout.h"
240b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
250b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
260b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
27480093f4SDimitry Andric #include "llvm/ADT/Sequence.h"
280b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
290b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
300b57cec5SDimitry Andric #include "llvm/IR/Function.h"
310b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
32bdd1243dSDimitry Andric #include <optional>
330b57cec5SDimitry Andric using namespace clang;
340b57cec5SDimitry Andric using namespace CodeGen;
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
370b57cec5SDimitry Andric //                            ConstantAggregateBuilder
380b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric namespace {
410b57cec5SDimitry Andric class ConstExprEmitter;
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric struct ConstantAggregateBuilderUtils {
440b57cec5SDimitry Andric   CodeGenModule &CGM;
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric   ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric   CharUnits getAlignment(const llvm::Constant *C) const {
490b57cec5SDimitry Andric     return CharUnits::fromQuantity(
50bdd1243dSDimitry Andric         CGM.getDataLayout().getABITypeAlign(C->getType()));
510b57cec5SDimitry Andric   }
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric   CharUnits getSize(llvm::Type *Ty) const {
540b57cec5SDimitry Andric     return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));
550b57cec5SDimitry Andric   }
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric   CharUnits getSize(const llvm::Constant *C) const {
580b57cec5SDimitry Andric     return getSize(C->getType());
590b57cec5SDimitry Andric   }
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric   llvm::Constant *getPadding(CharUnits PadSize) const {
62e8d8bef9SDimitry Andric     llvm::Type *Ty = CGM.CharTy;
630b57cec5SDimitry Andric     if (PadSize > CharUnits::One())
640b57cec5SDimitry Andric       Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
650b57cec5SDimitry Andric     return llvm::UndefValue::get(Ty);
660b57cec5SDimitry Andric   }
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric   llvm::Constant *getZeroes(CharUnits ZeroSize) const {
69e8d8bef9SDimitry Andric     llvm::Type *Ty = llvm::ArrayType::get(CGM.CharTy, ZeroSize.getQuantity());
700b57cec5SDimitry Andric     return llvm::ConstantAggregateZero::get(Ty);
710b57cec5SDimitry Andric   }
720b57cec5SDimitry Andric };
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric /// Incremental builder for an llvm::Constant* holding a struct or array
750b57cec5SDimitry Andric /// constant.
760b57cec5SDimitry Andric class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
770b57cec5SDimitry Andric   /// The elements of the constant. These two arrays must have the same size;
780b57cec5SDimitry Andric   /// Offsets[i] describes the offset of Elems[i] within the constant. The
790b57cec5SDimitry Andric   /// elements are kept in increasing offset order, and we ensure that there
800b57cec5SDimitry Andric   /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
810b57cec5SDimitry Andric   ///
820b57cec5SDimitry Andric   /// This may contain explicit padding elements (in order to create a
830b57cec5SDimitry Andric   /// natural layout), but need not. Gaps between elements are implicitly
840b57cec5SDimitry Andric   /// considered to be filled with undef.
850b57cec5SDimitry Andric   llvm::SmallVector<llvm::Constant*, 32> Elems;
860b57cec5SDimitry Andric   llvm::SmallVector<CharUnits, 32> Offsets;
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric   /// The size of the constant (the maximum end offset of any added element).
890b57cec5SDimitry Andric   /// May be larger than the end of Elems.back() if we split the last element
900b57cec5SDimitry Andric   /// and removed some trailing undefs.
910b57cec5SDimitry Andric   CharUnits Size = CharUnits::Zero();
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric   /// This is true only if laying out Elems in order as the elements of a
940b57cec5SDimitry Andric   /// non-packed LLVM struct will give the correct layout.
950b57cec5SDimitry Andric   bool NaturalLayout = true;
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric   bool split(size_t Index, CharUnits Hint);
98bdd1243dSDimitry Andric   std::optional<size_t> splitAt(CharUnits Pos);
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric   static llvm::Constant *buildFrom(CodeGenModule &CGM,
1010b57cec5SDimitry Andric                                    ArrayRef<llvm::Constant *> Elems,
1020b57cec5SDimitry Andric                                    ArrayRef<CharUnits> Offsets,
1030b57cec5SDimitry Andric                                    CharUnits StartOffset, CharUnits Size,
1040b57cec5SDimitry Andric                                    bool NaturalLayout, llvm::Type *DesiredTy,
1050b57cec5SDimitry Andric                                    bool AllowOversized);
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric public:
1080b57cec5SDimitry Andric   ConstantAggregateBuilder(CodeGenModule &CGM)
1090b57cec5SDimitry Andric       : ConstantAggregateBuilderUtils(CGM) {}
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric   /// Update or overwrite the value starting at \p Offset with \c C.
1120b57cec5SDimitry Andric   ///
1130b57cec5SDimitry Andric   /// \param AllowOverwrite If \c true, this constant might overwrite (part of)
1140b57cec5SDimitry Andric   ///        a constant that has already been added. This flag is only used to
1150b57cec5SDimitry Andric   ///        detect bugs.
1160b57cec5SDimitry Andric   bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
1190b57cec5SDimitry Andric   bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   /// Attempt to condense the value starting at \p Offset to a constant of type
1220b57cec5SDimitry Andric   /// \p DesiredTy.
1230b57cec5SDimitry Andric   void condense(CharUnits Offset, llvm::Type *DesiredTy);
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   /// Produce a constant representing the entire accumulated value, ideally of
1260b57cec5SDimitry Andric   /// the specified type. If \p AllowOversized, the constant might be larger
1270b57cec5SDimitry Andric   /// than implied by \p DesiredTy (eg, if there is a flexible array member).
1280b57cec5SDimitry Andric   /// Otherwise, the constant will be of exactly the same size as \p DesiredTy
1290b57cec5SDimitry Andric   /// even if we can't represent it as that type.
1300b57cec5SDimitry Andric   llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
1310b57cec5SDimitry Andric     return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,
1320b57cec5SDimitry Andric                      NaturalLayout, DesiredTy, AllowOversized);
1330b57cec5SDimitry Andric   }
1340b57cec5SDimitry Andric };
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric template<typename Container, typename Range = std::initializer_list<
1370b57cec5SDimitry Andric                                  typename Container::value_type>>
1380b57cec5SDimitry Andric static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
1390b57cec5SDimitry Andric   assert(BeginOff <= EndOff && "invalid replacement range");
1400b57cec5SDimitry Andric   llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
1410b57cec5SDimitry Andric }
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
1440b57cec5SDimitry Andric                           bool AllowOverwrite) {
1450b57cec5SDimitry Andric   // Common case: appending to a layout.
1460b57cec5SDimitry Andric   if (Offset >= Size) {
1470b57cec5SDimitry Andric     CharUnits Align = getAlignment(C);
1480b57cec5SDimitry Andric     CharUnits AlignedSize = Size.alignTo(Align);
1490b57cec5SDimitry Andric     if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)
1500b57cec5SDimitry Andric       NaturalLayout = false;
1510b57cec5SDimitry Andric     else if (AlignedSize < Offset) {
1520b57cec5SDimitry Andric       Elems.push_back(getPadding(Offset - Size));
1530b57cec5SDimitry Andric       Offsets.push_back(Size);
1540b57cec5SDimitry Andric     }
1550b57cec5SDimitry Andric     Elems.push_back(C);
1560b57cec5SDimitry Andric     Offsets.push_back(Offset);
1570b57cec5SDimitry Andric     Size = Offset + getSize(C);
1580b57cec5SDimitry Andric     return true;
1590b57cec5SDimitry Andric   }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   // Uncommon case: constant overlaps what we've already created.
162bdd1243dSDimitry Andric   std::optional<size_t> FirstElemToReplace = splitAt(Offset);
1630b57cec5SDimitry Andric   if (!FirstElemToReplace)
1640b57cec5SDimitry Andric     return false;
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   CharUnits CSize = getSize(C);
167bdd1243dSDimitry Andric   std::optional<size_t> LastElemToReplace = splitAt(Offset + CSize);
1680b57cec5SDimitry Andric   if (!LastElemToReplace)
1690b57cec5SDimitry Andric     return false;
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
1720b57cec5SDimitry Andric          "unexpectedly overwriting field");
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
1750b57cec5SDimitry Andric   replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
1760b57cec5SDimitry Andric   Size = std::max(Size, Offset + CSize);
1770b57cec5SDimitry Andric   NaturalLayout = false;
1780b57cec5SDimitry Andric   return true;
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
1820b57cec5SDimitry Andric                               bool AllowOverwrite) {
1830b57cec5SDimitry Andric   const ASTContext &Context = CGM.getContext();
1840b57cec5SDimitry Andric   const uint64_t CharWidth = CGM.getContext().getCharWidth();
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   // Offset of where we want the first bit to go within the bits of the
1870b57cec5SDimitry Andric   // current char.
1880b57cec5SDimitry Andric   unsigned OffsetWithinChar = OffsetInBits % CharWidth;
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   // We split bit-fields up into individual bytes. Walk over the bytes and
1910b57cec5SDimitry Andric   // update them.
1920b57cec5SDimitry Andric   for (CharUnits OffsetInChars =
1930b57cec5SDimitry Andric            Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar);
1940b57cec5SDimitry Andric        /**/; ++OffsetInChars) {
1950b57cec5SDimitry Andric     // Number of bits we want to fill in this char.
1960b57cec5SDimitry Andric     unsigned WantedBits =
1970b57cec5SDimitry Andric         std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric     // Get a char containing the bits we want in the right places. The other
2000b57cec5SDimitry Andric     // bits have unspecified values.
2010b57cec5SDimitry Andric     llvm::APInt BitsThisChar = Bits;
2020b57cec5SDimitry Andric     if (BitsThisChar.getBitWidth() < CharWidth)
2030b57cec5SDimitry Andric       BitsThisChar = BitsThisChar.zext(CharWidth);
2040b57cec5SDimitry Andric     if (CGM.getDataLayout().isBigEndian()) {
2050b57cec5SDimitry Andric       // Figure out how much to shift by. We may need to left-shift if we have
2060b57cec5SDimitry Andric       // less than one byte of Bits left.
2070b57cec5SDimitry Andric       int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
2080b57cec5SDimitry Andric       if (Shift > 0)
2090b57cec5SDimitry Andric         BitsThisChar.lshrInPlace(Shift);
2100b57cec5SDimitry Andric       else if (Shift < 0)
2110b57cec5SDimitry Andric         BitsThisChar = BitsThisChar.shl(-Shift);
2120b57cec5SDimitry Andric     } else {
2130b57cec5SDimitry Andric       BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
2140b57cec5SDimitry Andric     }
2150b57cec5SDimitry Andric     if (BitsThisChar.getBitWidth() > CharWidth)
2160b57cec5SDimitry Andric       BitsThisChar = BitsThisChar.trunc(CharWidth);
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric     if (WantedBits == CharWidth) {
2190b57cec5SDimitry Andric       // Got a full byte: just add it directly.
2200b57cec5SDimitry Andric       add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
2210b57cec5SDimitry Andric           OffsetInChars, AllowOverwrite);
2220b57cec5SDimitry Andric     } else {
2230b57cec5SDimitry Andric       // Partial byte: update the existing integer if there is one. If we
2240b57cec5SDimitry Andric       // can't split out a 1-CharUnit range to update, then we can't add
2250b57cec5SDimitry Andric       // these bits and fail the entire constant emission.
226bdd1243dSDimitry Andric       std::optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);
2270b57cec5SDimitry Andric       if (!FirstElemToUpdate)
2280b57cec5SDimitry Andric         return false;
229bdd1243dSDimitry Andric       std::optional<size_t> LastElemToUpdate =
2300b57cec5SDimitry Andric           splitAt(OffsetInChars + CharUnits::One());
2310b57cec5SDimitry Andric       if (!LastElemToUpdate)
2320b57cec5SDimitry Andric         return false;
2330b57cec5SDimitry Andric       assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
2340b57cec5SDimitry Andric              "should have at most one element covering one byte");
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric       // Figure out which bits we want and discard the rest.
2370b57cec5SDimitry Andric       llvm::APInt UpdateMask(CharWidth, 0);
2380b57cec5SDimitry Andric       if (CGM.getDataLayout().isBigEndian())
2390b57cec5SDimitry Andric         UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
2400b57cec5SDimitry Andric                            CharWidth - OffsetWithinChar);
2410b57cec5SDimitry Andric       else
2420b57cec5SDimitry Andric         UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
2430b57cec5SDimitry Andric       BitsThisChar &= UpdateMask;
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric       if (*FirstElemToUpdate == *LastElemToUpdate ||
2460b57cec5SDimitry Andric           Elems[*FirstElemToUpdate]->isNullValue() ||
2470b57cec5SDimitry Andric           isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {
2480b57cec5SDimitry Andric         // All existing bits are either zero or undef.
2490b57cec5SDimitry Andric         add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
2500b57cec5SDimitry Andric             OffsetInChars, /*AllowOverwrite*/ true);
2510b57cec5SDimitry Andric       } else {
2520b57cec5SDimitry Andric         llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
2530b57cec5SDimitry Andric         // In order to perform a partial update, we need the existing bitwise
2540b57cec5SDimitry Andric         // value, which we can only extract for a constant int.
2550b57cec5SDimitry Andric         auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
2560b57cec5SDimitry Andric         if (!CI)
2570b57cec5SDimitry Andric           return false;
2580b57cec5SDimitry Andric         // Because this is a 1-CharUnit range, the constant occupying it must
2590b57cec5SDimitry Andric         // be exactly one CharUnit wide.
2600b57cec5SDimitry Andric         assert(CI->getBitWidth() == CharWidth && "splitAt failed");
2610b57cec5SDimitry Andric         assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
2620b57cec5SDimitry Andric                "unexpectedly overwriting bitfield");
2630b57cec5SDimitry Andric         BitsThisChar |= (CI->getValue() & ~UpdateMask);
2640b57cec5SDimitry Andric         ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);
2650b57cec5SDimitry Andric       }
2660b57cec5SDimitry Andric     }
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric     // Stop if we've added all the bits.
2690b57cec5SDimitry Andric     if (WantedBits == Bits.getBitWidth())
2700b57cec5SDimitry Andric       break;
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric     // Remove the consumed bits from Bits.
2730b57cec5SDimitry Andric     if (!CGM.getDataLayout().isBigEndian())
2740b57cec5SDimitry Andric       Bits.lshrInPlace(WantedBits);
2750b57cec5SDimitry Andric     Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric     // The remanining bits go at the start of the following bytes.
2780b57cec5SDimitry Andric     OffsetWithinChar = 0;
2790b57cec5SDimitry Andric   }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   return true;
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric /// Returns a position within Elems and Offsets such that all elements
2850b57cec5SDimitry Andric /// before the returned index end before Pos and all elements at or after
2860b57cec5SDimitry Andric /// the returned index begin at or after Pos. Splits elements as necessary
287bdd1243dSDimitry Andric /// to ensure this. Returns std::nullopt if we find something we can't split.
288bdd1243dSDimitry Andric std::optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
2890b57cec5SDimitry Andric   if (Pos >= Size)
2900b57cec5SDimitry Andric     return Offsets.size();
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   while (true) {
2930b57cec5SDimitry Andric     auto FirstAfterPos = llvm::upper_bound(Offsets, Pos);
2940b57cec5SDimitry Andric     if (FirstAfterPos == Offsets.begin())
2950b57cec5SDimitry Andric       return 0;
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric     // If we already have an element starting at Pos, we're done.
2980b57cec5SDimitry Andric     size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
2990b57cec5SDimitry Andric     if (Offsets[LastAtOrBeforePosIndex] == Pos)
3000b57cec5SDimitry Andric       return LastAtOrBeforePosIndex;
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric     // We found an element starting before Pos. Check for overlap.
3030b57cec5SDimitry Andric     if (Offsets[LastAtOrBeforePosIndex] +
3040b57cec5SDimitry Andric         getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
3050b57cec5SDimitry Andric       return LastAtOrBeforePosIndex + 1;
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric     // Try to decompose it into smaller constants.
3080b57cec5SDimitry Andric     if (!split(LastAtOrBeforePosIndex, Pos))
309bdd1243dSDimitry Andric       return std::nullopt;
3100b57cec5SDimitry Andric   }
3110b57cec5SDimitry Andric }
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric /// Split the constant at index Index, if possible. Return true if we did.
3140b57cec5SDimitry Andric /// Hint indicates the location at which we'd like to split, but may be
3150b57cec5SDimitry Andric /// ignored.
3160b57cec5SDimitry Andric bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
3170b57cec5SDimitry Andric   NaturalLayout = false;
3180b57cec5SDimitry Andric   llvm::Constant *C = Elems[Index];
3190b57cec5SDimitry Andric   CharUnits Offset = Offsets[Index];
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
3225ffd83dbSDimitry Andric     // Expand the sequence into its contained elements.
3235ffd83dbSDimitry Andric     // FIXME: This assumes vector elements are byte-sized.
3240b57cec5SDimitry Andric     replace(Elems, Index, Index + 1,
3250b57cec5SDimitry Andric             llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
3260b57cec5SDimitry Andric                             [&](unsigned Op) { return CA->getOperand(Op); }));
3275ffd83dbSDimitry Andric     if (isa<llvm::ArrayType>(CA->getType()) ||
3285ffd83dbSDimitry Andric         isa<llvm::VectorType>(CA->getType())) {
3290b57cec5SDimitry Andric       // Array or vector.
3305ffd83dbSDimitry Andric       llvm::Type *ElemTy =
3315ffd83dbSDimitry Andric           llvm::GetElementPtrInst::getTypeAtIndex(CA->getType(), (uint64_t)0);
3325ffd83dbSDimitry Andric       CharUnits ElemSize = getSize(ElemTy);
3330b57cec5SDimitry Andric       replace(
3340b57cec5SDimitry Andric           Offsets, Index, Index + 1,
3350b57cec5SDimitry Andric           llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
3360b57cec5SDimitry Andric                           [&](unsigned Op) { return Offset + Op * ElemSize; }));
3370b57cec5SDimitry Andric     } else {
3380b57cec5SDimitry Andric       // Must be a struct.
3390b57cec5SDimitry Andric       auto *ST = cast<llvm::StructType>(CA->getType());
3400b57cec5SDimitry Andric       const llvm::StructLayout *Layout =
3410b57cec5SDimitry Andric           CGM.getDataLayout().getStructLayout(ST);
3420b57cec5SDimitry Andric       replace(Offsets, Index, Index + 1,
3430b57cec5SDimitry Andric               llvm::map_range(
3440b57cec5SDimitry Andric                   llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {
3450b57cec5SDimitry Andric                     return Offset + CharUnits::fromQuantity(
3460b57cec5SDimitry Andric                                         Layout->getElementOffset(Op));
3470b57cec5SDimitry Andric                   }));
3480b57cec5SDimitry Andric     }
3490b57cec5SDimitry Andric     return true;
3500b57cec5SDimitry Andric   }
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric   if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
3535ffd83dbSDimitry Andric     // Expand the sequence into its contained elements.
3545ffd83dbSDimitry Andric     // FIXME: This assumes vector elements are byte-sized.
3550b57cec5SDimitry Andric     // FIXME: If possible, split into two ConstantDataSequentials at Hint.
3560b57cec5SDimitry Andric     CharUnits ElemSize = getSize(CDS->getElementType());
3570b57cec5SDimitry Andric     replace(Elems, Index, Index + 1,
3580b57cec5SDimitry Andric             llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
3590b57cec5SDimitry Andric                             [&](unsigned Elem) {
3600b57cec5SDimitry Andric                               return CDS->getElementAsConstant(Elem);
3610b57cec5SDimitry Andric                             }));
3620b57cec5SDimitry Andric     replace(Offsets, Index, Index + 1,
3630b57cec5SDimitry Andric             llvm::map_range(
3640b57cec5SDimitry Andric                 llvm::seq(0u, CDS->getNumElements()),
3650b57cec5SDimitry Andric                 [&](unsigned Elem) { return Offset + Elem * ElemSize; }));
3660b57cec5SDimitry Andric     return true;
3670b57cec5SDimitry Andric   }
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   if (isa<llvm::ConstantAggregateZero>(C)) {
3705ffd83dbSDimitry Andric     // Split into two zeros at the hinted offset.
3710b57cec5SDimitry Andric     CharUnits ElemSize = getSize(C);
3720b57cec5SDimitry Andric     assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
3730b57cec5SDimitry Andric     replace(Elems, Index, Index + 1,
3740b57cec5SDimitry Andric             {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
3750b57cec5SDimitry Andric     replace(Offsets, Index, Index + 1, {Offset, Hint});
3760b57cec5SDimitry Andric     return true;
3770b57cec5SDimitry Andric   }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   if (isa<llvm::UndefValue>(C)) {
3805ffd83dbSDimitry Andric     // Drop undef; it doesn't contribute to the final layout.
3810b57cec5SDimitry Andric     replace(Elems, Index, Index + 1, {});
3820b57cec5SDimitry Andric     replace(Offsets, Index, Index + 1, {});
3830b57cec5SDimitry Andric     return true;
3840b57cec5SDimitry Andric   }
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   // FIXME: We could split a ConstantInt if the need ever arose.
3870b57cec5SDimitry Andric   // We don't need to do this to handle bit-fields because we always eagerly
3880b57cec5SDimitry Andric   // split them into 1-byte chunks.
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   return false;
3910b57cec5SDimitry Andric }
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric static llvm::Constant *
3940b57cec5SDimitry Andric EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
3950b57cec5SDimitry Andric                   llvm::Type *CommonElementType, unsigned ArrayBound,
3960b57cec5SDimitry Andric                   SmallVectorImpl<llvm::Constant *> &Elements,
3970b57cec5SDimitry Andric                   llvm::Constant *Filler);
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric llvm::Constant *ConstantAggregateBuilder::buildFrom(
4000b57cec5SDimitry Andric     CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
4010b57cec5SDimitry Andric     ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
4020b57cec5SDimitry Andric     bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
4030b57cec5SDimitry Andric   ConstantAggregateBuilderUtils Utils(CGM);
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   if (Elems.empty())
4060b57cec5SDimitry Andric     return llvm::UndefValue::get(DesiredTy);
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric   auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   // If we want an array type, see if all the elements are the same type and
4110b57cec5SDimitry Andric   // appropriately spaced.
4120b57cec5SDimitry Andric   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
4130b57cec5SDimitry Andric     assert(!AllowOversized && "oversized array emission not supported");
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric     bool CanEmitArray = true;
4160b57cec5SDimitry Andric     llvm::Type *CommonType = Elems[0]->getType();
4170b57cec5SDimitry Andric     llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
4180b57cec5SDimitry Andric     CharUnits ElemSize = Utils.getSize(ATy->getElementType());
4190b57cec5SDimitry Andric     SmallVector<llvm::Constant*, 32> ArrayElements;
4200b57cec5SDimitry Andric     for (size_t I = 0; I != Elems.size(); ++I) {
4210b57cec5SDimitry Andric       // Skip zeroes; we'll use a zero value as our array filler.
4220b57cec5SDimitry Andric       if (Elems[I]->isNullValue())
4230b57cec5SDimitry Andric         continue;
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric       // All remaining elements must be the same type.
4260b57cec5SDimitry Andric       if (Elems[I]->getType() != CommonType ||
4270b57cec5SDimitry Andric           Offset(I) % ElemSize != 0) {
4280b57cec5SDimitry Andric         CanEmitArray = false;
4290b57cec5SDimitry Andric         break;
4300b57cec5SDimitry Andric       }
4310b57cec5SDimitry Andric       ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);
4320b57cec5SDimitry Andric       ArrayElements.back() = Elems[I];
4330b57cec5SDimitry Andric     }
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric     if (CanEmitArray) {
4360b57cec5SDimitry Andric       return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
4370b57cec5SDimitry Andric                                ArrayElements, Filler);
4380b57cec5SDimitry Andric     }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric     // Can't emit as an array, carry on to emit as a struct.
4410b57cec5SDimitry Andric   }
4420b57cec5SDimitry Andric 
44381ad6265SDimitry Andric   // The size of the constant we plan to generate.  This is usually just
44481ad6265SDimitry Andric   // the size of the initialized type, but in AllowOversized mode (i.e.
44581ad6265SDimitry Andric   // flexible array init), it can be larger.
4460b57cec5SDimitry Andric   CharUnits DesiredSize = Utils.getSize(DesiredTy);
44781ad6265SDimitry Andric   if (Size > DesiredSize) {
44881ad6265SDimitry Andric     assert(AllowOversized && "Elems are oversized");
44981ad6265SDimitry Andric     DesiredSize = Size;
45081ad6265SDimitry Andric   }
45181ad6265SDimitry Andric 
45281ad6265SDimitry Andric   // The natural alignment of an unpacked LLVM struct with the given elements.
4530b57cec5SDimitry Andric   CharUnits Align = CharUnits::One();
4540b57cec5SDimitry Andric   for (llvm::Constant *C : Elems)
4550b57cec5SDimitry Andric     Align = std::max(Align, Utils.getAlignment(C));
45681ad6265SDimitry Andric 
45781ad6265SDimitry Andric   // The natural size of an unpacked LLVM struct with the given elements.
4580b57cec5SDimitry Andric   CharUnits AlignedSize = Size.alignTo(Align);
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   bool Packed = false;
4610b57cec5SDimitry Andric   ArrayRef<llvm::Constant*> UnpackedElems = Elems;
4620b57cec5SDimitry Andric   llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
46381ad6265SDimitry Andric   if (DesiredSize < AlignedSize || DesiredSize.alignTo(Align) != DesiredSize) {
46481ad6265SDimitry Andric     // The natural layout would be too big; force use of a packed layout.
4650b57cec5SDimitry Andric     NaturalLayout = false;
4660b57cec5SDimitry Andric     Packed = true;
4670b57cec5SDimitry Andric   } else if (DesiredSize > AlignedSize) {
46881ad6265SDimitry Andric     // The natural layout would be too small. Add padding to fix it. (This
46981ad6265SDimitry Andric     // is ignored if we choose a packed layout.)
4700b57cec5SDimitry Andric     UnpackedElemStorage.assign(Elems.begin(), Elems.end());
4710b57cec5SDimitry Andric     UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
4720b57cec5SDimitry Andric     UnpackedElems = UnpackedElemStorage;
4730b57cec5SDimitry Andric   }
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   // If we don't have a natural layout, insert padding as necessary.
4760b57cec5SDimitry Andric   // As we go, double-check to see if we can actually just emit Elems
4770b57cec5SDimitry Andric   // as a non-packed struct and do so opportunistically if possible.
4780b57cec5SDimitry Andric   llvm::SmallVector<llvm::Constant*, 32> PackedElems;
4790b57cec5SDimitry Andric   if (!NaturalLayout) {
4800b57cec5SDimitry Andric     CharUnits SizeSoFar = CharUnits::Zero();
4810b57cec5SDimitry Andric     for (size_t I = 0; I != Elems.size(); ++I) {
4820b57cec5SDimitry Andric       CharUnits Align = Utils.getAlignment(Elems[I]);
4830b57cec5SDimitry Andric       CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
4840b57cec5SDimitry Andric       CharUnits DesiredOffset = Offset(I);
4850b57cec5SDimitry Andric       assert(DesiredOffset >= SizeSoFar && "elements out of order");
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric       if (DesiredOffset != NaturalOffset)
4880b57cec5SDimitry Andric         Packed = true;
4890b57cec5SDimitry Andric       if (DesiredOffset != SizeSoFar)
4900b57cec5SDimitry Andric         PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
4910b57cec5SDimitry Andric       PackedElems.push_back(Elems[I]);
4920b57cec5SDimitry Andric       SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
4930b57cec5SDimitry Andric     }
4940b57cec5SDimitry Andric     // If we're using the packed layout, pad it out to the desired size if
4950b57cec5SDimitry Andric     // necessary.
4960b57cec5SDimitry Andric     if (Packed) {
49781ad6265SDimitry Andric       assert(SizeSoFar <= DesiredSize &&
4980b57cec5SDimitry Andric              "requested size is too small for contents");
4990b57cec5SDimitry Andric       if (SizeSoFar < DesiredSize)
5000b57cec5SDimitry Andric         PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
5010b57cec5SDimitry Andric     }
5020b57cec5SDimitry Andric   }
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric   llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
5050b57cec5SDimitry Andric       CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   // Pick the type to use.  If the type is layout identical to the desired
5080b57cec5SDimitry Andric   // type then use it, otherwise use whatever the builder produced for us.
5090b57cec5SDimitry Andric   if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
5100b57cec5SDimitry Andric     if (DesiredSTy->isLayoutIdentical(STy))
5110b57cec5SDimitry Andric       STy = DesiredSTy;
5120b57cec5SDimitry Andric   }
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric   return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
5150b57cec5SDimitry Andric }
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric void ConstantAggregateBuilder::condense(CharUnits Offset,
5180b57cec5SDimitry Andric                                         llvm::Type *DesiredTy) {
5190b57cec5SDimitry Andric   CharUnits Size = getSize(DesiredTy);
5200b57cec5SDimitry Andric 
521bdd1243dSDimitry Andric   std::optional<size_t> FirstElemToReplace = splitAt(Offset);
5220b57cec5SDimitry Andric   if (!FirstElemToReplace)
5230b57cec5SDimitry Andric     return;
5240b57cec5SDimitry Andric   size_t First = *FirstElemToReplace;
5250b57cec5SDimitry Andric 
526bdd1243dSDimitry Andric   std::optional<size_t> LastElemToReplace = splitAt(Offset + Size);
5270b57cec5SDimitry Andric   if (!LastElemToReplace)
5280b57cec5SDimitry Andric     return;
5290b57cec5SDimitry Andric   size_t Last = *LastElemToReplace;
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   size_t Length = Last - First;
5320b57cec5SDimitry Andric   if (Length == 0)
5330b57cec5SDimitry Andric     return;
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric   if (Length == 1 && Offsets[First] == Offset &&
5360b57cec5SDimitry Andric       getSize(Elems[First]) == Size) {
5370b57cec5SDimitry Andric     // Re-wrap single element structs if necessary. Otherwise, leave any single
5380b57cec5SDimitry Andric     // element constant of the right size alone even if it has the wrong type.
5390b57cec5SDimitry Andric     auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
5400b57cec5SDimitry Andric     if (STy && STy->getNumElements() == 1 &&
5410b57cec5SDimitry Andric         STy->getElementType(0) == Elems[First]->getType())
5420b57cec5SDimitry Andric       Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
5430b57cec5SDimitry Andric     return;
5440b57cec5SDimitry Andric   }
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   llvm::Constant *Replacement = buildFrom(
547bdd1243dSDimitry Andric       CGM, ArrayRef(Elems).slice(First, Length),
548bdd1243dSDimitry Andric       ArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
5490b57cec5SDimitry Andric       /*known to have natural layout=*/false, DesiredTy, false);
5500b57cec5SDimitry Andric   replace(Elems, First, Last, {Replacement});
5510b57cec5SDimitry Andric   replace(Offsets, First, Last, {Offset});
5520b57cec5SDimitry Andric }
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5550b57cec5SDimitry Andric //                            ConstStructBuilder
5560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric class ConstStructBuilder {
5590b57cec5SDimitry Andric   CodeGenModule &CGM;
5600b57cec5SDimitry Andric   ConstantEmitter &Emitter;
5610b57cec5SDimitry Andric   ConstantAggregateBuilder &Builder;
5620b57cec5SDimitry Andric   CharUnits StartOffset;
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric public:
5650b57cec5SDimitry Andric   static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
5660b57cec5SDimitry Andric                                      InitListExpr *ILE, QualType StructTy);
5670b57cec5SDimitry Andric   static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
5680b57cec5SDimitry Andric                                      const APValue &Value, QualType ValTy);
5690b57cec5SDimitry Andric   static bool UpdateStruct(ConstantEmitter &Emitter,
5700b57cec5SDimitry Andric                            ConstantAggregateBuilder &Const, CharUnits Offset,
5710b57cec5SDimitry Andric                            InitListExpr *Updater);
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric private:
5740b57cec5SDimitry Andric   ConstStructBuilder(ConstantEmitter &Emitter,
5750b57cec5SDimitry Andric                      ConstantAggregateBuilder &Builder, CharUnits StartOffset)
5760b57cec5SDimitry Andric       : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
5770b57cec5SDimitry Andric         StartOffset(StartOffset) {}
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric   bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
5800b57cec5SDimitry Andric                    llvm::Constant *InitExpr, bool AllowOverwrite = false);
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric   bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
5830b57cec5SDimitry Andric                    bool AllowOverwrite = false);
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
5860b57cec5SDimitry Andric                       llvm::ConstantInt *InitExpr, bool AllowOverwrite = false);
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric   bool Build(InitListExpr *ILE, bool AllowOverwrite);
5890b57cec5SDimitry Andric   bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
5900b57cec5SDimitry Andric              const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
5910b57cec5SDimitry Andric   llvm::Constant *Finalize(QualType Ty);
5920b57cec5SDimitry Andric };
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric bool ConstStructBuilder::AppendField(
5950b57cec5SDimitry Andric     const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
5960b57cec5SDimitry Andric     bool AllowOverwrite) {
5970b57cec5SDimitry Andric   const ASTContext &Context = CGM.getContext();
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric   CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
6020b57cec5SDimitry Andric }
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
6050b57cec5SDimitry Andric                                      llvm::Constant *InitCst,
6060b57cec5SDimitry Andric                                      bool AllowOverwrite) {
6070b57cec5SDimitry Andric   return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
6080b57cec5SDimitry Andric }
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric bool ConstStructBuilder::AppendBitField(
6110b57cec5SDimitry Andric     const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
6120b57cec5SDimitry Andric     bool AllowOverwrite) {
6135ffd83dbSDimitry Andric   const CGRecordLayout &RL =
6145ffd83dbSDimitry Andric       CGM.getTypes().getCGRecordLayout(Field->getParent());
6155ffd83dbSDimitry Andric   const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
6160b57cec5SDimitry Andric   llvm::APInt FieldValue = CI->getValue();
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric   // Promote the size of FieldValue if necessary
6190b57cec5SDimitry Andric   // FIXME: This should never occur, but currently it can because initializer
6200b57cec5SDimitry Andric   // constants are cast to bool, and because clang is not enforcing bitfield
6210b57cec5SDimitry Andric   // width limits.
6225ffd83dbSDimitry Andric   if (Info.Size > FieldValue.getBitWidth())
6235ffd83dbSDimitry Andric     FieldValue = FieldValue.zext(Info.Size);
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   // Truncate the size of FieldValue to the bit field size.
6265ffd83dbSDimitry Andric   if (Info.Size < FieldValue.getBitWidth())
6275ffd83dbSDimitry Andric     FieldValue = FieldValue.trunc(Info.Size);
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   return Builder.addBits(FieldValue,
6300b57cec5SDimitry Andric                          CGM.getContext().toBits(StartOffset) + FieldOffset,
6310b57cec5SDimitry Andric                          AllowOverwrite);
6320b57cec5SDimitry Andric }
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
6350b57cec5SDimitry Andric                                       ConstantAggregateBuilder &Const,
6360b57cec5SDimitry Andric                                       CharUnits Offset, QualType Type,
6370b57cec5SDimitry Andric                                       InitListExpr *Updater) {
6380b57cec5SDimitry Andric   if (Type->isRecordType())
6390b57cec5SDimitry Andric     return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
6420b57cec5SDimitry Andric   if (!CAT)
6430b57cec5SDimitry Andric     return false;
6440b57cec5SDimitry Andric   QualType ElemType = CAT->getElementType();
6450b57cec5SDimitry Andric   CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
6460b57cec5SDimitry Andric   llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric   llvm::Constant *FillC = nullptr;
6490b57cec5SDimitry Andric   if (Expr *Filler = Updater->getArrayFiller()) {
6500b57cec5SDimitry Andric     if (!isa<NoInitExpr>(Filler)) {
6510b57cec5SDimitry Andric       FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
6520b57cec5SDimitry Andric       if (!FillC)
6530b57cec5SDimitry Andric         return false;
6540b57cec5SDimitry Andric     }
6550b57cec5SDimitry Andric   }
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric   unsigned NumElementsToUpdate =
6580b57cec5SDimitry Andric       FillC ? CAT->getSize().getZExtValue() : Updater->getNumInits();
6590b57cec5SDimitry Andric   for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
6600b57cec5SDimitry Andric     Expr *Init = nullptr;
6610b57cec5SDimitry Andric     if (I < Updater->getNumInits())
6620b57cec5SDimitry Andric       Init = Updater->getInit(I);
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric     if (!Init && FillC) {
6650b57cec5SDimitry Andric       if (!Const.add(FillC, Offset, true))
6660b57cec5SDimitry Andric         return false;
6670b57cec5SDimitry Andric     } else if (!Init || isa<NoInitExpr>(Init)) {
6680b57cec5SDimitry Andric       continue;
6690b57cec5SDimitry Andric     } else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) {
6700b57cec5SDimitry Andric       if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
6710b57cec5SDimitry Andric                                      ChildILE))
6720b57cec5SDimitry Andric         return false;
6730b57cec5SDimitry Andric       // Attempt to reduce the array element to a single constant if necessary.
6740b57cec5SDimitry Andric       Const.condense(Offset, ElemTy);
6750b57cec5SDimitry Andric     } else {
6760b57cec5SDimitry Andric       llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
6770b57cec5SDimitry Andric       if (!Const.add(Val, Offset, true))
6780b57cec5SDimitry Andric         return false;
6790b57cec5SDimitry Andric     }
6800b57cec5SDimitry Andric   }
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric   return true;
6830b57cec5SDimitry Andric }
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric bool ConstStructBuilder::Build(InitListExpr *ILE, bool AllowOverwrite) {
686a7dea167SDimitry Andric   RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
6870b57cec5SDimitry Andric   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   unsigned FieldNo = -1;
6900b57cec5SDimitry Andric   unsigned ElementNo = 0;
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   // Bail out if we have base classes. We could support these, but they only
6930b57cec5SDimitry Andric   // arise in C++1z where we will have already constant folded most interesting
6940b57cec5SDimitry Andric   // cases. FIXME: There are still a few more cases we can handle this way.
6950b57cec5SDimitry Andric   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6960b57cec5SDimitry Andric     if (CXXRD->getNumBases())
6970b57cec5SDimitry Andric       return false;
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric   for (FieldDecl *Field : RD->fields()) {
7000b57cec5SDimitry Andric     ++FieldNo;
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric     // If this is a union, skip all the fields that aren't being initialized.
7030b57cec5SDimitry Andric     if (RD->isUnion() &&
7040b57cec5SDimitry Andric         !declaresSameEntity(ILE->getInitializedFieldInUnion(), Field))
7050b57cec5SDimitry Andric       continue;
7060b57cec5SDimitry Andric 
70781ad6265SDimitry Andric     // Don't emit anonymous bitfields.
70881ad6265SDimitry Andric     if (Field->isUnnamedBitfield())
7090b57cec5SDimitry Andric       continue;
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric     // Get the initializer.  A struct can include fields without initializers,
7120b57cec5SDimitry Andric     // we just use explicit null values for them.
7130b57cec5SDimitry Andric     Expr *Init = nullptr;
7140b57cec5SDimitry Andric     if (ElementNo < ILE->getNumInits())
7150b57cec5SDimitry Andric       Init = ILE->getInit(ElementNo++);
7160b57cec5SDimitry Andric     if (Init && isa<NoInitExpr>(Init))
7170b57cec5SDimitry Andric       continue;
7180b57cec5SDimitry Andric 
71981ad6265SDimitry Andric     // Zero-sized fields are not emitted, but their initializers may still
72081ad6265SDimitry Andric     // prevent emission of this struct as a constant.
72181ad6265SDimitry Andric     if (Field->isZeroSize(CGM.getContext())) {
72281ad6265SDimitry Andric       if (Init->HasSideEffects(CGM.getContext()))
72381ad6265SDimitry Andric         return false;
72481ad6265SDimitry Andric       continue;
72581ad6265SDimitry Andric     }
72681ad6265SDimitry Andric 
7270b57cec5SDimitry Andric     // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
7280b57cec5SDimitry Andric     // represents additional overwriting of our current constant value, and not
7290b57cec5SDimitry Andric     // a new constant to emit independently.
7300b57cec5SDimitry Andric     if (AllowOverwrite &&
7310b57cec5SDimitry Andric         (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
7320b57cec5SDimitry Andric       if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
7330b57cec5SDimitry Andric         CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
7340b57cec5SDimitry Andric             Layout.getFieldOffset(FieldNo));
7350b57cec5SDimitry Andric         if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
7360b57cec5SDimitry Andric                                        Field->getType(), SubILE))
7370b57cec5SDimitry Andric           return false;
7380b57cec5SDimitry Andric         // If we split apart the field's value, try to collapse it down to a
7390b57cec5SDimitry Andric         // single value now.
7400b57cec5SDimitry Andric         Builder.condense(StartOffset + Offset,
7410b57cec5SDimitry Andric                          CGM.getTypes().ConvertTypeForMem(Field->getType()));
7420b57cec5SDimitry Andric         continue;
7430b57cec5SDimitry Andric       }
7440b57cec5SDimitry Andric     }
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric     llvm::Constant *EltInit =
7470b57cec5SDimitry Andric         Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
7480b57cec5SDimitry Andric              : Emitter.emitNullForMemory(Field->getType());
7490b57cec5SDimitry Andric     if (!EltInit)
7500b57cec5SDimitry Andric       return false;
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric     if (!Field->isBitField()) {
7530b57cec5SDimitry Andric       // Handle non-bitfield members.
7540b57cec5SDimitry Andric       if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
7550b57cec5SDimitry Andric                        AllowOverwrite))
7560b57cec5SDimitry Andric         return false;
7570b57cec5SDimitry Andric       // After emitting a non-empty field with [[no_unique_address]], we may
7580b57cec5SDimitry Andric       // need to overwrite its tail padding.
7590b57cec5SDimitry Andric       if (Field->hasAttr<NoUniqueAddressAttr>())
7600b57cec5SDimitry Andric         AllowOverwrite = true;
7610b57cec5SDimitry Andric     } else {
7620b57cec5SDimitry Andric       // Otherwise we have a bitfield.
7630b57cec5SDimitry Andric       if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
7640b57cec5SDimitry Andric         if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI,
7650b57cec5SDimitry Andric                             AllowOverwrite))
7660b57cec5SDimitry Andric           return false;
7670b57cec5SDimitry Andric       } else {
7680b57cec5SDimitry Andric         // We are trying to initialize a bitfield with a non-trivial constant,
7690b57cec5SDimitry Andric         // this must require run-time code.
7700b57cec5SDimitry Andric         return false;
7710b57cec5SDimitry Andric       }
7720b57cec5SDimitry Andric     }
7730b57cec5SDimitry Andric   }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric   return true;
7760b57cec5SDimitry Andric }
7770b57cec5SDimitry Andric 
7780b57cec5SDimitry Andric namespace {
7790b57cec5SDimitry Andric struct BaseInfo {
7800b57cec5SDimitry Andric   BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
7810b57cec5SDimitry Andric     : Decl(Decl), Offset(Offset), Index(Index) {
7820b57cec5SDimitry Andric   }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   const CXXRecordDecl *Decl;
7850b57cec5SDimitry Andric   CharUnits Offset;
7860b57cec5SDimitry Andric   unsigned Index;
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric   bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
7890b57cec5SDimitry Andric };
7900b57cec5SDimitry Andric }
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
7930b57cec5SDimitry Andric                                bool IsPrimaryBase,
7940b57cec5SDimitry Andric                                const CXXRecordDecl *VTableClass,
7950b57cec5SDimitry Andric                                CharUnits Offset) {
7960b57cec5SDimitry Andric   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric   if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
7990b57cec5SDimitry Andric     // Add a vtable pointer, if we need one and it hasn't already been added.
8005ffd83dbSDimitry Andric     if (Layout.hasOwnVFPtr()) {
8010b57cec5SDimitry Andric       llvm::Constant *VTableAddressPoint =
8020b57cec5SDimitry Andric           CGM.getCXXABI().getVTableAddressPointForConstExpr(
8030b57cec5SDimitry Andric               BaseSubobject(CD, Offset), VTableClass);
8040b57cec5SDimitry Andric       if (!AppendBytes(Offset, VTableAddressPoint))
8050b57cec5SDimitry Andric         return false;
8060b57cec5SDimitry Andric     }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric     // Accumulate and sort bases, in order to visit them in address order, which
8090b57cec5SDimitry Andric     // may not be the same as declaration order.
8100b57cec5SDimitry Andric     SmallVector<BaseInfo, 8> Bases;
8110b57cec5SDimitry Andric     Bases.reserve(CD->getNumBases());
8120b57cec5SDimitry Andric     unsigned BaseNo = 0;
8130b57cec5SDimitry Andric     for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
8140b57cec5SDimitry Andric          BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
8150b57cec5SDimitry Andric       assert(!Base->isVirtual() && "should not have virtual bases here");
8160b57cec5SDimitry Andric       const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
8170b57cec5SDimitry Andric       CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
8180b57cec5SDimitry Andric       Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
8190b57cec5SDimitry Andric     }
8200b57cec5SDimitry Andric     llvm::stable_sort(Bases);
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric     for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
8230b57cec5SDimitry Andric       BaseInfo &Base = Bases[I];
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric       bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
8260b57cec5SDimitry Andric       Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
8270b57cec5SDimitry Andric             VTableClass, Offset + Base.Offset);
8280b57cec5SDimitry Andric     }
8290b57cec5SDimitry Andric   }
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   unsigned FieldNo = 0;
8320b57cec5SDimitry Andric   uint64_t OffsetBits = CGM.getContext().toBits(Offset);
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   bool AllowOverwrite = false;
8350b57cec5SDimitry Andric   for (RecordDecl::field_iterator Field = RD->field_begin(),
8360b57cec5SDimitry Andric        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
8370b57cec5SDimitry Andric     // If this is a union, skip all the fields that aren't being initialized.
8380b57cec5SDimitry Andric     if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
8390b57cec5SDimitry Andric       continue;
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric     // Don't emit anonymous bitfields or zero-sized fields.
8420b57cec5SDimitry Andric     if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
8430b57cec5SDimitry Andric       continue;
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric     // Emit the value of the initializer.
8460b57cec5SDimitry Andric     const APValue &FieldValue =
8470b57cec5SDimitry Andric       RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
8480b57cec5SDimitry Andric     llvm::Constant *EltInit =
8490b57cec5SDimitry Andric       Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
8500b57cec5SDimitry Andric     if (!EltInit)
8510b57cec5SDimitry Andric       return false;
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric     if (!Field->isBitField()) {
8540b57cec5SDimitry Andric       // Handle non-bitfield members.
8550b57cec5SDimitry Andric       if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
8560b57cec5SDimitry Andric                        EltInit, AllowOverwrite))
8570b57cec5SDimitry Andric         return false;
8580b57cec5SDimitry Andric       // After emitting a non-empty field with [[no_unique_address]], we may
8590b57cec5SDimitry Andric       // need to overwrite its tail padding.
8600b57cec5SDimitry Andric       if (Field->hasAttr<NoUniqueAddressAttr>())
8610b57cec5SDimitry Andric         AllowOverwrite = true;
8620b57cec5SDimitry Andric     } else {
8630b57cec5SDimitry Andric       // Otherwise we have a bitfield.
8640b57cec5SDimitry Andric       if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
8650b57cec5SDimitry Andric                           cast<llvm::ConstantInt>(EltInit), AllowOverwrite))
8660b57cec5SDimitry Andric         return false;
8670b57cec5SDimitry Andric     }
8680b57cec5SDimitry Andric   }
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric   return true;
8710b57cec5SDimitry Andric }
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
8741fd87a68SDimitry Andric   Type = Type.getNonReferenceType();
875a7dea167SDimitry Andric   RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
8760b57cec5SDimitry Andric   llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
8770b57cec5SDimitry Andric   return Builder.build(ValTy, RD->hasFlexibleArrayMember());
8780b57cec5SDimitry Andric }
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
8810b57cec5SDimitry Andric                                                 InitListExpr *ILE,
8820b57cec5SDimitry Andric                                                 QualType ValTy) {
8830b57cec5SDimitry Andric   ConstantAggregateBuilder Const(Emitter.CGM);
8840b57cec5SDimitry Andric   ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric   if (!Builder.Build(ILE, /*AllowOverwrite*/false))
8870b57cec5SDimitry Andric     return nullptr;
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   return Builder.Finalize(ValTy);
8900b57cec5SDimitry Andric }
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
8930b57cec5SDimitry Andric                                                 const APValue &Val,
8940b57cec5SDimitry Andric                                                 QualType ValTy) {
8950b57cec5SDimitry Andric   ConstantAggregateBuilder Const(Emitter.CGM);
8960b57cec5SDimitry Andric   ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric   const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
8990b57cec5SDimitry Andric   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9000b57cec5SDimitry Andric   if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
9010b57cec5SDimitry Andric     return nullptr;
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   return Builder.Finalize(ValTy);
9040b57cec5SDimitry Andric }
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
9070b57cec5SDimitry Andric                                       ConstantAggregateBuilder &Const,
9080b57cec5SDimitry Andric                                       CharUnits Offset, InitListExpr *Updater) {
9090b57cec5SDimitry Andric   return ConstStructBuilder(Emitter, Const, Offset)
9100b57cec5SDimitry Andric       .Build(Updater, /*AllowOverwrite*/ true);
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9140b57cec5SDimitry Andric //                             ConstExprEmitter
9150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9160b57cec5SDimitry Andric 
917bdd1243dSDimitry Andric static ConstantAddress
918bdd1243dSDimitry Andric tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter,
9190b57cec5SDimitry Andric                              const CompoundLiteralExpr *E) {
920bdd1243dSDimitry Andric   CodeGenModule &CGM = emitter.CGM;
9210b57cec5SDimitry Andric   CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
9220b57cec5SDimitry Andric   if (llvm::GlobalVariable *Addr =
9230b57cec5SDimitry Andric           CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
9240eae32dcSDimitry Andric     return ConstantAddress(Addr, Addr->getValueType(), Align);
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   LangAS addressSpace = E->getType().getAddressSpace();
9270b57cec5SDimitry Andric   llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
9280b57cec5SDimitry Andric                                                     addressSpace, E->getType());
9290b57cec5SDimitry Andric   if (!C) {
9300b57cec5SDimitry Andric     assert(!E->isFileScope() &&
9310b57cec5SDimitry Andric            "file-scope compound literal did not have constant initializer!");
9320b57cec5SDimitry Andric     return ConstantAddress::invalid();
9330b57cec5SDimitry Andric   }
9340b57cec5SDimitry Andric 
935*fe013be4SDimitry Andric   auto GV = new llvm::GlobalVariable(
936*fe013be4SDimitry Andric       CGM.getModule(), C->getType(),
937*fe013be4SDimitry Andric       CGM.isTypeConstant(E->getType(), true, false),
938*fe013be4SDimitry Andric       llvm::GlobalValue::InternalLinkage, C, ".compoundliteral", nullptr,
9390b57cec5SDimitry Andric       llvm::GlobalVariable::NotThreadLocal,
9400b57cec5SDimitry Andric       CGM.getContext().getTargetAddressSpace(addressSpace));
9410b57cec5SDimitry Andric   emitter.finalize(GV);
942a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
9430b57cec5SDimitry Andric   CGM.setAddrOfConstantCompoundLiteral(E, GV);
9440eae32dcSDimitry Andric   return ConstantAddress(GV, GV->getValueType(), Align);
9450b57cec5SDimitry Andric }
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric static llvm::Constant *
9480b57cec5SDimitry Andric EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
9490b57cec5SDimitry Andric                   llvm::Type *CommonElementType, unsigned ArrayBound,
9500b57cec5SDimitry Andric                   SmallVectorImpl<llvm::Constant *> &Elements,
9510b57cec5SDimitry Andric                   llvm::Constant *Filler) {
9520b57cec5SDimitry Andric   // Figure out how long the initial prefix of non-zero elements is.
9530b57cec5SDimitry Andric   unsigned NonzeroLength = ArrayBound;
9540b57cec5SDimitry Andric   if (Elements.size() < NonzeroLength && Filler->isNullValue())
9550b57cec5SDimitry Andric     NonzeroLength = Elements.size();
9560b57cec5SDimitry Andric   if (NonzeroLength == Elements.size()) {
9570b57cec5SDimitry Andric     while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
9580b57cec5SDimitry Andric       --NonzeroLength;
9590b57cec5SDimitry Andric   }
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   if (NonzeroLength == 0)
9620b57cec5SDimitry Andric     return llvm::ConstantAggregateZero::get(DesiredType);
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric   // Add a zeroinitializer array filler if we have lots of trailing zeroes.
9650b57cec5SDimitry Andric   unsigned TrailingZeroes = ArrayBound - NonzeroLength;
9660b57cec5SDimitry Andric   if (TrailingZeroes >= 8) {
9670b57cec5SDimitry Andric     assert(Elements.size() >= NonzeroLength &&
9680b57cec5SDimitry Andric            "missing initializer for non-zero element");
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric     // If all the elements had the same type up to the trailing zeroes, emit a
9710b57cec5SDimitry Andric     // struct of two arrays (the nonzero data and the zeroinitializer).
9720b57cec5SDimitry Andric     if (CommonElementType && NonzeroLength >= 8) {
9730b57cec5SDimitry Andric       llvm::Constant *Initial = llvm::ConstantArray::get(
9740b57cec5SDimitry Andric           llvm::ArrayType::get(CommonElementType, NonzeroLength),
975bdd1243dSDimitry Andric           ArrayRef(Elements).take_front(NonzeroLength));
9760b57cec5SDimitry Andric       Elements.resize(2);
9770b57cec5SDimitry Andric       Elements[0] = Initial;
9780b57cec5SDimitry Andric     } else {
9790b57cec5SDimitry Andric       Elements.resize(NonzeroLength + 1);
9800b57cec5SDimitry Andric     }
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric     auto *FillerType =
9830b57cec5SDimitry Andric         CommonElementType ? CommonElementType : DesiredType->getElementType();
9840b57cec5SDimitry Andric     FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
9850b57cec5SDimitry Andric     Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
9860b57cec5SDimitry Andric     CommonElementType = nullptr;
9870b57cec5SDimitry Andric   } else if (Elements.size() != ArrayBound) {
9880b57cec5SDimitry Andric     // Otherwise pad to the right size with the filler if necessary.
9890b57cec5SDimitry Andric     Elements.resize(ArrayBound, Filler);
9900b57cec5SDimitry Andric     if (Filler->getType() != CommonElementType)
9910b57cec5SDimitry Andric       CommonElementType = nullptr;
9920b57cec5SDimitry Andric   }
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   // If all elements have the same type, just emit an array constant.
9950b57cec5SDimitry Andric   if (CommonElementType)
9960b57cec5SDimitry Andric     return llvm::ConstantArray::get(
9970b57cec5SDimitry Andric         llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric   // We have mixed types. Use a packed struct.
10000b57cec5SDimitry Andric   llvm::SmallVector<llvm::Type *, 16> Types;
10010b57cec5SDimitry Andric   Types.reserve(Elements.size());
10020b57cec5SDimitry Andric   for (llvm::Constant *Elt : Elements)
10030b57cec5SDimitry Andric     Types.push_back(Elt->getType());
10040b57cec5SDimitry Andric   llvm::StructType *SType =
10050b57cec5SDimitry Andric       llvm::StructType::get(CGM.getLLVMContext(), Types, true);
10060b57cec5SDimitry Andric   return llvm::ConstantStruct::get(SType, Elements);
10070b57cec5SDimitry Andric }
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric // This class only needs to handle arrays, structs and unions. Outside C++11
10100b57cec5SDimitry Andric // mode, we don't currently constant fold those types.  All other types are
10110b57cec5SDimitry Andric // handled by constant folding.
10120b57cec5SDimitry Andric //
10130b57cec5SDimitry Andric // Constant folding is currently missing support for a few features supported
10140b57cec5SDimitry Andric // here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
10150b57cec5SDimitry Andric class ConstExprEmitter :
10160b57cec5SDimitry Andric   public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
10170b57cec5SDimitry Andric   CodeGenModule &CGM;
10180b57cec5SDimitry Andric   ConstantEmitter &Emitter;
10190b57cec5SDimitry Andric   llvm::LLVMContext &VMContext;
10200b57cec5SDimitry Andric public:
10210b57cec5SDimitry Andric   ConstExprEmitter(ConstantEmitter &emitter)
10220b57cec5SDimitry Andric     : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
10230b57cec5SDimitry Andric   }
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric   //===--------------------------------------------------------------------===//
10260b57cec5SDimitry Andric   //                            Visitor Methods
10270b57cec5SDimitry Andric   //===--------------------------------------------------------------------===//
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   llvm::Constant *VisitStmt(Stmt *S, QualType T) {
10300b57cec5SDimitry Andric     return nullptr;
10310b57cec5SDimitry Andric   }
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric   llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
10345ffd83dbSDimitry Andric     if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(CE))
10355ffd83dbSDimitry Andric       return Result;
10360b57cec5SDimitry Andric     return Visit(CE->getSubExpr(), T);
10370b57cec5SDimitry Andric   }
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric   llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
10400b57cec5SDimitry Andric     return Visit(PE->getSubExpr(), T);
10410b57cec5SDimitry Andric   }
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   llvm::Constant *
10440b57cec5SDimitry Andric   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
10450b57cec5SDimitry Andric                                     QualType T) {
10460b57cec5SDimitry Andric     return Visit(PE->getReplacement(), T);
10470b57cec5SDimitry Andric   }
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric   llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
10500b57cec5SDimitry Andric                                             QualType T) {
10510b57cec5SDimitry Andric     return Visit(GE->getResultExpr(), T);
10520b57cec5SDimitry Andric   }
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
10550b57cec5SDimitry Andric     return Visit(CE->getChosenSubExpr(), T);
10560b57cec5SDimitry Andric   }
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
10590b57cec5SDimitry Andric     return Visit(E->getInitializer(), T);
10600b57cec5SDimitry Andric   }
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric   llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
10630b57cec5SDimitry Andric     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
10640b57cec5SDimitry Andric       CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
10650b57cec5SDimitry Andric     Expr *subExpr = E->getSubExpr();
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric     switch (E->getCastKind()) {
10680b57cec5SDimitry Andric     case CK_ToUnion: {
10690b57cec5SDimitry Andric       // GCC cast to union extension
10700b57cec5SDimitry Andric       assert(E->getType()->isUnionType() &&
10710b57cec5SDimitry Andric              "Destination type is not union type!");
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric       auto field = E->getTargetUnionField();
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric       auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
10760b57cec5SDimitry Andric       if (!C) return nullptr;
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric       auto destTy = ConvertType(destType);
10790b57cec5SDimitry Andric       if (C->getType() == destTy) return C;
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric       // Build a struct with the union sub-element as the first member,
10820b57cec5SDimitry Andric       // and padded to the appropriate size.
10830b57cec5SDimitry Andric       SmallVector<llvm::Constant*, 2> Elts;
10840b57cec5SDimitry Andric       SmallVector<llvm::Type*, 2> Types;
10850b57cec5SDimitry Andric       Elts.push_back(C);
10860b57cec5SDimitry Andric       Types.push_back(C->getType());
10870b57cec5SDimitry Andric       unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
10880b57cec5SDimitry Andric       unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
10890b57cec5SDimitry Andric 
10900b57cec5SDimitry Andric       assert(CurSize <= TotalSize && "Union size mismatch!");
10910b57cec5SDimitry Andric       if (unsigned NumPadBytes = TotalSize - CurSize) {
1092e8d8bef9SDimitry Andric         llvm::Type *Ty = CGM.CharTy;
10930b57cec5SDimitry Andric         if (NumPadBytes > 1)
10940b57cec5SDimitry Andric           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric         Elts.push_back(llvm::UndefValue::get(Ty));
10970b57cec5SDimitry Andric         Types.push_back(Ty);
10980b57cec5SDimitry Andric       }
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric       llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
11010b57cec5SDimitry Andric       return llvm::ConstantStruct::get(STy, Elts);
11020b57cec5SDimitry Andric     }
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric     case CK_AddressSpaceConversion: {
11050b57cec5SDimitry Andric       auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
11060b57cec5SDimitry Andric       if (!C) return nullptr;
11070b57cec5SDimitry Andric       LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
11080b57cec5SDimitry Andric       LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
11090b57cec5SDimitry Andric       llvm::Type *destTy = ConvertType(E->getType());
11100b57cec5SDimitry Andric       return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
11110b57cec5SDimitry Andric                                                              destAS, destTy);
11120b57cec5SDimitry Andric     }
11130b57cec5SDimitry Andric 
111481ad6265SDimitry Andric     case CK_LValueToRValue: {
111581ad6265SDimitry Andric       // We don't really support doing lvalue-to-rvalue conversions here; any
111681ad6265SDimitry Andric       // interesting conversions should be done in Evaluate().  But as a
111781ad6265SDimitry Andric       // special case, allow compound literals to support the gcc extension
111881ad6265SDimitry Andric       // allowing "struct x {int x;} x = (struct x) {};".
111981ad6265SDimitry Andric       if (auto *E = dyn_cast<CompoundLiteralExpr>(subExpr->IgnoreParens()))
112081ad6265SDimitry Andric         return Visit(E->getInitializer(), destType);
112181ad6265SDimitry Andric       return nullptr;
112281ad6265SDimitry Andric     }
112381ad6265SDimitry Andric 
11240b57cec5SDimitry Andric     case CK_AtomicToNonAtomic:
11250b57cec5SDimitry Andric     case CK_NonAtomicToAtomic:
11260b57cec5SDimitry Andric     case CK_NoOp:
11270b57cec5SDimitry Andric     case CK_ConstructorConversion:
11280b57cec5SDimitry Andric       return Visit(subExpr, destType);
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric     case CK_IntToOCLSampler:
11310b57cec5SDimitry Andric       llvm_unreachable("global sampler variables are not generated");
11320b57cec5SDimitry Andric 
11330b57cec5SDimitry Andric     case CK_Dependent: llvm_unreachable("saw dependent cast!");
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric     case CK_BuiltinFnToFnPtr:
11360b57cec5SDimitry Andric       llvm_unreachable("builtin functions are handled elsewhere");
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric     case CK_ReinterpretMemberPointer:
11390b57cec5SDimitry Andric     case CK_DerivedToBaseMemberPointer:
11400b57cec5SDimitry Andric     case CK_BaseToDerivedMemberPointer: {
11410b57cec5SDimitry Andric       auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
11420b57cec5SDimitry Andric       if (!C) return nullptr;
11430b57cec5SDimitry Andric       return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
11440b57cec5SDimitry Andric     }
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric     // These will never be supported.
11470b57cec5SDimitry Andric     case CK_ObjCObjectLValueCast:
11480b57cec5SDimitry Andric     case CK_ARCProduceObject:
11490b57cec5SDimitry Andric     case CK_ARCConsumeObject:
11500b57cec5SDimitry Andric     case CK_ARCReclaimReturnedObject:
11510b57cec5SDimitry Andric     case CK_ARCExtendBlockObject:
11520b57cec5SDimitry Andric     case CK_CopyAndAutoreleaseBlockObject:
11530b57cec5SDimitry Andric       return nullptr;
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric     // These don't need to be handled here because Evaluate knows how to
11560b57cec5SDimitry Andric     // evaluate them in the cases where they can be folded.
11570b57cec5SDimitry Andric     case CK_BitCast:
11580b57cec5SDimitry Andric     case CK_ToVoid:
11590b57cec5SDimitry Andric     case CK_Dynamic:
11600b57cec5SDimitry Andric     case CK_LValueBitCast:
11610b57cec5SDimitry Andric     case CK_LValueToRValueBitCast:
11620b57cec5SDimitry Andric     case CK_NullToMemberPointer:
11630b57cec5SDimitry Andric     case CK_UserDefinedConversion:
11640b57cec5SDimitry Andric     case CK_CPointerToObjCPointerCast:
11650b57cec5SDimitry Andric     case CK_BlockPointerToObjCPointerCast:
11660b57cec5SDimitry Andric     case CK_AnyPointerToBlockPointerCast:
11670b57cec5SDimitry Andric     case CK_ArrayToPointerDecay:
11680b57cec5SDimitry Andric     case CK_FunctionToPointerDecay:
11690b57cec5SDimitry Andric     case CK_BaseToDerived:
11700b57cec5SDimitry Andric     case CK_DerivedToBase:
11710b57cec5SDimitry Andric     case CK_UncheckedDerivedToBase:
11720b57cec5SDimitry Andric     case CK_MemberPointerToBoolean:
11730b57cec5SDimitry Andric     case CK_VectorSplat:
11740b57cec5SDimitry Andric     case CK_FloatingRealToComplex:
11750b57cec5SDimitry Andric     case CK_FloatingComplexToReal:
11760b57cec5SDimitry Andric     case CK_FloatingComplexToBoolean:
11770b57cec5SDimitry Andric     case CK_FloatingComplexCast:
11780b57cec5SDimitry Andric     case CK_FloatingComplexToIntegralComplex:
11790b57cec5SDimitry Andric     case CK_IntegralRealToComplex:
11800b57cec5SDimitry Andric     case CK_IntegralComplexToReal:
11810b57cec5SDimitry Andric     case CK_IntegralComplexToBoolean:
11820b57cec5SDimitry Andric     case CK_IntegralComplexCast:
11830b57cec5SDimitry Andric     case CK_IntegralComplexToFloatingComplex:
11840b57cec5SDimitry Andric     case CK_PointerToIntegral:
11850b57cec5SDimitry Andric     case CK_PointerToBoolean:
11860b57cec5SDimitry Andric     case CK_NullToPointer:
11870b57cec5SDimitry Andric     case CK_IntegralCast:
11880b57cec5SDimitry Andric     case CK_BooleanToSignedIntegral:
11890b57cec5SDimitry Andric     case CK_IntegralToPointer:
11900b57cec5SDimitry Andric     case CK_IntegralToBoolean:
11910b57cec5SDimitry Andric     case CK_IntegralToFloating:
11920b57cec5SDimitry Andric     case CK_FloatingToIntegral:
11930b57cec5SDimitry Andric     case CK_FloatingToBoolean:
11940b57cec5SDimitry Andric     case CK_FloatingCast:
1195e8d8bef9SDimitry Andric     case CK_FloatingToFixedPoint:
1196e8d8bef9SDimitry Andric     case CK_FixedPointToFloating:
11970b57cec5SDimitry Andric     case CK_FixedPointCast:
11980b57cec5SDimitry Andric     case CK_FixedPointToBoolean:
11990b57cec5SDimitry Andric     case CK_FixedPointToIntegral:
12000b57cec5SDimitry Andric     case CK_IntegralToFixedPoint:
12010b57cec5SDimitry Andric     case CK_ZeroToOCLOpaqueType:
1202fe6060f1SDimitry Andric     case CK_MatrixCast:
12030b57cec5SDimitry Andric       return nullptr;
12040b57cec5SDimitry Andric     }
12050b57cec5SDimitry Andric     llvm_unreachable("Invalid CastKind");
12060b57cec5SDimitry Andric   }
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
12090b57cec5SDimitry Andric     // No need for a DefaultInitExprScope: we don't handle 'this' in a
12100b57cec5SDimitry Andric     // constant expression.
12110b57cec5SDimitry Andric     return Visit(DIE->getExpr(), T);
12120b57cec5SDimitry Andric   }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric   llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
12150b57cec5SDimitry Andric     return Visit(E->getSubExpr(), T);
12160b57cec5SDimitry Andric   }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
12190b57cec5SDimitry Andric     auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
12200b57cec5SDimitry Andric     assert(CAT && "can't emit array init for non-constant-bound array");
12210b57cec5SDimitry Andric     unsigned NumInitElements = ILE->getNumInits();
12220b57cec5SDimitry Andric     unsigned NumElements = CAT->getSize().getZExtValue();
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric     // Initialising an array requires us to automatically
12250b57cec5SDimitry Andric     // initialise any elements that have not been initialised explicitly
12260b57cec5SDimitry Andric     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric     QualType EltType = CAT->getElementType();
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric     // Initialize remaining array elements.
12310b57cec5SDimitry Andric     llvm::Constant *fillC = nullptr;
12320b57cec5SDimitry Andric     if (Expr *filler = ILE->getArrayFiller()) {
12330b57cec5SDimitry Andric       fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
12340b57cec5SDimitry Andric       if (!fillC)
12350b57cec5SDimitry Andric         return nullptr;
12360b57cec5SDimitry Andric     }
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric     // Copy initializer elements.
12390b57cec5SDimitry Andric     SmallVector<llvm::Constant*, 16> Elts;
12400b57cec5SDimitry Andric     if (fillC && fillC->isNullValue())
12410b57cec5SDimitry Andric       Elts.reserve(NumInitableElts + 1);
12420b57cec5SDimitry Andric     else
12430b57cec5SDimitry Andric       Elts.reserve(NumElements);
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric     llvm::Type *CommonElementType = nullptr;
12460b57cec5SDimitry Andric     for (unsigned i = 0; i < NumInitableElts; ++i) {
12470b57cec5SDimitry Andric       Expr *Init = ILE->getInit(i);
12480b57cec5SDimitry Andric       llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
12490b57cec5SDimitry Andric       if (!C)
12500b57cec5SDimitry Andric         return nullptr;
12510b57cec5SDimitry Andric       if (i == 0)
12520b57cec5SDimitry Andric         CommonElementType = C->getType();
12530b57cec5SDimitry Andric       else if (C->getType() != CommonElementType)
12540b57cec5SDimitry Andric         CommonElementType = nullptr;
12550b57cec5SDimitry Andric       Elts.push_back(C);
12560b57cec5SDimitry Andric     }
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric     llvm::ArrayType *Desired =
12590b57cec5SDimitry Andric         cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
12600b57cec5SDimitry Andric     return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
12610b57cec5SDimitry Andric                              fillC);
12620b57cec5SDimitry Andric   }
12630b57cec5SDimitry Andric 
12640b57cec5SDimitry Andric   llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
12650b57cec5SDimitry Andric     return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
12660b57cec5SDimitry Andric   }
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
12690b57cec5SDimitry Andric                                              QualType T) {
12700b57cec5SDimitry Andric     return CGM.EmitNullConstant(T);
12710b57cec5SDimitry Andric   }
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric   llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
12740b57cec5SDimitry Andric     if (ILE->isTransparent())
12750b57cec5SDimitry Andric       return Visit(ILE->getInit(0), T);
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric     if (ILE->getType()->isArrayType())
12780b57cec5SDimitry Andric       return EmitArrayInitialization(ILE, T);
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric     if (ILE->getType()->isRecordType())
12810b57cec5SDimitry Andric       return EmitRecordInitialization(ILE, T);
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric     return nullptr;
12840b57cec5SDimitry Andric   }
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric   llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
12870b57cec5SDimitry Andric                                                 QualType destType) {
12880b57cec5SDimitry Andric     auto C = Visit(E->getBase(), destType);
12890b57cec5SDimitry Andric     if (!C)
12900b57cec5SDimitry Andric       return nullptr;
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric     ConstantAggregateBuilder Const(CGM);
12930b57cec5SDimitry Andric     Const.add(C, CharUnits::Zero(), false);
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric     if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
12960b57cec5SDimitry Andric                                    E->getUpdater()))
12970b57cec5SDimitry Andric       return nullptr;
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric     llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
13000b57cec5SDimitry Andric     bool HasFlexibleArray = false;
13010b57cec5SDimitry Andric     if (auto *RT = destType->getAs<RecordType>())
13020b57cec5SDimitry Andric       HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
13030b57cec5SDimitry Andric     return Const.build(ValTy, HasFlexibleArray);
13040b57cec5SDimitry Andric   }
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
13070b57cec5SDimitry Andric     if (!E->getConstructor()->isTrivial())
13080b57cec5SDimitry Andric       return nullptr;
13090b57cec5SDimitry Andric 
13105ffd83dbSDimitry Andric     // Only default and copy/move constructors can be trivial.
13110b57cec5SDimitry Andric     if (E->getNumArgs()) {
13120b57cec5SDimitry Andric       assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
13130b57cec5SDimitry Andric       assert(E->getConstructor()->isCopyOrMoveConstructor() &&
13140b57cec5SDimitry Andric              "trivial ctor has argument but isn't a copy/move ctor");
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric       Expr *Arg = E->getArg(0);
13170b57cec5SDimitry Andric       assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
13180b57cec5SDimitry Andric              "argument to copy ctor is of wrong type");
13190b57cec5SDimitry Andric 
1320*fe013be4SDimitry Andric       // Look through the temporary; it's just converting the value to an
1321*fe013be4SDimitry Andric       // lvalue to pass it to the constructor.
1322*fe013be4SDimitry Andric       if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Arg))
1323*fe013be4SDimitry Andric         return Visit(MTE->getSubExpr(), Ty);
1324*fe013be4SDimitry Andric       // Don't try to support arbitrary lvalue-to-rvalue conversions for now.
1325*fe013be4SDimitry Andric       return nullptr;
13260b57cec5SDimitry Andric     }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric     return CGM.EmitNullConstant(Ty);
13290b57cec5SDimitry Andric   }
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric   llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
13320b57cec5SDimitry Andric     // This is a string literal initializing an array in an initializer.
13330b57cec5SDimitry Andric     return CGM.GetConstantArrayFromStringLiteral(E);
13340b57cec5SDimitry Andric   }
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
13370b57cec5SDimitry Andric     // This must be an @encode initializing an array in a static initializer.
13380b57cec5SDimitry Andric     // Don't emit it as the address of the string, emit the string data itself
13390b57cec5SDimitry Andric     // as an inline array.
13400b57cec5SDimitry Andric     std::string Str;
13410b57cec5SDimitry Andric     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
13420b57cec5SDimitry Andric     const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1343*fe013be4SDimitry Andric     assert(CAT && "String data not of constant array type!");
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric     // Resize the string to the right size, adding zeros at the end, or
13460b57cec5SDimitry Andric     // truncating as needed.
13470b57cec5SDimitry Andric     Str.resize(CAT->getSize().getZExtValue(), '\0');
13480b57cec5SDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
13490b57cec5SDimitry Andric   }
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
13520b57cec5SDimitry Andric     return Visit(E->getSubExpr(), T);
13530b57cec5SDimitry Andric   }
13540b57cec5SDimitry Andric 
13550b57cec5SDimitry Andric   // Utility methods
13560b57cec5SDimitry Andric   llvm::Type *ConvertType(QualType T) {
13570b57cec5SDimitry Andric     return CGM.getTypes().ConvertType(T);
13580b57cec5SDimitry Andric   }
13590b57cec5SDimitry Andric };
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric }  // end anonymous namespace.
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
13640b57cec5SDimitry Andric                                                         AbstractState saved) {
13650b57cec5SDimitry Andric   Abstract = saved.OldValue;
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric   assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
13680b57cec5SDimitry Andric          "created a placeholder while doing an abstract emission?");
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric   // No validation necessary for now.
13710b57cec5SDimitry Andric   // No cleanup to do for now.
13720b57cec5SDimitry Andric   return C;
13730b57cec5SDimitry Andric }
13740b57cec5SDimitry Andric 
13750b57cec5SDimitry Andric llvm::Constant *
13760b57cec5SDimitry Andric ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
13770b57cec5SDimitry Andric   auto state = pushAbstract();
13780b57cec5SDimitry Andric   auto C = tryEmitPrivateForVarInit(D);
13790b57cec5SDimitry Andric   return validateAndPopAbstract(C, state);
13800b57cec5SDimitry Andric }
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric llvm::Constant *
13830b57cec5SDimitry Andric ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
13840b57cec5SDimitry Andric   auto state = pushAbstract();
13850b57cec5SDimitry Andric   auto C = tryEmitPrivate(E, destType);
13860b57cec5SDimitry Andric   return validateAndPopAbstract(C, state);
13870b57cec5SDimitry Andric }
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric llvm::Constant *
13900b57cec5SDimitry Andric ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
13910b57cec5SDimitry Andric   auto state = pushAbstract();
13920b57cec5SDimitry Andric   auto C = tryEmitPrivate(value, destType);
13930b57cec5SDimitry Andric   return validateAndPopAbstract(C, state);
13940b57cec5SDimitry Andric }
13950b57cec5SDimitry Andric 
13965ffd83dbSDimitry Andric llvm::Constant *ConstantEmitter::tryEmitConstantExpr(const ConstantExpr *CE) {
13975ffd83dbSDimitry Andric   if (!CE->hasAPValueResult())
13985ffd83dbSDimitry Andric     return nullptr;
1399bdd1243dSDimitry Andric 
1400bdd1243dSDimitry Andric   QualType RetType = CE->getType();
1401bdd1243dSDimitry Andric   if (CE->isGLValue())
1402bdd1243dSDimitry Andric     RetType = CGM.getContext().getLValueReferenceType(RetType);
1403bdd1243dSDimitry Andric 
1404bdd1243dSDimitry Andric   return emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), RetType);
14055ffd83dbSDimitry Andric }
14065ffd83dbSDimitry Andric 
14070b57cec5SDimitry Andric llvm::Constant *
14080b57cec5SDimitry Andric ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
14090b57cec5SDimitry Andric   auto state = pushAbstract();
14100b57cec5SDimitry Andric   auto C = tryEmitPrivate(E, destType);
14110b57cec5SDimitry Andric   C = validateAndPopAbstract(C, state);
14120b57cec5SDimitry Andric   if (!C) {
14130b57cec5SDimitry Andric     CGM.Error(E->getExprLoc(),
14140b57cec5SDimitry Andric               "internal error: could not emit constant value \"abstractly\"");
14150b57cec5SDimitry Andric     C = CGM.EmitNullConstant(destType);
14160b57cec5SDimitry Andric   }
14170b57cec5SDimitry Andric   return C;
14180b57cec5SDimitry Andric }
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric llvm::Constant *
14210b57cec5SDimitry Andric ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
14220b57cec5SDimitry Andric                               QualType destType) {
14230b57cec5SDimitry Andric   auto state = pushAbstract();
14240b57cec5SDimitry Andric   auto C = tryEmitPrivate(value, destType);
14250b57cec5SDimitry Andric   C = validateAndPopAbstract(C, state);
14260b57cec5SDimitry Andric   if (!C) {
14270b57cec5SDimitry Andric     CGM.Error(loc,
14280b57cec5SDimitry Andric               "internal error: could not emit constant value \"abstractly\"");
14290b57cec5SDimitry Andric     C = CGM.EmitNullConstant(destType);
14300b57cec5SDimitry Andric   }
14310b57cec5SDimitry Andric   return C;
14320b57cec5SDimitry Andric }
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
14350b57cec5SDimitry Andric   initializeNonAbstract(D.getType().getAddressSpace());
14360b57cec5SDimitry Andric   return markIfFailed(tryEmitPrivateForVarInit(D));
14370b57cec5SDimitry Andric }
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
14400b57cec5SDimitry Andric                                                        LangAS destAddrSpace,
14410b57cec5SDimitry Andric                                                        QualType destType) {
14420b57cec5SDimitry Andric   initializeNonAbstract(destAddrSpace);
14430b57cec5SDimitry Andric   return markIfFailed(tryEmitPrivateForMemory(E, destType));
14440b57cec5SDimitry Andric }
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
14470b57cec5SDimitry Andric                                                     LangAS destAddrSpace,
14480b57cec5SDimitry Andric                                                     QualType destType) {
14490b57cec5SDimitry Andric   initializeNonAbstract(destAddrSpace);
14500b57cec5SDimitry Andric   auto C = tryEmitPrivateForMemory(value, destType);
14510b57cec5SDimitry Andric   assert(C && "couldn't emit constant value non-abstractly?");
14520b57cec5SDimitry Andric   return C;
14530b57cec5SDimitry Andric }
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
14560b57cec5SDimitry Andric   assert(!Abstract && "cannot get current address for abstract constant");
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   // Make an obviously ill-formed global that should blow up compilation
14610b57cec5SDimitry Andric   // if it survives.
14620b57cec5SDimitry Andric   auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
14630b57cec5SDimitry Andric                                          llvm::GlobalValue::PrivateLinkage,
14640b57cec5SDimitry Andric                                          /*init*/ nullptr,
14650b57cec5SDimitry Andric                                          /*name*/ "",
14660b57cec5SDimitry Andric                                          /*before*/ nullptr,
14670b57cec5SDimitry Andric                                          llvm::GlobalVariable::NotThreadLocal,
14680b57cec5SDimitry Andric                                          CGM.getContext().getTargetAddressSpace(DestAddressSpace));
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric   PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   return global;
14730b57cec5SDimitry Andric }
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
14760b57cec5SDimitry Andric                                            llvm::GlobalValue *placeholder) {
14770b57cec5SDimitry Andric   assert(!PlaceholderAddresses.empty());
14780b57cec5SDimitry Andric   assert(PlaceholderAddresses.back().first == nullptr);
14790b57cec5SDimitry Andric   assert(PlaceholderAddresses.back().second == placeholder);
14800b57cec5SDimitry Andric   PlaceholderAddresses.back().first = signal;
14810b57cec5SDimitry Andric }
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric namespace {
14840b57cec5SDimitry Andric   struct ReplacePlaceholders {
14850b57cec5SDimitry Andric     CodeGenModule &CGM;
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric     /// The base address of the global.
14880b57cec5SDimitry Andric     llvm::Constant *Base;
14890b57cec5SDimitry Andric     llvm::Type *BaseValueTy = nullptr;
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric     /// The placeholder addresses that were registered during emission.
14920b57cec5SDimitry Andric     llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
14930b57cec5SDimitry Andric 
14940b57cec5SDimitry Andric     /// The locations of the placeholder signals.
14950b57cec5SDimitry Andric     llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric     /// The current index stack.  We use a simple unsigned stack because
14980b57cec5SDimitry Andric     /// we assume that placeholders will be relatively sparse in the
14990b57cec5SDimitry Andric     /// initializer, but we cache the index values we find just in case.
15000b57cec5SDimitry Andric     llvm::SmallVector<unsigned, 8> Indices;
15010b57cec5SDimitry Andric     llvm::SmallVector<llvm::Constant*, 8> IndexValues;
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric     ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
15040b57cec5SDimitry Andric                         ArrayRef<std::pair<llvm::Constant*,
15050b57cec5SDimitry Andric                                            llvm::GlobalVariable*>> addresses)
15060b57cec5SDimitry Andric         : CGM(CGM), Base(base),
15070b57cec5SDimitry Andric           PlaceholderAddresses(addresses.begin(), addresses.end()) {
15080b57cec5SDimitry Andric     }
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric     void replaceInInitializer(llvm::Constant *init) {
15110b57cec5SDimitry Andric       // Remember the type of the top-most initializer.
15120b57cec5SDimitry Andric       BaseValueTy = init->getType();
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric       // Initialize the stack.
15150b57cec5SDimitry Andric       Indices.push_back(0);
15160b57cec5SDimitry Andric       IndexValues.push_back(nullptr);
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric       // Recurse into the initializer.
15190b57cec5SDimitry Andric       findLocations(init);
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric       // Check invariants.
15220b57cec5SDimitry Andric       assert(IndexValues.size() == Indices.size() && "mismatch");
15230b57cec5SDimitry Andric       assert(Indices.size() == 1 && "didn't pop all indices");
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric       // Do the replacement; this basically invalidates 'init'.
15260b57cec5SDimitry Andric       assert(Locations.size() == PlaceholderAddresses.size() &&
15270b57cec5SDimitry Andric              "missed a placeholder?");
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric       // We're iterating over a hashtable, so this would be a source of
15300b57cec5SDimitry Andric       // non-determinism in compiler output *except* that we're just
15310b57cec5SDimitry Andric       // messing around with llvm::Constant structures, which never itself
15320b57cec5SDimitry Andric       // does anything that should be visible in compiler output.
15330b57cec5SDimitry Andric       for (auto &entry : Locations) {
15340b57cec5SDimitry Andric         assert(entry.first->getParent() == nullptr && "not a placeholder!");
15350b57cec5SDimitry Andric         entry.first->replaceAllUsesWith(entry.second);
15360b57cec5SDimitry Andric         entry.first->eraseFromParent();
15370b57cec5SDimitry Andric       }
15380b57cec5SDimitry Andric     }
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric   private:
15410b57cec5SDimitry Andric     void findLocations(llvm::Constant *init) {
15420b57cec5SDimitry Andric       // Recurse into aggregates.
15430b57cec5SDimitry Andric       if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
15440b57cec5SDimitry Andric         for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
15450b57cec5SDimitry Andric           Indices.push_back(i);
15460b57cec5SDimitry Andric           IndexValues.push_back(nullptr);
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric           findLocations(agg->getOperand(i));
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric           IndexValues.pop_back();
15510b57cec5SDimitry Andric           Indices.pop_back();
15520b57cec5SDimitry Andric         }
15530b57cec5SDimitry Andric         return;
15540b57cec5SDimitry Andric       }
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric       // Otherwise, check for registered constants.
15570b57cec5SDimitry Andric       while (true) {
15580b57cec5SDimitry Andric         auto it = PlaceholderAddresses.find(init);
15590b57cec5SDimitry Andric         if (it != PlaceholderAddresses.end()) {
15600b57cec5SDimitry Andric           setLocation(it->second);
15610b57cec5SDimitry Andric           break;
15620b57cec5SDimitry Andric         }
15630b57cec5SDimitry Andric 
15640b57cec5SDimitry Andric         // Look through bitcasts or other expressions.
15650b57cec5SDimitry Andric         if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
15660b57cec5SDimitry Andric           init = expr->getOperand(0);
15670b57cec5SDimitry Andric         } else {
15680b57cec5SDimitry Andric           break;
15690b57cec5SDimitry Andric         }
15700b57cec5SDimitry Andric       }
15710b57cec5SDimitry Andric     }
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric     void setLocation(llvm::GlobalVariable *placeholder) {
1574*fe013be4SDimitry Andric       assert(!Locations.contains(placeholder) &&
15750b57cec5SDimitry Andric              "already found location for placeholder!");
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric       // Lazily fill in IndexValues with the values from Indices.
15780b57cec5SDimitry Andric       // We do this in reverse because we should always have a strict
15790b57cec5SDimitry Andric       // prefix of indices from the start.
15800b57cec5SDimitry Andric       assert(Indices.size() == IndexValues.size());
15810b57cec5SDimitry Andric       for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
15820b57cec5SDimitry Andric         if (IndexValues[i]) {
15830b57cec5SDimitry Andric #ifndef NDEBUG
15840b57cec5SDimitry Andric           for (size_t j = 0; j != i + 1; ++j) {
15850b57cec5SDimitry Andric             assert(IndexValues[j] &&
15860b57cec5SDimitry Andric                    isa<llvm::ConstantInt>(IndexValues[j]) &&
15870b57cec5SDimitry Andric                    cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
15880b57cec5SDimitry Andric                      == Indices[j]);
15890b57cec5SDimitry Andric           }
15900b57cec5SDimitry Andric #endif
15910b57cec5SDimitry Andric           break;
15920b57cec5SDimitry Andric         }
15930b57cec5SDimitry Andric 
15940b57cec5SDimitry Andric         IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
15950b57cec5SDimitry Andric       }
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric       // Form a GEP and then bitcast to the placeholder type so that the
15980b57cec5SDimitry Andric       // replacement will succeed.
15990b57cec5SDimitry Andric       llvm::Constant *location =
16000b57cec5SDimitry Andric         llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
16010b57cec5SDimitry Andric                                                      Base, IndexValues);
16020b57cec5SDimitry Andric       location = llvm::ConstantExpr::getBitCast(location,
16030b57cec5SDimitry Andric                                                 placeholder->getType());
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric       Locations.insert({placeholder, location});
16060b57cec5SDimitry Andric     }
16070b57cec5SDimitry Andric   };
16080b57cec5SDimitry Andric }
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
16110b57cec5SDimitry Andric   assert(InitializedNonAbstract &&
16120b57cec5SDimitry Andric          "finalizing emitter that was used for abstract emission?");
16130b57cec5SDimitry Andric   assert(!Finalized && "finalizing emitter multiple times");
16140b57cec5SDimitry Andric   assert(global->getInitializer());
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric   // Note that we might also be Failed.
16170b57cec5SDimitry Andric   Finalized = true;
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric   if (!PlaceholderAddresses.empty()) {
16200b57cec5SDimitry Andric     ReplacePlaceholders(CGM, global, PlaceholderAddresses)
16210b57cec5SDimitry Andric       .replaceInInitializer(global->getInitializer());
16220b57cec5SDimitry Andric     PlaceholderAddresses.clear(); // satisfy
16230b57cec5SDimitry Andric   }
16240b57cec5SDimitry Andric }
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric ConstantEmitter::~ConstantEmitter() {
16270b57cec5SDimitry Andric   assert((!InitializedNonAbstract || Finalized || Failed) &&
16280b57cec5SDimitry Andric          "not finalized after being initialized for non-abstract emission");
16290b57cec5SDimitry Andric   assert(PlaceholderAddresses.empty() && "unhandled placeholders");
16300b57cec5SDimitry Andric }
16310b57cec5SDimitry Andric 
16320b57cec5SDimitry Andric static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
16330b57cec5SDimitry Andric   if (auto AT = type->getAs<AtomicType>()) {
16340b57cec5SDimitry Andric     return CGM.getContext().getQualifiedType(AT->getValueType(),
16350b57cec5SDimitry Andric                                              type.getQualifiers());
16360b57cec5SDimitry Andric   }
16370b57cec5SDimitry Andric   return type;
16380b57cec5SDimitry Andric }
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
16410b57cec5SDimitry Andric   // Make a quick check if variable can be default NULL initialized
16420b57cec5SDimitry Andric   // and avoid going through rest of code which may do, for c++11,
16430b57cec5SDimitry Andric   // initialization of memory to all NULLs.
16440b57cec5SDimitry Andric   if (!D.hasLocalStorage()) {
16450b57cec5SDimitry Andric     QualType Ty = CGM.getContext().getBaseElementType(D.getType());
16460b57cec5SDimitry Andric     if (Ty->isRecordType())
16470b57cec5SDimitry Andric       if (const CXXConstructExpr *E =
16480b57cec5SDimitry Andric           dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
16490b57cec5SDimitry Andric         const CXXConstructorDecl *CD = E->getConstructor();
16500b57cec5SDimitry Andric         if (CD->isTrivial() && CD->isDefaultConstructor())
16510b57cec5SDimitry Andric           return CGM.EmitNullConstant(D.getType());
16520b57cec5SDimitry Andric       }
16530b57cec5SDimitry Andric   }
1654*fe013be4SDimitry Andric   InConstantContext = D.hasConstantInitialization();
16550b57cec5SDimitry Andric 
16560b57cec5SDimitry Andric   QualType destType = D.getType();
16570b57cec5SDimitry Andric   const Expr *E = D.getInit();
16580b57cec5SDimitry Andric   assert(E && "No initializer to emit");
16590b57cec5SDimitry Andric 
1660*fe013be4SDimitry Andric   if (!destType->isReferenceType()) {
1661*fe013be4SDimitry Andric     QualType nonMemoryDestType = getNonMemoryType(CGM, destType);
1662*fe013be4SDimitry Andric     if (llvm::Constant *C = ConstExprEmitter(*this).Visit(const_cast<Expr *>(E),
1663*fe013be4SDimitry Andric                                                           nonMemoryDestType))
1664*fe013be4SDimitry Andric       return emitForMemory(C, destType);
1665*fe013be4SDimitry Andric   }
1666*fe013be4SDimitry Andric 
1667*fe013be4SDimitry Andric   // Try to emit the initializer.  Note that this can allow some things that
1668*fe013be4SDimitry Andric   // are not allowed by tryEmitPrivateForMemory alone.
1669*fe013be4SDimitry Andric   if (APValue *value = D.evaluateValue())
1670*fe013be4SDimitry Andric     return tryEmitPrivateForMemory(*value, destType);
1671*fe013be4SDimitry Andric 
1672*fe013be4SDimitry Andric   return nullptr;
16730b57cec5SDimitry Andric }
16740b57cec5SDimitry Andric 
16750b57cec5SDimitry Andric llvm::Constant *
16760b57cec5SDimitry Andric ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
16770b57cec5SDimitry Andric   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
16780b57cec5SDimitry Andric   auto C = tryEmitAbstract(E, nonMemoryDestType);
16790b57cec5SDimitry Andric   return (C ? emitForMemory(C, destType) : nullptr);
16800b57cec5SDimitry Andric }
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric llvm::Constant *
16830b57cec5SDimitry Andric ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
16840b57cec5SDimitry Andric                                           QualType destType) {
16850b57cec5SDimitry Andric   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
16860b57cec5SDimitry Andric   auto C = tryEmitAbstract(value, nonMemoryDestType);
16870b57cec5SDimitry Andric   return (C ? emitForMemory(C, destType) : nullptr);
16880b57cec5SDimitry Andric }
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
16910b57cec5SDimitry Andric                                                          QualType destType) {
16920b57cec5SDimitry Andric   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
16930b57cec5SDimitry Andric   llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
16940b57cec5SDimitry Andric   return (C ? emitForMemory(C, destType) : nullptr);
16950b57cec5SDimitry Andric }
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
16980b57cec5SDimitry Andric                                                          QualType destType) {
16990b57cec5SDimitry Andric   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
17000b57cec5SDimitry Andric   auto C = tryEmitPrivate(value, nonMemoryDestType);
17010b57cec5SDimitry Andric   return (C ? emitForMemory(C, destType) : nullptr);
17020b57cec5SDimitry Andric }
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
17050b57cec5SDimitry Andric                                                llvm::Constant *C,
17060b57cec5SDimitry Andric                                                QualType destType) {
17070b57cec5SDimitry Andric   // For an _Atomic-qualified constant, we may need to add tail padding.
17080b57cec5SDimitry Andric   if (auto AT = destType->getAs<AtomicType>()) {
17090b57cec5SDimitry Andric     QualType destValueType = AT->getValueType();
17100b57cec5SDimitry Andric     C = emitForMemory(CGM, C, destValueType);
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric     uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
17130b57cec5SDimitry Andric     uint64_t outerSize = CGM.getContext().getTypeSize(destType);
17140b57cec5SDimitry Andric     if (innerSize == outerSize)
17150b57cec5SDimitry Andric       return C;
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric     assert(innerSize < outerSize && "emitted over-large constant for atomic");
17180b57cec5SDimitry Andric     llvm::Constant *elts[] = {
17190b57cec5SDimitry Andric       C,
17200b57cec5SDimitry Andric       llvm::ConstantAggregateZero::get(
17210b57cec5SDimitry Andric           llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
17220b57cec5SDimitry Andric     };
17230b57cec5SDimitry Andric     return llvm::ConstantStruct::getAnon(elts);
17240b57cec5SDimitry Andric   }
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric   // Zero-extend bool.
1727*fe013be4SDimitry Andric   if (C->getType()->isIntegerTy(1) && !destType->isBitIntType()) {
17280b57cec5SDimitry Andric     llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
17290b57cec5SDimitry Andric     return llvm::ConstantExpr::getZExt(C, boolTy);
17300b57cec5SDimitry Andric   }
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   return C;
17330b57cec5SDimitry Andric }
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
17360b57cec5SDimitry Andric                                                 QualType destType) {
1737349cc55cSDimitry Andric   assert(!destType->isVoidType() && "can't emit a void constant");
1738349cc55cSDimitry Andric 
1739*fe013be4SDimitry Andric   if (llvm::Constant *C =
1740*fe013be4SDimitry Andric           ConstExprEmitter(*this).Visit(const_cast<Expr *>(E), destType))
1741*fe013be4SDimitry Andric     return C;
1742*fe013be4SDimitry Andric 
17430b57cec5SDimitry Andric   Expr::EvalResult Result;
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric   bool Success = false;
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric   if (destType->isReferenceType())
17480b57cec5SDimitry Andric     Success = E->EvaluateAsLValue(Result, CGM.getContext());
17490b57cec5SDimitry Andric   else
17500b57cec5SDimitry Andric     Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
17510b57cec5SDimitry Andric 
17520b57cec5SDimitry Andric   if (Success && !Result.HasSideEffects)
1753*fe013be4SDimitry Andric     return tryEmitPrivate(Result.Val, destType);
17540b57cec5SDimitry Andric 
1755*fe013be4SDimitry Andric   return nullptr;
17560b57cec5SDimitry Andric }
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
17590b57cec5SDimitry Andric   return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
17600b57cec5SDimitry Andric }
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric namespace {
17630b57cec5SDimitry Andric /// A struct which can be used to peephole certain kinds of finalization
17640b57cec5SDimitry Andric /// that normally happen during l-value emission.
17650b57cec5SDimitry Andric struct ConstantLValue {
17660b57cec5SDimitry Andric   llvm::Constant *Value;
17670b57cec5SDimitry Andric   bool HasOffsetApplied;
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric   /*implicit*/ ConstantLValue(llvm::Constant *value,
17700b57cec5SDimitry Andric                               bool hasOffsetApplied = false)
1771480093f4SDimitry Andric     : Value(value), HasOffsetApplied(hasOffsetApplied) {}
17720b57cec5SDimitry Andric 
17730b57cec5SDimitry Andric   /*implicit*/ ConstantLValue(ConstantAddress address)
17740b57cec5SDimitry Andric     : ConstantLValue(address.getPointer()) {}
17750b57cec5SDimitry Andric };
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric /// A helper class for emitting constant l-values.
17780b57cec5SDimitry Andric class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
17790b57cec5SDimitry Andric                                                       ConstantLValue> {
17800b57cec5SDimitry Andric   CodeGenModule &CGM;
17810b57cec5SDimitry Andric   ConstantEmitter &Emitter;
17820b57cec5SDimitry Andric   const APValue &Value;
17830b57cec5SDimitry Andric   QualType DestType;
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric   // Befriend StmtVisitorBase so that we don't have to expose Visit*.
17860b57cec5SDimitry Andric   friend StmtVisitorBase;
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric public:
17890b57cec5SDimitry Andric   ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
17900b57cec5SDimitry Andric                         QualType destType)
17910b57cec5SDimitry Andric     : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric   llvm::Constant *tryEmit();
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric private:
17960b57cec5SDimitry Andric   llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
17970b57cec5SDimitry Andric   ConstantLValue tryEmitBase(const APValue::LValueBase &base);
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric   ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
18000b57cec5SDimitry Andric   ConstantLValue VisitConstantExpr(const ConstantExpr *E);
18010b57cec5SDimitry Andric   ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
18020b57cec5SDimitry Andric   ConstantLValue VisitStringLiteral(const StringLiteral *E);
18030b57cec5SDimitry Andric   ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
18040b57cec5SDimitry Andric   ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
18050b57cec5SDimitry Andric   ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
18060b57cec5SDimitry Andric   ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
18070b57cec5SDimitry Andric   ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
18080b57cec5SDimitry Andric   ConstantLValue VisitCallExpr(const CallExpr *E);
18090b57cec5SDimitry Andric   ConstantLValue VisitBlockExpr(const BlockExpr *E);
18100b57cec5SDimitry Andric   ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
18110b57cec5SDimitry Andric   ConstantLValue VisitMaterializeTemporaryExpr(
18120b57cec5SDimitry Andric                                          const MaterializeTemporaryExpr *E);
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   bool hasNonZeroOffset() const {
18150b57cec5SDimitry Andric     return !Value.getLValueOffset().isZero();
18160b57cec5SDimitry Andric   }
18170b57cec5SDimitry Andric 
18180b57cec5SDimitry Andric   /// Return the value offset.
18190b57cec5SDimitry Andric   llvm::Constant *getOffset() {
18200b57cec5SDimitry Andric     return llvm::ConstantInt::get(CGM.Int64Ty,
18210b57cec5SDimitry Andric                                   Value.getLValueOffset().getQuantity());
18220b57cec5SDimitry Andric   }
18230b57cec5SDimitry Andric 
18240b57cec5SDimitry Andric   /// Apply the value offset to the given constant.
18250b57cec5SDimitry Andric   llvm::Constant *applyOffset(llvm::Constant *C) {
18260b57cec5SDimitry Andric     if (!hasNonZeroOffset())
18270b57cec5SDimitry Andric       return C;
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric     llvm::Type *origPtrTy = C->getType();
18300b57cec5SDimitry Andric     C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
18310b57cec5SDimitry Andric     C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
18320b57cec5SDimitry Andric     return C;
18330b57cec5SDimitry Andric   }
18340b57cec5SDimitry Andric };
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric }
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric llvm::Constant *ConstantLValueEmitter::tryEmit() {
18390b57cec5SDimitry Andric   const APValue::LValueBase &base = Value.getLValueBase();
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric   // The destination type should be a pointer or reference
18420b57cec5SDimitry Andric   // type, but it might also be a cast thereof.
18430b57cec5SDimitry Andric   //
18440b57cec5SDimitry Andric   // FIXME: the chain of casts required should be reflected in the APValue.
18450b57cec5SDimitry Andric   // We need this in order to correctly handle things like a ptrtoint of a
18460b57cec5SDimitry Andric   // non-zero null pointer and addrspace casts that aren't trivially
18470b57cec5SDimitry Andric   // represented in LLVM IR.
18480b57cec5SDimitry Andric   auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
18490b57cec5SDimitry Andric   assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   // If there's no base at all, this is a null or absolute pointer,
18520b57cec5SDimitry Andric   // possibly cast back to an integer type.
18530b57cec5SDimitry Andric   if (!base) {
18540b57cec5SDimitry Andric     return tryEmitAbsolute(destTy);
18550b57cec5SDimitry Andric   }
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric   // Otherwise, try to emit the base.
18580b57cec5SDimitry Andric   ConstantLValue result = tryEmitBase(base);
18590b57cec5SDimitry Andric 
18600b57cec5SDimitry Andric   // If that failed, we're done.
18610b57cec5SDimitry Andric   llvm::Constant *value = result.Value;
18620b57cec5SDimitry Andric   if (!value) return nullptr;
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric   // Apply the offset if necessary and not already done.
18650b57cec5SDimitry Andric   if (!result.HasOffsetApplied) {
18660b57cec5SDimitry Andric     value = applyOffset(value);
18670b57cec5SDimitry Andric   }
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric   // Convert to the appropriate type; this could be an lvalue for
18700b57cec5SDimitry Andric   // an integer.  FIXME: performAddrSpaceCast
18710b57cec5SDimitry Andric   if (isa<llvm::PointerType>(destTy))
18720b57cec5SDimitry Andric     return llvm::ConstantExpr::getPointerCast(value, destTy);
18730b57cec5SDimitry Andric 
18740b57cec5SDimitry Andric   return llvm::ConstantExpr::getPtrToInt(value, destTy);
18750b57cec5SDimitry Andric }
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric /// Try to emit an absolute l-value, such as a null pointer or an integer
18780b57cec5SDimitry Andric /// bitcast to pointer type.
18790b57cec5SDimitry Andric llvm::Constant *
18800b57cec5SDimitry Andric ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
18810b57cec5SDimitry Andric   // If we're producing a pointer, this is easy.
18820b57cec5SDimitry Andric   auto destPtrTy = cast<llvm::PointerType>(destTy);
18830b57cec5SDimitry Andric   if (Value.isNullPointer()) {
18840b57cec5SDimitry Andric     // FIXME: integer offsets from non-zero null pointers.
18850b57cec5SDimitry Andric     return CGM.getNullPointer(destPtrTy, DestType);
18860b57cec5SDimitry Andric   }
18870b57cec5SDimitry Andric 
18880b57cec5SDimitry Andric   // Convert the integer to a pointer-sized integer before converting it
18890b57cec5SDimitry Andric   // to a pointer.
18900b57cec5SDimitry Andric   // FIXME: signedness depends on the original integer type.
18910b57cec5SDimitry Andric   auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
18920b57cec5SDimitry Andric   llvm::Constant *C;
18930b57cec5SDimitry Andric   C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
18940b57cec5SDimitry Andric                                          /*isSigned*/ false);
18950b57cec5SDimitry Andric   C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
18960b57cec5SDimitry Andric   return C;
18970b57cec5SDimitry Andric }
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric ConstantLValue
19000b57cec5SDimitry Andric ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
19010b57cec5SDimitry Andric   // Handle values.
19020b57cec5SDimitry Andric   if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1903e8d8bef9SDimitry Andric     // The constant always points to the canonical declaration. We want to look
1904e8d8bef9SDimitry Andric     // at properties of the most recent declaration at the point of emission.
1905e8d8bef9SDimitry Andric     D = cast<ValueDecl>(D->getMostRecentDecl());
1906e8d8bef9SDimitry Andric 
19070b57cec5SDimitry Andric     if (D->hasAttr<WeakRefAttr>())
19080b57cec5SDimitry Andric       return CGM.GetWeakRefReference(D).getPointer();
19090b57cec5SDimitry Andric 
19100b57cec5SDimitry Andric     if (auto FD = dyn_cast<FunctionDecl>(D))
19110b57cec5SDimitry Andric       return CGM.GetAddrOfFunction(FD);
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric     if (auto VD = dyn_cast<VarDecl>(D)) {
19140b57cec5SDimitry Andric       // We can never refer to a variable with local storage.
19150b57cec5SDimitry Andric       if (!VD->hasLocalStorage()) {
19160b57cec5SDimitry Andric         if (VD->isFileVarDecl() || VD->hasExternalStorage())
19170b57cec5SDimitry Andric           return CGM.GetAddrOfGlobalVar(VD);
19180b57cec5SDimitry Andric 
19190b57cec5SDimitry Andric         if (VD->isLocalVarDecl()) {
19200b57cec5SDimitry Andric           return CGM.getOrCreateStaticVarDecl(
19210b57cec5SDimitry Andric               *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
19220b57cec5SDimitry Andric         }
19230b57cec5SDimitry Andric       }
19240b57cec5SDimitry Andric     }
19250b57cec5SDimitry Andric 
19265ffd83dbSDimitry Andric     if (auto *GD = dyn_cast<MSGuidDecl>(D))
19275ffd83dbSDimitry Andric       return CGM.GetAddrOfMSGuidDecl(GD);
19285ffd83dbSDimitry Andric 
192981ad6265SDimitry Andric     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D))
193081ad6265SDimitry Andric       return CGM.GetAddrOfUnnamedGlobalConstantDecl(GCD);
193181ad6265SDimitry Andric 
1932e8d8bef9SDimitry Andric     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D))
1933e8d8bef9SDimitry Andric       return CGM.GetAddrOfTemplateParamObject(TPO);
1934e8d8bef9SDimitry Andric 
19350b57cec5SDimitry Andric     return nullptr;
19360b57cec5SDimitry Andric   }
19370b57cec5SDimitry Andric 
19380b57cec5SDimitry Andric   // Handle typeid(T).
1939*fe013be4SDimitry Andric   if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>())
1940*fe013be4SDimitry Andric     return CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
19410b57cec5SDimitry Andric 
19420b57cec5SDimitry Andric   // Otherwise, it must be an expression.
19430b57cec5SDimitry Andric   return Visit(base.get<const Expr*>());
19440b57cec5SDimitry Andric }
19450b57cec5SDimitry Andric 
19460b57cec5SDimitry Andric ConstantLValue
19470b57cec5SDimitry Andric ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
19485ffd83dbSDimitry Andric   if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(E))
19495ffd83dbSDimitry Andric     return Result;
19500b57cec5SDimitry Andric   return Visit(E->getSubExpr());
19510b57cec5SDimitry Andric }
19520b57cec5SDimitry Andric 
19530b57cec5SDimitry Andric ConstantLValue
19540b57cec5SDimitry Andric ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1955bdd1243dSDimitry Andric   ConstantEmitter CompoundLiteralEmitter(CGM, Emitter.CGF);
1956bdd1243dSDimitry Andric   CompoundLiteralEmitter.setInConstantContext(Emitter.isInConstantContext());
1957bdd1243dSDimitry Andric   return tryEmitGlobalCompoundLiteral(CompoundLiteralEmitter, E);
19580b57cec5SDimitry Andric }
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric ConstantLValue
19610b57cec5SDimitry Andric ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
19620b57cec5SDimitry Andric   return CGM.GetAddrOfConstantStringFromLiteral(E);
19630b57cec5SDimitry Andric }
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric ConstantLValue
19660b57cec5SDimitry Andric ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
19670b57cec5SDimitry Andric   return CGM.GetAddrOfConstantStringFromObjCEncode(E);
19680b57cec5SDimitry Andric }
19690b57cec5SDimitry Andric 
19700b57cec5SDimitry Andric static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
19710b57cec5SDimitry Andric                                                     QualType T,
19720b57cec5SDimitry Andric                                                     CodeGenModule &CGM) {
19730b57cec5SDimitry Andric   auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1974*fe013be4SDimitry Andric   return C.withElementType(CGM.getTypes().ConvertTypeForMem(T));
19750b57cec5SDimitry Andric }
19760b57cec5SDimitry Andric 
19770b57cec5SDimitry Andric ConstantLValue
19780b57cec5SDimitry Andric ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
19790b57cec5SDimitry Andric   return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
19800b57cec5SDimitry Andric }
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric ConstantLValue
19830b57cec5SDimitry Andric ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
19840b57cec5SDimitry Andric   assert(E->isExpressibleAsConstantInitializer() &&
19850b57cec5SDimitry Andric          "this boxed expression can't be emitted as a compile-time constant");
19860b57cec5SDimitry Andric   auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
19870b57cec5SDimitry Andric   return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
19880b57cec5SDimitry Andric }
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric ConstantLValue
19910b57cec5SDimitry Andric ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
19920b57cec5SDimitry Andric   return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
19930b57cec5SDimitry Andric }
19940b57cec5SDimitry Andric 
19950b57cec5SDimitry Andric ConstantLValue
19960b57cec5SDimitry Andric ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
19970b57cec5SDimitry Andric   assert(Emitter.CGF && "Invalid address of label expression outside function");
19980b57cec5SDimitry Andric   llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
19990b57cec5SDimitry Andric   Ptr = llvm::ConstantExpr::getBitCast(Ptr,
20000b57cec5SDimitry Andric                                    CGM.getTypes().ConvertType(E->getType()));
20010b57cec5SDimitry Andric   return Ptr;
20020b57cec5SDimitry Andric }
20030b57cec5SDimitry Andric 
20040b57cec5SDimitry Andric ConstantLValue
20050b57cec5SDimitry Andric ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
20060b57cec5SDimitry Andric   unsigned builtin = E->getBuiltinCallee();
20070eae32dcSDimitry Andric   if (builtin == Builtin::BI__builtin_function_start)
20080eae32dcSDimitry Andric     return CGM.GetFunctionStart(
20090eae32dcSDimitry Andric         E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext()));
20100b57cec5SDimitry Andric   if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
20110b57cec5SDimitry Andric       builtin != Builtin::BI__builtin___NSStringMakeConstantString)
20120b57cec5SDimitry Andric     return nullptr;
20130b57cec5SDimitry Andric 
20140b57cec5SDimitry Andric   auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
20150b57cec5SDimitry Andric   if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
20160b57cec5SDimitry Andric     return CGM.getObjCRuntime().GenerateConstantString(literal);
20170b57cec5SDimitry Andric   } else {
20180b57cec5SDimitry Andric     // FIXME: need to deal with UCN conversion issues.
20190b57cec5SDimitry Andric     return CGM.GetAddrOfConstantCFString(literal);
20200b57cec5SDimitry Andric   }
20210b57cec5SDimitry Andric }
20220b57cec5SDimitry Andric 
20230b57cec5SDimitry Andric ConstantLValue
20240b57cec5SDimitry Andric ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
20250b57cec5SDimitry Andric   StringRef functionName;
20260b57cec5SDimitry Andric   if (auto CGF = Emitter.CGF)
20270b57cec5SDimitry Andric     functionName = CGF->CurFn->getName();
20280b57cec5SDimitry Andric   else
20290b57cec5SDimitry Andric     functionName = "global";
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric   return CGM.GetAddrOfGlobalBlock(E, functionName);
20320b57cec5SDimitry Andric }
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric ConstantLValue
20350b57cec5SDimitry Andric ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
20360b57cec5SDimitry Andric   QualType T;
20370b57cec5SDimitry Andric   if (E->isTypeOperand())
20380b57cec5SDimitry Andric     T = E->getTypeOperand(CGM.getContext());
20390b57cec5SDimitry Andric   else
20400b57cec5SDimitry Andric     T = E->getExprOperand()->getType();
20410b57cec5SDimitry Andric   return CGM.GetAddrOfRTTIDescriptor(T);
20420b57cec5SDimitry Andric }
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric ConstantLValue
20450b57cec5SDimitry Andric ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
20460b57cec5SDimitry Andric                                             const MaterializeTemporaryExpr *E) {
20470b57cec5SDimitry Andric   assert(E->getStorageDuration() == SD_Static);
20480b57cec5SDimitry Andric   SmallVector<const Expr *, 2> CommaLHSs;
20490b57cec5SDimitry Andric   SmallVector<SubobjectAdjustment, 2> Adjustments;
2050480093f4SDimitry Andric   const Expr *Inner =
2051480093f4SDimitry Andric       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
20520b57cec5SDimitry Andric   return CGM.GetAddrOfGlobalTemporary(E, Inner);
20530b57cec5SDimitry Andric }
20540b57cec5SDimitry Andric 
20550b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
20560b57cec5SDimitry Andric                                                 QualType DestType) {
20570b57cec5SDimitry Andric   switch (Value.getKind()) {
20580b57cec5SDimitry Andric   case APValue::None:
20590b57cec5SDimitry Andric   case APValue::Indeterminate:
20600b57cec5SDimitry Andric     // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
20610b57cec5SDimitry Andric     return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
20620b57cec5SDimitry Andric   case APValue::LValue:
20630b57cec5SDimitry Andric     return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
20640b57cec5SDimitry Andric   case APValue::Int:
20650b57cec5SDimitry Andric     return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
20660b57cec5SDimitry Andric   case APValue::FixedPoint:
20670b57cec5SDimitry Andric     return llvm::ConstantInt::get(CGM.getLLVMContext(),
20680b57cec5SDimitry Andric                                   Value.getFixedPoint().getValue());
20690b57cec5SDimitry Andric   case APValue::ComplexInt: {
20700b57cec5SDimitry Andric     llvm::Constant *Complex[2];
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric     Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
20730b57cec5SDimitry Andric                                         Value.getComplexIntReal());
20740b57cec5SDimitry Andric     Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
20750b57cec5SDimitry Andric                                         Value.getComplexIntImag());
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric     // FIXME: the target may want to specify that this is packed.
20780b57cec5SDimitry Andric     llvm::StructType *STy =
20790b57cec5SDimitry Andric         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
20800b57cec5SDimitry Andric     return llvm::ConstantStruct::get(STy, Complex);
20810b57cec5SDimitry Andric   }
20820b57cec5SDimitry Andric   case APValue::Float: {
20830b57cec5SDimitry Andric     const llvm::APFloat &Init = Value.getFloat();
20840b57cec5SDimitry Andric     if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
20850b57cec5SDimitry Andric         !CGM.getContext().getLangOpts().NativeHalfType &&
20860b57cec5SDimitry Andric         CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
20870b57cec5SDimitry Andric       return llvm::ConstantInt::get(CGM.getLLVMContext(),
20880b57cec5SDimitry Andric                                     Init.bitcastToAPInt());
20890b57cec5SDimitry Andric     else
20900b57cec5SDimitry Andric       return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
20910b57cec5SDimitry Andric   }
20920b57cec5SDimitry Andric   case APValue::ComplexFloat: {
20930b57cec5SDimitry Andric     llvm::Constant *Complex[2];
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric     Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
20960b57cec5SDimitry Andric                                        Value.getComplexFloatReal());
20970b57cec5SDimitry Andric     Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
20980b57cec5SDimitry Andric                                        Value.getComplexFloatImag());
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric     // FIXME: the target may want to specify that this is packed.
21010b57cec5SDimitry Andric     llvm::StructType *STy =
21020b57cec5SDimitry Andric         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
21030b57cec5SDimitry Andric     return llvm::ConstantStruct::get(STy, Complex);
21040b57cec5SDimitry Andric   }
21050b57cec5SDimitry Andric   case APValue::Vector: {
21060b57cec5SDimitry Andric     unsigned NumElts = Value.getVectorLength();
21070b57cec5SDimitry Andric     SmallVector<llvm::Constant *, 4> Inits(NumElts);
21080b57cec5SDimitry Andric 
21090b57cec5SDimitry Andric     for (unsigned I = 0; I != NumElts; ++I) {
21100b57cec5SDimitry Andric       const APValue &Elt = Value.getVectorElt(I);
21110b57cec5SDimitry Andric       if (Elt.isInt())
21120b57cec5SDimitry Andric         Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
21130b57cec5SDimitry Andric       else if (Elt.isFloat())
21140b57cec5SDimitry Andric         Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
21150b57cec5SDimitry Andric       else
21160b57cec5SDimitry Andric         llvm_unreachable("unsupported vector element type");
21170b57cec5SDimitry Andric     }
21180b57cec5SDimitry Andric     return llvm::ConstantVector::get(Inits);
21190b57cec5SDimitry Andric   }
21200b57cec5SDimitry Andric   case APValue::AddrLabelDiff: {
21210b57cec5SDimitry Andric     const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
21220b57cec5SDimitry Andric     const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
21230b57cec5SDimitry Andric     llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
21240b57cec5SDimitry Andric     llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
21250b57cec5SDimitry Andric     if (!LHS || !RHS) return nullptr;
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric     // Compute difference
21280b57cec5SDimitry Andric     llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
21290b57cec5SDimitry Andric     LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
21300b57cec5SDimitry Andric     RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
21310b57cec5SDimitry Andric     llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric     // LLVM is a bit sensitive about the exact format of the
21340b57cec5SDimitry Andric     // address-of-label difference; make sure to truncate after
21350b57cec5SDimitry Andric     // the subtraction.
21360b57cec5SDimitry Andric     return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
21370b57cec5SDimitry Andric   }
21380b57cec5SDimitry Andric   case APValue::Struct:
21390b57cec5SDimitry Andric   case APValue::Union:
21400b57cec5SDimitry Andric     return ConstStructBuilder::BuildStruct(*this, Value, DestType);
21410b57cec5SDimitry Andric   case APValue::Array: {
2142e8d8bef9SDimitry Andric     const ArrayType *ArrayTy = CGM.getContext().getAsArrayType(DestType);
21430b57cec5SDimitry Andric     unsigned NumElements = Value.getArraySize();
21440b57cec5SDimitry Andric     unsigned NumInitElts = Value.getArrayInitializedElts();
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric     // Emit array filler, if there is one.
21470b57cec5SDimitry Andric     llvm::Constant *Filler = nullptr;
21480b57cec5SDimitry Andric     if (Value.hasArrayFiller()) {
21490b57cec5SDimitry Andric       Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
2150e8d8bef9SDimitry Andric                                         ArrayTy->getElementType());
21510b57cec5SDimitry Andric       if (!Filler)
21520b57cec5SDimitry Andric         return nullptr;
21530b57cec5SDimitry Andric     }
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric     // Emit initializer elements.
21560b57cec5SDimitry Andric     SmallVector<llvm::Constant*, 16> Elts;
21570b57cec5SDimitry Andric     if (Filler && Filler->isNullValue())
21580b57cec5SDimitry Andric       Elts.reserve(NumInitElts + 1);
21590b57cec5SDimitry Andric     else
21600b57cec5SDimitry Andric       Elts.reserve(NumElements);
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric     llvm::Type *CommonElementType = nullptr;
21630b57cec5SDimitry Andric     for (unsigned I = 0; I < NumInitElts; ++I) {
21640b57cec5SDimitry Andric       llvm::Constant *C = tryEmitPrivateForMemory(
2165e8d8bef9SDimitry Andric           Value.getArrayInitializedElt(I), ArrayTy->getElementType());
21660b57cec5SDimitry Andric       if (!C) return nullptr;
21670b57cec5SDimitry Andric 
21680b57cec5SDimitry Andric       if (I == 0)
21690b57cec5SDimitry Andric         CommonElementType = C->getType();
21700b57cec5SDimitry Andric       else if (C->getType() != CommonElementType)
21710b57cec5SDimitry Andric         CommonElementType = nullptr;
21720b57cec5SDimitry Andric       Elts.push_back(C);
21730b57cec5SDimitry Andric     }
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric     llvm::ArrayType *Desired =
21760b57cec5SDimitry Andric         cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
2177*fe013be4SDimitry Andric 
2178*fe013be4SDimitry Andric     // Fix the type of incomplete arrays if the initializer isn't empty.
2179*fe013be4SDimitry Andric     if (DestType->isIncompleteArrayType() && !Elts.empty())
2180*fe013be4SDimitry Andric       Desired = llvm::ArrayType::get(Desired->getElementType(), Elts.size());
2181*fe013be4SDimitry Andric 
21820b57cec5SDimitry Andric     return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
21830b57cec5SDimitry Andric                              Filler);
21840b57cec5SDimitry Andric   }
21850b57cec5SDimitry Andric   case APValue::MemberPointer:
21860b57cec5SDimitry Andric     return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
21870b57cec5SDimitry Andric   }
21880b57cec5SDimitry Andric   llvm_unreachable("Unknown APValue kind");
21890b57cec5SDimitry Andric }
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
21920b57cec5SDimitry Andric     const CompoundLiteralExpr *E) {
21930b57cec5SDimitry Andric   return EmittedCompoundLiterals.lookup(E);
21940b57cec5SDimitry Andric }
21950b57cec5SDimitry Andric 
21960b57cec5SDimitry Andric void CodeGenModule::setAddrOfConstantCompoundLiteral(
21970b57cec5SDimitry Andric     const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
21980b57cec5SDimitry Andric   bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
21990b57cec5SDimitry Andric   (void)Ok;
22000b57cec5SDimitry Andric   assert(Ok && "CLE has already been emitted!");
22010b57cec5SDimitry Andric }
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric ConstantAddress
22040b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
22050b57cec5SDimitry Andric   assert(E->isFileScope() && "not a file-scope compound literal expr");
2206bdd1243dSDimitry Andric   ConstantEmitter emitter(*this);
2207bdd1243dSDimitry Andric   return tryEmitGlobalCompoundLiteral(emitter, E);
22080b57cec5SDimitry Andric }
22090b57cec5SDimitry Andric 
22100b57cec5SDimitry Andric llvm::Constant *
22110b57cec5SDimitry Andric CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
22120b57cec5SDimitry Andric   // Member pointer constants always have a very particular form.
22130b57cec5SDimitry Andric   const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
22140b57cec5SDimitry Andric   const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
22150b57cec5SDimitry Andric 
22160b57cec5SDimitry Andric   // A member function pointer.
22170b57cec5SDimitry Andric   if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
22180b57cec5SDimitry Andric     return getCXXABI().EmitMemberFunctionPointer(method);
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric   // Otherwise, a member data pointer.
22210b57cec5SDimitry Andric   uint64_t fieldOffset = getContext().getFieldOffset(decl);
22220b57cec5SDimitry Andric   CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
22230b57cec5SDimitry Andric   return getCXXABI().EmitMemberDataPointer(type, chars);
22240b57cec5SDimitry Andric }
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
22270b57cec5SDimitry Andric                                                llvm::Type *baseType,
22280b57cec5SDimitry Andric                                                const CXXRecordDecl *base);
22290b57cec5SDimitry Andric 
22300b57cec5SDimitry Andric static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
22310b57cec5SDimitry Andric                                         const RecordDecl *record,
22320b57cec5SDimitry Andric                                         bool asCompleteObject) {
22330b57cec5SDimitry Andric   const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
22340b57cec5SDimitry Andric   llvm::StructType *structure =
22350b57cec5SDimitry Andric     (asCompleteObject ? layout.getLLVMType()
22360b57cec5SDimitry Andric                       : layout.getBaseSubobjectLLVMType());
22370b57cec5SDimitry Andric 
22380b57cec5SDimitry Andric   unsigned numElements = structure->getNumElements();
22390b57cec5SDimitry Andric   std::vector<llvm::Constant *> elements(numElements);
22400b57cec5SDimitry Andric 
22410b57cec5SDimitry Andric   auto CXXR = dyn_cast<CXXRecordDecl>(record);
22420b57cec5SDimitry Andric   // Fill in all the bases.
22430b57cec5SDimitry Andric   if (CXXR) {
22440b57cec5SDimitry Andric     for (const auto &I : CXXR->bases()) {
22450b57cec5SDimitry Andric       if (I.isVirtual()) {
22460b57cec5SDimitry Andric         // Ignore virtual bases; if we're laying out for a complete
22470b57cec5SDimitry Andric         // object, we'll lay these out later.
22480b57cec5SDimitry Andric         continue;
22490b57cec5SDimitry Andric       }
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric       const CXXRecordDecl *base =
22520b57cec5SDimitry Andric         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
22530b57cec5SDimitry Andric 
22540b57cec5SDimitry Andric       // Ignore empty bases.
22550b57cec5SDimitry Andric       if (base->isEmpty() ||
22560b57cec5SDimitry Andric           CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
22570b57cec5SDimitry Andric               .isZero())
22580b57cec5SDimitry Andric         continue;
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric       unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
22610b57cec5SDimitry Andric       llvm::Type *baseType = structure->getElementType(fieldIndex);
22620b57cec5SDimitry Andric       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
22630b57cec5SDimitry Andric     }
22640b57cec5SDimitry Andric   }
22650b57cec5SDimitry Andric 
22660b57cec5SDimitry Andric   // Fill in all the fields.
22670b57cec5SDimitry Andric   for (const auto *Field : record->fields()) {
22680b57cec5SDimitry Andric     // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
22690b57cec5SDimitry Andric     // will fill in later.)
22700b57cec5SDimitry Andric     if (!Field->isBitField() && !Field->isZeroSize(CGM.getContext())) {
22710b57cec5SDimitry Andric       unsigned fieldIndex = layout.getLLVMFieldNo(Field);
22720b57cec5SDimitry Andric       elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
22730b57cec5SDimitry Andric     }
22740b57cec5SDimitry Andric 
22750b57cec5SDimitry Andric     // For unions, stop after the first named field.
22760b57cec5SDimitry Andric     if (record->isUnion()) {
22770b57cec5SDimitry Andric       if (Field->getIdentifier())
22780b57cec5SDimitry Andric         break;
22790b57cec5SDimitry Andric       if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
22800b57cec5SDimitry Andric         if (FieldRD->findFirstNamedDataMember())
22810b57cec5SDimitry Andric           break;
22820b57cec5SDimitry Andric     }
22830b57cec5SDimitry Andric   }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric   // Fill in the virtual bases, if we're working with the complete object.
22860b57cec5SDimitry Andric   if (CXXR && asCompleteObject) {
22870b57cec5SDimitry Andric     for (const auto &I : CXXR->vbases()) {
22880b57cec5SDimitry Andric       const CXXRecordDecl *base =
22890b57cec5SDimitry Andric         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric       // Ignore empty bases.
22920b57cec5SDimitry Andric       if (base->isEmpty())
22930b57cec5SDimitry Andric         continue;
22940b57cec5SDimitry Andric 
22950b57cec5SDimitry Andric       unsigned fieldIndex = layout.getVirtualBaseIndex(base);
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric       // We might have already laid this field out.
22980b57cec5SDimitry Andric       if (elements[fieldIndex]) continue;
22990b57cec5SDimitry Andric 
23000b57cec5SDimitry Andric       llvm::Type *baseType = structure->getElementType(fieldIndex);
23010b57cec5SDimitry Andric       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
23020b57cec5SDimitry Andric     }
23030b57cec5SDimitry Andric   }
23040b57cec5SDimitry Andric 
23050b57cec5SDimitry Andric   // Now go through all other fields and zero them out.
23060b57cec5SDimitry Andric   for (unsigned i = 0; i != numElements; ++i) {
23070b57cec5SDimitry Andric     if (!elements[i])
23080b57cec5SDimitry Andric       elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
23090b57cec5SDimitry Andric   }
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric   return llvm::ConstantStruct::get(structure, elements);
23120b57cec5SDimitry Andric }
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric /// Emit the null constant for a base subobject.
23150b57cec5SDimitry Andric static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
23160b57cec5SDimitry Andric                                                llvm::Type *baseType,
23170b57cec5SDimitry Andric                                                const CXXRecordDecl *base) {
23180b57cec5SDimitry Andric   const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric   // Just zero out bases that don't have any pointer to data members.
23210b57cec5SDimitry Andric   if (baseLayout.isZeroInitializableAsBase())
23220b57cec5SDimitry Andric     return llvm::Constant::getNullValue(baseType);
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric   // Otherwise, we can just use its null constant.
23250b57cec5SDimitry Andric   return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
23260b57cec5SDimitry Andric }
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
23290b57cec5SDimitry Andric                                                    QualType T) {
23300b57cec5SDimitry Andric   return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
23310b57cec5SDimitry Andric }
23320b57cec5SDimitry Andric 
23330b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
23340b57cec5SDimitry Andric   if (T->getAs<PointerType>())
23350b57cec5SDimitry Andric     return getNullPointer(
23360b57cec5SDimitry Andric         cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
23370b57cec5SDimitry Andric 
23380b57cec5SDimitry Andric   if (getTypes().isZeroInitializable(T))
23390b57cec5SDimitry Andric     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
23420b57cec5SDimitry Andric     llvm::ArrayType *ATy =
23430b57cec5SDimitry Andric       cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
23440b57cec5SDimitry Andric 
23450b57cec5SDimitry Andric     QualType ElementTy = CAT->getElementType();
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric     llvm::Constant *Element =
23480b57cec5SDimitry Andric       ConstantEmitter::emitNullForMemory(*this, ElementTy);
23490b57cec5SDimitry Andric     unsigned NumElements = CAT->getSize().getZExtValue();
23500b57cec5SDimitry Andric     SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
23510b57cec5SDimitry Andric     return llvm::ConstantArray::get(ATy, Array);
23520b57cec5SDimitry Andric   }
23530b57cec5SDimitry Andric 
23540b57cec5SDimitry Andric   if (const RecordType *RT = T->getAs<RecordType>())
23550b57cec5SDimitry Andric     return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric   assert(T->isMemberDataPointerType() &&
23580b57cec5SDimitry Andric          "Should only see pointers to data members here!");
23590b57cec5SDimitry Andric 
23600b57cec5SDimitry Andric   return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
23610b57cec5SDimitry Andric }
23620b57cec5SDimitry Andric 
23630b57cec5SDimitry Andric llvm::Constant *
23640b57cec5SDimitry Andric CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
23650b57cec5SDimitry Andric   return ::EmitNullConstant(*this, Record, false);
23660b57cec5SDimitry Andric }
2367