xref: /minix3/external/bsd/llvm/dist/clang/lib/CodeGen/CGExprConstant.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This contains code to emit Constant Expr nodes as LLVM code.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc 
14f4a2713aSLionel Sambuc #include "CodeGenFunction.h"
15f4a2713aSLionel Sambuc #include "CGCXXABI.h"
16f4a2713aSLionel Sambuc #include "CGObjCRuntime.h"
17f4a2713aSLionel Sambuc #include "CGRecordLayout.h"
18f4a2713aSLionel Sambuc #include "CodeGenModule.h"
19f4a2713aSLionel Sambuc #include "clang/AST/APValue.h"
20f4a2713aSLionel Sambuc #include "clang/AST/ASTContext.h"
21f4a2713aSLionel Sambuc #include "clang/AST/RecordLayout.h"
22f4a2713aSLionel Sambuc #include "clang/AST/StmtVisitor.h"
23f4a2713aSLionel Sambuc #include "clang/Basic/Builtins.h"
24f4a2713aSLionel Sambuc #include "llvm/IR/Constants.h"
25f4a2713aSLionel Sambuc #include "llvm/IR/DataLayout.h"
26f4a2713aSLionel Sambuc #include "llvm/IR/Function.h"
27f4a2713aSLionel Sambuc #include "llvm/IR/GlobalVariable.h"
28f4a2713aSLionel Sambuc using namespace clang;
29f4a2713aSLionel Sambuc using namespace CodeGen;
30f4a2713aSLionel Sambuc 
31f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
32f4a2713aSLionel Sambuc //                            ConstStructBuilder
33f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
34f4a2713aSLionel Sambuc 
35f4a2713aSLionel Sambuc namespace {
36f4a2713aSLionel Sambuc class ConstStructBuilder {
37f4a2713aSLionel Sambuc   CodeGenModule &CGM;
38f4a2713aSLionel Sambuc   CodeGenFunction *CGF;
39f4a2713aSLionel Sambuc 
40f4a2713aSLionel Sambuc   bool Packed;
41f4a2713aSLionel Sambuc   CharUnits NextFieldOffsetInChars;
42f4a2713aSLionel Sambuc   CharUnits LLVMStructAlignment;
43f4a2713aSLionel Sambuc   SmallVector<llvm::Constant *, 32> Elements;
44f4a2713aSLionel Sambuc public:
45f4a2713aSLionel Sambuc   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
46f4a2713aSLionel Sambuc                                      InitListExpr *ILE);
47f4a2713aSLionel Sambuc   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
48f4a2713aSLionel Sambuc                                      const APValue &Value, QualType ValTy);
49f4a2713aSLionel Sambuc 
50f4a2713aSLionel Sambuc private:
ConstStructBuilder(CodeGenModule & CGM,CodeGenFunction * CGF)51f4a2713aSLionel Sambuc   ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
52f4a2713aSLionel Sambuc     : CGM(CGM), CGF(CGF), Packed(false),
53f4a2713aSLionel Sambuc     NextFieldOffsetInChars(CharUnits::Zero()),
54f4a2713aSLionel Sambuc     LLVMStructAlignment(CharUnits::One()) { }
55f4a2713aSLionel Sambuc 
56f4a2713aSLionel Sambuc   void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
57f4a2713aSLionel Sambuc                    llvm::Constant *InitExpr);
58f4a2713aSLionel Sambuc 
59f4a2713aSLionel Sambuc   void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
60f4a2713aSLionel Sambuc 
61f4a2713aSLionel Sambuc   void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
62f4a2713aSLionel Sambuc                       llvm::ConstantInt *InitExpr);
63f4a2713aSLionel Sambuc 
64f4a2713aSLionel Sambuc   void AppendPadding(CharUnits PadSize);
65f4a2713aSLionel Sambuc 
66f4a2713aSLionel Sambuc   void AppendTailPadding(CharUnits RecordSize);
67f4a2713aSLionel Sambuc 
68f4a2713aSLionel Sambuc   void ConvertStructToPacked();
69f4a2713aSLionel Sambuc 
70f4a2713aSLionel Sambuc   bool Build(InitListExpr *ILE);
71f4a2713aSLionel Sambuc   void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
72f4a2713aSLionel Sambuc              const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
73f4a2713aSLionel Sambuc   llvm::Constant *Finalize(QualType Ty);
74f4a2713aSLionel Sambuc 
getAlignment(const llvm::Constant * C) const75f4a2713aSLionel Sambuc   CharUnits getAlignment(const llvm::Constant *C) const {
76f4a2713aSLionel Sambuc     if (Packed)  return CharUnits::One();
77f4a2713aSLionel Sambuc     return CharUnits::fromQuantity(
78f4a2713aSLionel Sambuc         CGM.getDataLayout().getABITypeAlignment(C->getType()));
79f4a2713aSLionel Sambuc   }
80f4a2713aSLionel Sambuc 
getSizeInChars(const llvm::Constant * C) const81f4a2713aSLionel Sambuc   CharUnits getSizeInChars(const llvm::Constant *C) const {
82f4a2713aSLionel Sambuc     return CharUnits::fromQuantity(
83f4a2713aSLionel Sambuc         CGM.getDataLayout().getTypeAllocSize(C->getType()));
84f4a2713aSLionel Sambuc   }
85f4a2713aSLionel Sambuc };
86f4a2713aSLionel Sambuc 
87f4a2713aSLionel Sambuc void ConstStructBuilder::
AppendField(const FieldDecl * Field,uint64_t FieldOffset,llvm::Constant * InitCst)88f4a2713aSLionel Sambuc AppendField(const FieldDecl *Field, uint64_t FieldOffset,
89f4a2713aSLionel Sambuc             llvm::Constant *InitCst) {
90f4a2713aSLionel Sambuc   const ASTContext &Context = CGM.getContext();
91f4a2713aSLionel Sambuc 
92f4a2713aSLionel Sambuc   CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
93f4a2713aSLionel Sambuc 
94f4a2713aSLionel Sambuc   AppendBytes(FieldOffsetInChars, InitCst);
95f4a2713aSLionel Sambuc }
96f4a2713aSLionel Sambuc 
97f4a2713aSLionel Sambuc void ConstStructBuilder::
AppendBytes(CharUnits FieldOffsetInChars,llvm::Constant * InitCst)98f4a2713aSLionel Sambuc AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
99f4a2713aSLionel Sambuc 
100f4a2713aSLionel Sambuc   assert(NextFieldOffsetInChars <= FieldOffsetInChars
101f4a2713aSLionel Sambuc          && "Field offset mismatch!");
102f4a2713aSLionel Sambuc 
103f4a2713aSLionel Sambuc   CharUnits FieldAlignment = getAlignment(InitCst);
104f4a2713aSLionel Sambuc 
105f4a2713aSLionel Sambuc   // Round up the field offset to the alignment of the field type.
106f4a2713aSLionel Sambuc   CharUnits AlignedNextFieldOffsetInChars =
107f4a2713aSLionel Sambuc       NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
108f4a2713aSLionel Sambuc 
109f4a2713aSLionel Sambuc   if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
110f4a2713aSLionel Sambuc     // We need to append padding.
111f4a2713aSLionel Sambuc     AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
112f4a2713aSLionel Sambuc 
113f4a2713aSLionel Sambuc     assert(NextFieldOffsetInChars == FieldOffsetInChars &&
114f4a2713aSLionel Sambuc            "Did not add enough padding!");
115f4a2713aSLionel Sambuc 
116*0a6a1f1dSLionel Sambuc     AlignedNextFieldOffsetInChars =
117*0a6a1f1dSLionel Sambuc         NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
118*0a6a1f1dSLionel Sambuc   }
119*0a6a1f1dSLionel Sambuc 
120*0a6a1f1dSLionel Sambuc   if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
121*0a6a1f1dSLionel Sambuc     assert(!Packed && "Alignment is wrong even with a packed struct!");
122*0a6a1f1dSLionel Sambuc 
123*0a6a1f1dSLionel Sambuc     // Convert the struct to a packed struct.
124*0a6a1f1dSLionel Sambuc     ConvertStructToPacked();
125*0a6a1f1dSLionel Sambuc 
126*0a6a1f1dSLionel Sambuc     // After we pack the struct, we may need to insert padding.
127*0a6a1f1dSLionel Sambuc     if (NextFieldOffsetInChars < FieldOffsetInChars) {
128*0a6a1f1dSLionel Sambuc       // We need to append padding.
129*0a6a1f1dSLionel Sambuc       AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
130*0a6a1f1dSLionel Sambuc 
131*0a6a1f1dSLionel Sambuc       assert(NextFieldOffsetInChars == FieldOffsetInChars &&
132*0a6a1f1dSLionel Sambuc              "Did not add enough padding!");
133*0a6a1f1dSLionel Sambuc     }
134f4a2713aSLionel Sambuc     AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
135f4a2713aSLionel Sambuc   }
136f4a2713aSLionel Sambuc 
137f4a2713aSLionel Sambuc   // Add the field.
138f4a2713aSLionel Sambuc   Elements.push_back(InitCst);
139f4a2713aSLionel Sambuc   NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
140f4a2713aSLionel Sambuc                            getSizeInChars(InitCst);
141f4a2713aSLionel Sambuc 
142f4a2713aSLionel Sambuc   if (Packed)
143f4a2713aSLionel Sambuc     assert(LLVMStructAlignment == CharUnits::One() &&
144f4a2713aSLionel Sambuc            "Packed struct not byte-aligned!");
145f4a2713aSLionel Sambuc   else
146f4a2713aSLionel Sambuc     LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
147f4a2713aSLionel Sambuc }
148f4a2713aSLionel Sambuc 
AppendBitField(const FieldDecl * Field,uint64_t FieldOffset,llvm::ConstantInt * CI)149f4a2713aSLionel Sambuc void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
150f4a2713aSLionel Sambuc                                         uint64_t FieldOffset,
151f4a2713aSLionel Sambuc                                         llvm::ConstantInt *CI) {
152f4a2713aSLionel Sambuc   const ASTContext &Context = CGM.getContext();
153f4a2713aSLionel Sambuc   const uint64_t CharWidth = Context.getCharWidth();
154f4a2713aSLionel Sambuc   uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
155f4a2713aSLionel Sambuc   if (FieldOffset > NextFieldOffsetInBits) {
156f4a2713aSLionel Sambuc     // We need to add padding.
157f4a2713aSLionel Sambuc     CharUnits PadSize = Context.toCharUnitsFromBits(
158f4a2713aSLionel Sambuc       llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBits,
159f4a2713aSLionel Sambuc                                Context.getTargetInfo().getCharAlign()));
160f4a2713aSLionel Sambuc 
161f4a2713aSLionel Sambuc     AppendPadding(PadSize);
162f4a2713aSLionel Sambuc   }
163f4a2713aSLionel Sambuc 
164f4a2713aSLionel Sambuc   uint64_t FieldSize = Field->getBitWidthValue(Context);
165f4a2713aSLionel Sambuc 
166f4a2713aSLionel Sambuc   llvm::APInt FieldValue = CI->getValue();
167f4a2713aSLionel Sambuc 
168f4a2713aSLionel Sambuc   // Promote the size of FieldValue if necessary
169f4a2713aSLionel Sambuc   // FIXME: This should never occur, but currently it can because initializer
170f4a2713aSLionel Sambuc   // constants are cast to bool, and because clang is not enforcing bitfield
171f4a2713aSLionel Sambuc   // width limits.
172f4a2713aSLionel Sambuc   if (FieldSize > FieldValue.getBitWidth())
173f4a2713aSLionel Sambuc     FieldValue = FieldValue.zext(FieldSize);
174f4a2713aSLionel Sambuc 
175f4a2713aSLionel Sambuc   // Truncate the size of FieldValue to the bit field size.
176f4a2713aSLionel Sambuc   if (FieldSize < FieldValue.getBitWidth())
177f4a2713aSLionel Sambuc     FieldValue = FieldValue.trunc(FieldSize);
178f4a2713aSLionel Sambuc 
179f4a2713aSLionel Sambuc   NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
180f4a2713aSLionel Sambuc   if (FieldOffset < NextFieldOffsetInBits) {
181f4a2713aSLionel Sambuc     // Either part of the field or the entire field can go into the previous
182f4a2713aSLionel Sambuc     // byte.
183f4a2713aSLionel Sambuc     assert(!Elements.empty() && "Elements can't be empty!");
184f4a2713aSLionel Sambuc 
185f4a2713aSLionel Sambuc     unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
186f4a2713aSLionel Sambuc 
187f4a2713aSLionel Sambuc     bool FitsCompletelyInPreviousByte =
188f4a2713aSLionel Sambuc       BitsInPreviousByte >= FieldValue.getBitWidth();
189f4a2713aSLionel Sambuc 
190f4a2713aSLionel Sambuc     llvm::APInt Tmp = FieldValue;
191f4a2713aSLionel Sambuc 
192f4a2713aSLionel Sambuc     if (!FitsCompletelyInPreviousByte) {
193f4a2713aSLionel Sambuc       unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
194f4a2713aSLionel Sambuc 
195f4a2713aSLionel Sambuc       if (CGM.getDataLayout().isBigEndian()) {
196f4a2713aSLionel Sambuc         Tmp = Tmp.lshr(NewFieldWidth);
197f4a2713aSLionel Sambuc         Tmp = Tmp.trunc(BitsInPreviousByte);
198f4a2713aSLionel Sambuc 
199f4a2713aSLionel Sambuc         // We want the remaining high bits.
200f4a2713aSLionel Sambuc         FieldValue = FieldValue.trunc(NewFieldWidth);
201f4a2713aSLionel Sambuc       } else {
202f4a2713aSLionel Sambuc         Tmp = Tmp.trunc(BitsInPreviousByte);
203f4a2713aSLionel Sambuc 
204f4a2713aSLionel Sambuc         // We want the remaining low bits.
205f4a2713aSLionel Sambuc         FieldValue = FieldValue.lshr(BitsInPreviousByte);
206f4a2713aSLionel Sambuc         FieldValue = FieldValue.trunc(NewFieldWidth);
207f4a2713aSLionel Sambuc       }
208f4a2713aSLionel Sambuc     }
209f4a2713aSLionel Sambuc 
210f4a2713aSLionel Sambuc     Tmp = Tmp.zext(CharWidth);
211f4a2713aSLionel Sambuc     if (CGM.getDataLayout().isBigEndian()) {
212f4a2713aSLionel Sambuc       if (FitsCompletelyInPreviousByte)
213f4a2713aSLionel Sambuc         Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
214f4a2713aSLionel Sambuc     } else {
215f4a2713aSLionel Sambuc       Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
216f4a2713aSLionel Sambuc     }
217f4a2713aSLionel Sambuc 
218f4a2713aSLionel Sambuc     // 'or' in the bits that go into the previous byte.
219f4a2713aSLionel Sambuc     llvm::Value *LastElt = Elements.back();
220f4a2713aSLionel Sambuc     if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
221f4a2713aSLionel Sambuc       Tmp |= Val->getValue();
222f4a2713aSLionel Sambuc     else {
223f4a2713aSLionel Sambuc       assert(isa<llvm::UndefValue>(LastElt));
224f4a2713aSLionel Sambuc       // If there is an undef field that we're adding to, it can either be a
225f4a2713aSLionel Sambuc       // scalar undef (in which case, we just replace it with our field) or it
226f4a2713aSLionel Sambuc       // is an array.  If it is an array, we have to pull one byte off the
227f4a2713aSLionel Sambuc       // array so that the other undef bytes stay around.
228f4a2713aSLionel Sambuc       if (!isa<llvm::IntegerType>(LastElt->getType())) {
229f4a2713aSLionel Sambuc         // The undef padding will be a multibyte array, create a new smaller
230f4a2713aSLionel Sambuc         // padding and then an hole for our i8 to get plopped into.
231f4a2713aSLionel Sambuc         assert(isa<llvm::ArrayType>(LastElt->getType()) &&
232f4a2713aSLionel Sambuc                "Expected array padding of undefs");
233f4a2713aSLionel Sambuc         llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
234f4a2713aSLionel Sambuc         assert(AT->getElementType()->isIntegerTy(CharWidth) &&
235f4a2713aSLionel Sambuc                AT->getNumElements() != 0 &&
236f4a2713aSLionel Sambuc                "Expected non-empty array padding of undefs");
237f4a2713aSLionel Sambuc 
238f4a2713aSLionel Sambuc         // Remove the padding array.
239f4a2713aSLionel Sambuc         NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
240f4a2713aSLionel Sambuc         Elements.pop_back();
241f4a2713aSLionel Sambuc 
242f4a2713aSLionel Sambuc         // Add the padding back in two chunks.
243f4a2713aSLionel Sambuc         AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
244f4a2713aSLionel Sambuc         AppendPadding(CharUnits::One());
245f4a2713aSLionel Sambuc         assert(isa<llvm::UndefValue>(Elements.back()) &&
246f4a2713aSLionel Sambuc                Elements.back()->getType()->isIntegerTy(CharWidth) &&
247f4a2713aSLionel Sambuc                "Padding addition didn't work right");
248f4a2713aSLionel Sambuc       }
249f4a2713aSLionel Sambuc     }
250f4a2713aSLionel Sambuc 
251f4a2713aSLionel Sambuc     Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
252f4a2713aSLionel Sambuc 
253f4a2713aSLionel Sambuc     if (FitsCompletelyInPreviousByte)
254f4a2713aSLionel Sambuc       return;
255f4a2713aSLionel Sambuc   }
256f4a2713aSLionel Sambuc 
257f4a2713aSLionel Sambuc   while (FieldValue.getBitWidth() > CharWidth) {
258f4a2713aSLionel Sambuc     llvm::APInt Tmp;
259f4a2713aSLionel Sambuc 
260f4a2713aSLionel Sambuc     if (CGM.getDataLayout().isBigEndian()) {
261f4a2713aSLionel Sambuc       // We want the high bits.
262f4a2713aSLionel Sambuc       Tmp =
263f4a2713aSLionel Sambuc         FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
264f4a2713aSLionel Sambuc     } else {
265f4a2713aSLionel Sambuc       // We want the low bits.
266f4a2713aSLionel Sambuc       Tmp = FieldValue.trunc(CharWidth);
267f4a2713aSLionel Sambuc 
268f4a2713aSLionel Sambuc       FieldValue = FieldValue.lshr(CharWidth);
269f4a2713aSLionel Sambuc     }
270f4a2713aSLionel Sambuc 
271f4a2713aSLionel Sambuc     Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
272f4a2713aSLionel Sambuc     ++NextFieldOffsetInChars;
273f4a2713aSLionel Sambuc 
274f4a2713aSLionel Sambuc     FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
275f4a2713aSLionel Sambuc   }
276f4a2713aSLionel Sambuc 
277f4a2713aSLionel Sambuc   assert(FieldValue.getBitWidth() > 0 &&
278f4a2713aSLionel Sambuc          "Should have at least one bit left!");
279f4a2713aSLionel Sambuc   assert(FieldValue.getBitWidth() <= CharWidth &&
280f4a2713aSLionel Sambuc          "Should not have more than a byte left!");
281f4a2713aSLionel Sambuc 
282f4a2713aSLionel Sambuc   if (FieldValue.getBitWidth() < CharWidth) {
283f4a2713aSLionel Sambuc     if (CGM.getDataLayout().isBigEndian()) {
284f4a2713aSLionel Sambuc       unsigned BitWidth = FieldValue.getBitWidth();
285f4a2713aSLionel Sambuc 
286f4a2713aSLionel Sambuc       FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
287f4a2713aSLionel Sambuc     } else
288f4a2713aSLionel Sambuc       FieldValue = FieldValue.zext(CharWidth);
289f4a2713aSLionel Sambuc   }
290f4a2713aSLionel Sambuc 
291f4a2713aSLionel Sambuc   // Append the last element.
292f4a2713aSLionel Sambuc   Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
293f4a2713aSLionel Sambuc                                             FieldValue));
294f4a2713aSLionel Sambuc   ++NextFieldOffsetInChars;
295f4a2713aSLionel Sambuc }
296f4a2713aSLionel Sambuc 
AppendPadding(CharUnits PadSize)297f4a2713aSLionel Sambuc void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
298f4a2713aSLionel Sambuc   if (PadSize.isZero())
299f4a2713aSLionel Sambuc     return;
300f4a2713aSLionel Sambuc 
301f4a2713aSLionel Sambuc   llvm::Type *Ty = CGM.Int8Ty;
302f4a2713aSLionel Sambuc   if (PadSize > CharUnits::One())
303f4a2713aSLionel Sambuc     Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
304f4a2713aSLionel Sambuc 
305f4a2713aSLionel Sambuc   llvm::Constant *C = llvm::UndefValue::get(Ty);
306f4a2713aSLionel Sambuc   Elements.push_back(C);
307f4a2713aSLionel Sambuc   assert(getAlignment(C) == CharUnits::One() &&
308f4a2713aSLionel Sambuc          "Padding must have 1 byte alignment!");
309f4a2713aSLionel Sambuc 
310f4a2713aSLionel Sambuc   NextFieldOffsetInChars += getSizeInChars(C);
311f4a2713aSLionel Sambuc }
312f4a2713aSLionel Sambuc 
AppendTailPadding(CharUnits RecordSize)313f4a2713aSLionel Sambuc void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
314f4a2713aSLionel Sambuc   assert(NextFieldOffsetInChars <= RecordSize &&
315f4a2713aSLionel Sambuc          "Size mismatch!");
316f4a2713aSLionel Sambuc 
317f4a2713aSLionel Sambuc   AppendPadding(RecordSize - NextFieldOffsetInChars);
318f4a2713aSLionel Sambuc }
319f4a2713aSLionel Sambuc 
ConvertStructToPacked()320f4a2713aSLionel Sambuc void ConstStructBuilder::ConvertStructToPacked() {
321f4a2713aSLionel Sambuc   SmallVector<llvm::Constant *, 16> PackedElements;
322f4a2713aSLionel Sambuc   CharUnits ElementOffsetInChars = CharUnits::Zero();
323f4a2713aSLionel Sambuc 
324f4a2713aSLionel Sambuc   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
325f4a2713aSLionel Sambuc     llvm::Constant *C = Elements[i];
326f4a2713aSLionel Sambuc 
327f4a2713aSLionel Sambuc     CharUnits ElementAlign = CharUnits::fromQuantity(
328f4a2713aSLionel Sambuc       CGM.getDataLayout().getABITypeAlignment(C->getType()));
329f4a2713aSLionel Sambuc     CharUnits AlignedElementOffsetInChars =
330f4a2713aSLionel Sambuc       ElementOffsetInChars.RoundUpToAlignment(ElementAlign);
331f4a2713aSLionel Sambuc 
332f4a2713aSLionel Sambuc     if (AlignedElementOffsetInChars > ElementOffsetInChars) {
333f4a2713aSLionel Sambuc       // We need some padding.
334f4a2713aSLionel Sambuc       CharUnits NumChars =
335f4a2713aSLionel Sambuc         AlignedElementOffsetInChars - ElementOffsetInChars;
336f4a2713aSLionel Sambuc 
337f4a2713aSLionel Sambuc       llvm::Type *Ty = CGM.Int8Ty;
338f4a2713aSLionel Sambuc       if (NumChars > CharUnits::One())
339f4a2713aSLionel Sambuc         Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
340f4a2713aSLionel Sambuc 
341f4a2713aSLionel Sambuc       llvm::Constant *Padding = llvm::UndefValue::get(Ty);
342f4a2713aSLionel Sambuc       PackedElements.push_back(Padding);
343f4a2713aSLionel Sambuc       ElementOffsetInChars += getSizeInChars(Padding);
344f4a2713aSLionel Sambuc     }
345f4a2713aSLionel Sambuc 
346f4a2713aSLionel Sambuc     PackedElements.push_back(C);
347f4a2713aSLionel Sambuc     ElementOffsetInChars += getSizeInChars(C);
348f4a2713aSLionel Sambuc   }
349f4a2713aSLionel Sambuc 
350f4a2713aSLionel Sambuc   assert(ElementOffsetInChars == NextFieldOffsetInChars &&
351f4a2713aSLionel Sambuc          "Packing the struct changed its size!");
352f4a2713aSLionel Sambuc 
353f4a2713aSLionel Sambuc   Elements.swap(PackedElements);
354f4a2713aSLionel Sambuc   LLVMStructAlignment = CharUnits::One();
355f4a2713aSLionel Sambuc   Packed = true;
356f4a2713aSLionel Sambuc }
357f4a2713aSLionel Sambuc 
Build(InitListExpr * ILE)358f4a2713aSLionel Sambuc bool ConstStructBuilder::Build(InitListExpr *ILE) {
359f4a2713aSLionel Sambuc   RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
360f4a2713aSLionel Sambuc   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
361f4a2713aSLionel Sambuc 
362f4a2713aSLionel Sambuc   unsigned FieldNo = 0;
363f4a2713aSLionel Sambuc   unsigned ElementNo = 0;
364f4a2713aSLionel Sambuc 
365f4a2713aSLionel Sambuc   for (RecordDecl::field_iterator Field = RD->field_begin(),
366f4a2713aSLionel Sambuc        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
367f4a2713aSLionel Sambuc     // If this is a union, skip all the fields that aren't being initialized.
368f4a2713aSLionel Sambuc     if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
369f4a2713aSLionel Sambuc       continue;
370f4a2713aSLionel Sambuc 
371f4a2713aSLionel Sambuc     // Don't emit anonymous bitfields, they just affect layout.
372f4a2713aSLionel Sambuc     if (Field->isUnnamedBitfield())
373f4a2713aSLionel Sambuc       continue;
374f4a2713aSLionel Sambuc 
375f4a2713aSLionel Sambuc     // Get the initializer.  A struct can include fields without initializers,
376f4a2713aSLionel Sambuc     // we just use explicit null values for them.
377f4a2713aSLionel Sambuc     llvm::Constant *EltInit;
378f4a2713aSLionel Sambuc     if (ElementNo < ILE->getNumInits())
379f4a2713aSLionel Sambuc       EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++),
380f4a2713aSLionel Sambuc                                      Field->getType(), CGF);
381f4a2713aSLionel Sambuc     else
382f4a2713aSLionel Sambuc       EltInit = CGM.EmitNullConstant(Field->getType());
383f4a2713aSLionel Sambuc 
384f4a2713aSLionel Sambuc     if (!EltInit)
385f4a2713aSLionel Sambuc       return false;
386f4a2713aSLionel Sambuc 
387f4a2713aSLionel Sambuc     if (!Field->isBitField()) {
388f4a2713aSLionel Sambuc       // Handle non-bitfield members.
389f4a2713aSLionel Sambuc       AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
390f4a2713aSLionel Sambuc     } else {
391f4a2713aSLionel Sambuc       // Otherwise we have a bitfield.
392f4a2713aSLionel Sambuc       AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
393f4a2713aSLionel Sambuc                      cast<llvm::ConstantInt>(EltInit));
394f4a2713aSLionel Sambuc     }
395f4a2713aSLionel Sambuc   }
396f4a2713aSLionel Sambuc 
397f4a2713aSLionel Sambuc   return true;
398f4a2713aSLionel Sambuc }
399f4a2713aSLionel Sambuc 
400f4a2713aSLionel Sambuc namespace {
401f4a2713aSLionel Sambuc struct BaseInfo {
BaseInfo__anon29892e440111::__anon29892e440211::BaseInfo402f4a2713aSLionel Sambuc   BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
403f4a2713aSLionel Sambuc     : Decl(Decl), Offset(Offset), Index(Index) {
404f4a2713aSLionel Sambuc   }
405f4a2713aSLionel Sambuc 
406f4a2713aSLionel Sambuc   const CXXRecordDecl *Decl;
407f4a2713aSLionel Sambuc   CharUnits Offset;
408f4a2713aSLionel Sambuc   unsigned Index;
409f4a2713aSLionel Sambuc 
operator <__anon29892e440111::__anon29892e440211::BaseInfo410f4a2713aSLionel Sambuc   bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
411f4a2713aSLionel Sambuc };
412f4a2713aSLionel Sambuc }
413f4a2713aSLionel Sambuc 
Build(const APValue & Val,const RecordDecl * RD,bool IsPrimaryBase,const CXXRecordDecl * VTableClass,CharUnits Offset)414f4a2713aSLionel Sambuc void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
415f4a2713aSLionel Sambuc                                bool IsPrimaryBase,
416f4a2713aSLionel Sambuc                                const CXXRecordDecl *VTableClass,
417f4a2713aSLionel Sambuc                                CharUnits Offset) {
418f4a2713aSLionel Sambuc   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
419f4a2713aSLionel Sambuc 
420f4a2713aSLionel Sambuc   if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
421f4a2713aSLionel Sambuc     // Add a vtable pointer, if we need one and it hasn't already been added.
422f4a2713aSLionel Sambuc     if (CD->isDynamicClass() && !IsPrimaryBase) {
423f4a2713aSLionel Sambuc       llvm::Constant *VTableAddressPoint =
424f4a2713aSLionel Sambuc           CGM.getCXXABI().getVTableAddressPointForConstExpr(
425f4a2713aSLionel Sambuc               BaseSubobject(CD, Offset), VTableClass);
426f4a2713aSLionel Sambuc       AppendBytes(Offset, VTableAddressPoint);
427f4a2713aSLionel Sambuc     }
428f4a2713aSLionel Sambuc 
429f4a2713aSLionel Sambuc     // Accumulate and sort bases, in order to visit them in address order, which
430f4a2713aSLionel Sambuc     // may not be the same as declaration order.
431f4a2713aSLionel Sambuc     SmallVector<BaseInfo, 8> Bases;
432f4a2713aSLionel Sambuc     Bases.reserve(CD->getNumBases());
433f4a2713aSLionel Sambuc     unsigned BaseNo = 0;
434f4a2713aSLionel Sambuc     for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
435f4a2713aSLionel Sambuc          BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
436f4a2713aSLionel Sambuc       assert(!Base->isVirtual() && "should not have virtual bases here");
437f4a2713aSLionel Sambuc       const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
438f4a2713aSLionel Sambuc       CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
439f4a2713aSLionel Sambuc       Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
440f4a2713aSLionel Sambuc     }
441f4a2713aSLionel Sambuc     std::stable_sort(Bases.begin(), Bases.end());
442f4a2713aSLionel Sambuc 
443f4a2713aSLionel Sambuc     for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
444f4a2713aSLionel Sambuc       BaseInfo &Base = Bases[I];
445f4a2713aSLionel Sambuc 
446f4a2713aSLionel Sambuc       bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
447f4a2713aSLionel Sambuc       Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
448f4a2713aSLionel Sambuc             VTableClass, Offset + Base.Offset);
449f4a2713aSLionel Sambuc     }
450f4a2713aSLionel Sambuc   }
451f4a2713aSLionel Sambuc 
452f4a2713aSLionel Sambuc   unsigned FieldNo = 0;
453f4a2713aSLionel Sambuc   uint64_t OffsetBits = CGM.getContext().toBits(Offset);
454f4a2713aSLionel Sambuc 
455f4a2713aSLionel Sambuc   for (RecordDecl::field_iterator Field = RD->field_begin(),
456f4a2713aSLionel Sambuc        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
457f4a2713aSLionel Sambuc     // If this is a union, skip all the fields that aren't being initialized.
458f4a2713aSLionel Sambuc     if (RD->isUnion() && Val.getUnionField() != *Field)
459f4a2713aSLionel Sambuc       continue;
460f4a2713aSLionel Sambuc 
461f4a2713aSLionel Sambuc     // Don't emit anonymous bitfields, they just affect layout.
462f4a2713aSLionel Sambuc     if (Field->isUnnamedBitfield())
463f4a2713aSLionel Sambuc       continue;
464f4a2713aSLionel Sambuc 
465f4a2713aSLionel Sambuc     // Emit the value of the initializer.
466f4a2713aSLionel Sambuc     const APValue &FieldValue =
467f4a2713aSLionel Sambuc       RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
468f4a2713aSLionel Sambuc     llvm::Constant *EltInit =
469f4a2713aSLionel Sambuc       CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF);
470f4a2713aSLionel Sambuc     assert(EltInit && "EmitConstantValue can't fail");
471f4a2713aSLionel Sambuc 
472f4a2713aSLionel Sambuc     if (!Field->isBitField()) {
473f4a2713aSLionel Sambuc       // Handle non-bitfield members.
474f4a2713aSLionel Sambuc       AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
475f4a2713aSLionel Sambuc     } else {
476f4a2713aSLionel Sambuc       // Otherwise we have a bitfield.
477f4a2713aSLionel Sambuc       AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
478f4a2713aSLionel Sambuc                      cast<llvm::ConstantInt>(EltInit));
479f4a2713aSLionel Sambuc     }
480f4a2713aSLionel Sambuc   }
481f4a2713aSLionel Sambuc }
482f4a2713aSLionel Sambuc 
Finalize(QualType Ty)483f4a2713aSLionel Sambuc llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
484f4a2713aSLionel Sambuc   RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
485f4a2713aSLionel Sambuc   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
486f4a2713aSLionel Sambuc 
487f4a2713aSLionel Sambuc   CharUnits LayoutSizeInChars = Layout.getSize();
488f4a2713aSLionel Sambuc 
489f4a2713aSLionel Sambuc   if (NextFieldOffsetInChars > LayoutSizeInChars) {
490f4a2713aSLionel Sambuc     // If the struct is bigger than the size of the record type,
491f4a2713aSLionel Sambuc     // we must have a flexible array member at the end.
492f4a2713aSLionel Sambuc     assert(RD->hasFlexibleArrayMember() &&
493f4a2713aSLionel Sambuc            "Must have flexible array member if struct is bigger than type!");
494f4a2713aSLionel Sambuc 
495f4a2713aSLionel Sambuc     // No tail padding is necessary.
496f4a2713aSLionel Sambuc   } else {
497f4a2713aSLionel Sambuc     // Append tail padding if necessary.
498*0a6a1f1dSLionel Sambuc     CharUnits LLVMSizeInChars =
499*0a6a1f1dSLionel Sambuc         NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
500*0a6a1f1dSLionel Sambuc 
501*0a6a1f1dSLionel Sambuc     if (LLVMSizeInChars != LayoutSizeInChars)
502f4a2713aSLionel Sambuc       AppendTailPadding(LayoutSizeInChars);
503f4a2713aSLionel Sambuc 
504*0a6a1f1dSLionel Sambuc     LLVMSizeInChars =
505f4a2713aSLionel Sambuc         NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
506f4a2713aSLionel Sambuc 
507f4a2713aSLionel Sambuc     // Check if we need to convert the struct to a packed struct.
508f4a2713aSLionel Sambuc     if (NextFieldOffsetInChars <= LayoutSizeInChars &&
509f4a2713aSLionel Sambuc         LLVMSizeInChars > LayoutSizeInChars) {
510f4a2713aSLionel Sambuc       assert(!Packed && "Size mismatch!");
511f4a2713aSLionel Sambuc 
512f4a2713aSLionel Sambuc       ConvertStructToPacked();
513f4a2713aSLionel Sambuc       assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
514f4a2713aSLionel Sambuc              "Converting to packed did not help!");
515f4a2713aSLionel Sambuc     }
516f4a2713aSLionel Sambuc 
517*0a6a1f1dSLionel Sambuc     LLVMSizeInChars =
518*0a6a1f1dSLionel Sambuc         NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
519*0a6a1f1dSLionel Sambuc 
520*0a6a1f1dSLionel Sambuc     assert(LayoutSizeInChars == LLVMSizeInChars &&
521f4a2713aSLionel Sambuc            "Tail padding mismatch!");
522f4a2713aSLionel Sambuc   }
523f4a2713aSLionel Sambuc 
524f4a2713aSLionel Sambuc   // Pick the type to use.  If the type is layout identical to the ConvertType
525f4a2713aSLionel Sambuc   // type then use it, otherwise use whatever the builder produced for us.
526f4a2713aSLionel Sambuc   llvm::StructType *STy =
527f4a2713aSLionel Sambuc       llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
528f4a2713aSLionel Sambuc                                                Elements, Packed);
529f4a2713aSLionel Sambuc   llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
530f4a2713aSLionel Sambuc   if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
531f4a2713aSLionel Sambuc     if (ValSTy->isLayoutIdentical(STy))
532f4a2713aSLionel Sambuc       STy = ValSTy;
533f4a2713aSLionel Sambuc   }
534f4a2713aSLionel Sambuc 
535f4a2713aSLionel Sambuc   llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
536f4a2713aSLionel Sambuc 
537f4a2713aSLionel Sambuc   assert(NextFieldOffsetInChars.RoundUpToAlignment(getAlignment(Result)) ==
538f4a2713aSLionel Sambuc          getSizeInChars(Result) && "Size mismatch!");
539f4a2713aSLionel Sambuc 
540f4a2713aSLionel Sambuc   return Result;
541f4a2713aSLionel Sambuc }
542f4a2713aSLionel Sambuc 
BuildStruct(CodeGenModule & CGM,CodeGenFunction * CGF,InitListExpr * ILE)543f4a2713aSLionel Sambuc llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
544f4a2713aSLionel Sambuc                                                 CodeGenFunction *CGF,
545f4a2713aSLionel Sambuc                                                 InitListExpr *ILE) {
546f4a2713aSLionel Sambuc   ConstStructBuilder Builder(CGM, CGF);
547f4a2713aSLionel Sambuc 
548f4a2713aSLionel Sambuc   if (!Builder.Build(ILE))
549*0a6a1f1dSLionel Sambuc     return nullptr;
550f4a2713aSLionel Sambuc 
551f4a2713aSLionel Sambuc   return Builder.Finalize(ILE->getType());
552f4a2713aSLionel Sambuc }
553f4a2713aSLionel Sambuc 
BuildStruct(CodeGenModule & CGM,CodeGenFunction * CGF,const APValue & Val,QualType ValTy)554f4a2713aSLionel Sambuc llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
555f4a2713aSLionel Sambuc                                                 CodeGenFunction *CGF,
556f4a2713aSLionel Sambuc                                                 const APValue &Val,
557f4a2713aSLionel Sambuc                                                 QualType ValTy) {
558f4a2713aSLionel Sambuc   ConstStructBuilder Builder(CGM, CGF);
559f4a2713aSLionel Sambuc 
560f4a2713aSLionel Sambuc   const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
561f4a2713aSLionel Sambuc   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
562f4a2713aSLionel Sambuc   Builder.Build(Val, RD, false, CD, CharUnits::Zero());
563f4a2713aSLionel Sambuc 
564f4a2713aSLionel Sambuc   return Builder.Finalize(ValTy);
565f4a2713aSLionel Sambuc }
566f4a2713aSLionel Sambuc 
567f4a2713aSLionel Sambuc 
568f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
569f4a2713aSLionel Sambuc //                             ConstExprEmitter
570f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
571f4a2713aSLionel Sambuc 
572f4a2713aSLionel Sambuc /// This class only needs to handle two cases:
573f4a2713aSLionel Sambuc /// 1) Literals (this is used by APValue emission to emit literals).
574f4a2713aSLionel Sambuc /// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
575f4a2713aSLionel Sambuc ///    constant fold these types).
576f4a2713aSLionel Sambuc class ConstExprEmitter :
577f4a2713aSLionel Sambuc   public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
578f4a2713aSLionel Sambuc   CodeGenModule &CGM;
579f4a2713aSLionel Sambuc   CodeGenFunction *CGF;
580f4a2713aSLionel Sambuc   llvm::LLVMContext &VMContext;
581f4a2713aSLionel Sambuc public:
ConstExprEmitter(CodeGenModule & cgm,CodeGenFunction * cgf)582f4a2713aSLionel Sambuc   ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
583f4a2713aSLionel Sambuc     : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
584f4a2713aSLionel Sambuc   }
585f4a2713aSLionel Sambuc 
586f4a2713aSLionel Sambuc   //===--------------------------------------------------------------------===//
587f4a2713aSLionel Sambuc   //                            Visitor Methods
588f4a2713aSLionel Sambuc   //===--------------------------------------------------------------------===//
589f4a2713aSLionel Sambuc 
VisitStmt(Stmt * S)590f4a2713aSLionel Sambuc   llvm::Constant *VisitStmt(Stmt *S) {
591*0a6a1f1dSLionel Sambuc     return nullptr;
592f4a2713aSLionel Sambuc   }
593f4a2713aSLionel Sambuc 
VisitParenExpr(ParenExpr * PE)594f4a2713aSLionel Sambuc   llvm::Constant *VisitParenExpr(ParenExpr *PE) {
595f4a2713aSLionel Sambuc     return Visit(PE->getSubExpr());
596f4a2713aSLionel Sambuc   }
597f4a2713aSLionel Sambuc 
598f4a2713aSLionel Sambuc   llvm::Constant *
VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr * PE)599f4a2713aSLionel Sambuc   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
600f4a2713aSLionel Sambuc     return Visit(PE->getReplacement());
601f4a2713aSLionel Sambuc   }
602f4a2713aSLionel Sambuc 
VisitGenericSelectionExpr(GenericSelectionExpr * GE)603f4a2713aSLionel Sambuc   llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
604f4a2713aSLionel Sambuc     return Visit(GE->getResultExpr());
605f4a2713aSLionel Sambuc   }
606f4a2713aSLionel Sambuc 
VisitChooseExpr(ChooseExpr * CE)607f4a2713aSLionel Sambuc   llvm::Constant *VisitChooseExpr(ChooseExpr *CE) {
608f4a2713aSLionel Sambuc     return Visit(CE->getChosenSubExpr());
609f4a2713aSLionel Sambuc   }
610f4a2713aSLionel Sambuc 
VisitCompoundLiteralExpr(CompoundLiteralExpr * E)611f4a2713aSLionel Sambuc   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
612f4a2713aSLionel Sambuc     return Visit(E->getInitializer());
613f4a2713aSLionel Sambuc   }
614f4a2713aSLionel Sambuc 
VisitCastExpr(CastExpr * E)615f4a2713aSLionel Sambuc   llvm::Constant *VisitCastExpr(CastExpr* E) {
616f4a2713aSLionel Sambuc     Expr *subExpr = E->getSubExpr();
617f4a2713aSLionel Sambuc     llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF);
618*0a6a1f1dSLionel Sambuc     if (!C) return nullptr;
619f4a2713aSLionel Sambuc 
620f4a2713aSLionel Sambuc     llvm::Type *destType = ConvertType(E->getType());
621f4a2713aSLionel Sambuc 
622f4a2713aSLionel Sambuc     switch (E->getCastKind()) {
623f4a2713aSLionel Sambuc     case CK_ToUnion: {
624f4a2713aSLionel Sambuc       // GCC cast to union extension
625f4a2713aSLionel Sambuc       assert(E->getType()->isUnionType() &&
626f4a2713aSLionel Sambuc              "Destination type is not union type!");
627f4a2713aSLionel Sambuc 
628f4a2713aSLionel Sambuc       // Build a struct with the union sub-element as the first member,
629f4a2713aSLionel Sambuc       // and padded to the appropriate size
630f4a2713aSLionel Sambuc       SmallVector<llvm::Constant*, 2> Elts;
631f4a2713aSLionel Sambuc       SmallVector<llvm::Type*, 2> Types;
632f4a2713aSLionel Sambuc       Elts.push_back(C);
633f4a2713aSLionel Sambuc       Types.push_back(C->getType());
634f4a2713aSLionel Sambuc       unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
635f4a2713aSLionel Sambuc       unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destType);
636f4a2713aSLionel Sambuc 
637f4a2713aSLionel Sambuc       assert(CurSize <= TotalSize && "Union size mismatch!");
638f4a2713aSLionel Sambuc       if (unsigned NumPadBytes = TotalSize - CurSize) {
639f4a2713aSLionel Sambuc         llvm::Type *Ty = CGM.Int8Ty;
640f4a2713aSLionel Sambuc         if (NumPadBytes > 1)
641f4a2713aSLionel Sambuc           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
642f4a2713aSLionel Sambuc 
643f4a2713aSLionel Sambuc         Elts.push_back(llvm::UndefValue::get(Ty));
644f4a2713aSLionel Sambuc         Types.push_back(Ty);
645f4a2713aSLionel Sambuc       }
646f4a2713aSLionel Sambuc 
647f4a2713aSLionel Sambuc       llvm::StructType* STy =
648f4a2713aSLionel Sambuc         llvm::StructType::get(C->getType()->getContext(), Types, false);
649f4a2713aSLionel Sambuc       return llvm::ConstantStruct::get(STy, Elts);
650f4a2713aSLionel Sambuc     }
651f4a2713aSLionel Sambuc 
652*0a6a1f1dSLionel Sambuc     case CK_AddressSpaceConversion:
653*0a6a1f1dSLionel Sambuc       return llvm::ConstantExpr::getAddrSpaceCast(C, destType);
654*0a6a1f1dSLionel Sambuc 
655f4a2713aSLionel Sambuc     case CK_LValueToRValue:
656f4a2713aSLionel Sambuc     case CK_AtomicToNonAtomic:
657f4a2713aSLionel Sambuc     case CK_NonAtomicToAtomic:
658f4a2713aSLionel Sambuc     case CK_NoOp:
659f4a2713aSLionel Sambuc     case CK_ConstructorConversion:
660f4a2713aSLionel Sambuc       return C;
661f4a2713aSLionel Sambuc 
662f4a2713aSLionel Sambuc     case CK_Dependent: llvm_unreachable("saw dependent cast!");
663f4a2713aSLionel Sambuc 
664f4a2713aSLionel Sambuc     case CK_BuiltinFnToFnPtr:
665f4a2713aSLionel Sambuc       llvm_unreachable("builtin functions are handled elsewhere");
666f4a2713aSLionel Sambuc 
667f4a2713aSLionel Sambuc     case CK_ReinterpretMemberPointer:
668f4a2713aSLionel Sambuc     case CK_DerivedToBaseMemberPointer:
669f4a2713aSLionel Sambuc     case CK_BaseToDerivedMemberPointer:
670f4a2713aSLionel Sambuc       return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
671f4a2713aSLionel Sambuc 
672f4a2713aSLionel Sambuc     // These will never be supported.
673f4a2713aSLionel Sambuc     case CK_ObjCObjectLValueCast:
674f4a2713aSLionel Sambuc     case CK_ARCProduceObject:
675f4a2713aSLionel Sambuc     case CK_ARCConsumeObject:
676f4a2713aSLionel Sambuc     case CK_ARCReclaimReturnedObject:
677f4a2713aSLionel Sambuc     case CK_ARCExtendBlockObject:
678f4a2713aSLionel Sambuc     case CK_CopyAndAutoreleaseBlockObject:
679*0a6a1f1dSLionel Sambuc       return nullptr;
680f4a2713aSLionel Sambuc 
681f4a2713aSLionel Sambuc     // These don't need to be handled here because Evaluate knows how to
682f4a2713aSLionel Sambuc     // evaluate them in the cases where they can be folded.
683f4a2713aSLionel Sambuc     case CK_BitCast:
684f4a2713aSLionel Sambuc     case CK_ToVoid:
685f4a2713aSLionel Sambuc     case CK_Dynamic:
686f4a2713aSLionel Sambuc     case CK_LValueBitCast:
687f4a2713aSLionel Sambuc     case CK_NullToMemberPointer:
688f4a2713aSLionel Sambuc     case CK_UserDefinedConversion:
689f4a2713aSLionel Sambuc     case CK_CPointerToObjCPointerCast:
690f4a2713aSLionel Sambuc     case CK_BlockPointerToObjCPointerCast:
691f4a2713aSLionel Sambuc     case CK_AnyPointerToBlockPointerCast:
692f4a2713aSLionel Sambuc     case CK_ArrayToPointerDecay:
693f4a2713aSLionel Sambuc     case CK_FunctionToPointerDecay:
694f4a2713aSLionel Sambuc     case CK_BaseToDerived:
695f4a2713aSLionel Sambuc     case CK_DerivedToBase:
696f4a2713aSLionel Sambuc     case CK_UncheckedDerivedToBase:
697f4a2713aSLionel Sambuc     case CK_MemberPointerToBoolean:
698f4a2713aSLionel Sambuc     case CK_VectorSplat:
699f4a2713aSLionel Sambuc     case CK_FloatingRealToComplex:
700f4a2713aSLionel Sambuc     case CK_FloatingComplexToReal:
701f4a2713aSLionel Sambuc     case CK_FloatingComplexToBoolean:
702f4a2713aSLionel Sambuc     case CK_FloatingComplexCast:
703f4a2713aSLionel Sambuc     case CK_FloatingComplexToIntegralComplex:
704f4a2713aSLionel Sambuc     case CK_IntegralRealToComplex:
705f4a2713aSLionel Sambuc     case CK_IntegralComplexToReal:
706f4a2713aSLionel Sambuc     case CK_IntegralComplexToBoolean:
707f4a2713aSLionel Sambuc     case CK_IntegralComplexCast:
708f4a2713aSLionel Sambuc     case CK_IntegralComplexToFloatingComplex:
709f4a2713aSLionel Sambuc     case CK_PointerToIntegral:
710f4a2713aSLionel Sambuc     case CK_PointerToBoolean:
711f4a2713aSLionel Sambuc     case CK_NullToPointer:
712f4a2713aSLionel Sambuc     case CK_IntegralCast:
713f4a2713aSLionel Sambuc     case CK_IntegralToPointer:
714f4a2713aSLionel Sambuc     case CK_IntegralToBoolean:
715f4a2713aSLionel Sambuc     case CK_IntegralToFloating:
716f4a2713aSLionel Sambuc     case CK_FloatingToIntegral:
717f4a2713aSLionel Sambuc     case CK_FloatingToBoolean:
718f4a2713aSLionel Sambuc     case CK_FloatingCast:
719f4a2713aSLionel Sambuc     case CK_ZeroToOCLEvent:
720*0a6a1f1dSLionel Sambuc       return nullptr;
721f4a2713aSLionel Sambuc     }
722f4a2713aSLionel Sambuc     llvm_unreachable("Invalid CastKind");
723f4a2713aSLionel Sambuc   }
724f4a2713aSLionel Sambuc 
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * DAE)725f4a2713aSLionel Sambuc   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
726f4a2713aSLionel Sambuc     return Visit(DAE->getExpr());
727f4a2713aSLionel Sambuc   }
728f4a2713aSLionel Sambuc 
VisitCXXDefaultInitExpr(CXXDefaultInitExpr * DIE)729f4a2713aSLionel Sambuc   llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
730f4a2713aSLionel Sambuc     // No need for a DefaultInitExprScope: we don't handle 'this' in a
731f4a2713aSLionel Sambuc     // constant expression.
732f4a2713aSLionel Sambuc     return Visit(DIE->getExpr());
733f4a2713aSLionel Sambuc   }
734f4a2713aSLionel Sambuc 
VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr * E)735f4a2713aSLionel Sambuc   llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
736f4a2713aSLionel Sambuc     return Visit(E->GetTemporaryExpr());
737f4a2713aSLionel Sambuc   }
738f4a2713aSLionel Sambuc 
EmitArrayInitialization(InitListExpr * ILE)739f4a2713aSLionel Sambuc   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
740f4a2713aSLionel Sambuc     if (ILE->isStringLiteralInit())
741f4a2713aSLionel Sambuc       return Visit(ILE->getInit(0));
742f4a2713aSLionel Sambuc 
743f4a2713aSLionel Sambuc     llvm::ArrayType *AType =
744f4a2713aSLionel Sambuc         cast<llvm::ArrayType>(ConvertType(ILE->getType()));
745f4a2713aSLionel Sambuc     llvm::Type *ElemTy = AType->getElementType();
746f4a2713aSLionel Sambuc     unsigned NumInitElements = ILE->getNumInits();
747f4a2713aSLionel Sambuc     unsigned NumElements = AType->getNumElements();
748f4a2713aSLionel Sambuc 
749f4a2713aSLionel Sambuc     // Initialising an array requires us to automatically
750f4a2713aSLionel Sambuc     // initialise any elements that have not been initialised explicitly
751f4a2713aSLionel Sambuc     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
752f4a2713aSLionel Sambuc 
753*0a6a1f1dSLionel Sambuc     // Initialize remaining array elements.
754*0a6a1f1dSLionel Sambuc     // FIXME: This doesn't handle member pointers correctly!
755*0a6a1f1dSLionel Sambuc     llvm::Constant *fillC;
756*0a6a1f1dSLionel Sambuc     if (Expr *filler = ILE->getArrayFiller())
757*0a6a1f1dSLionel Sambuc       fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
758*0a6a1f1dSLionel Sambuc     else
759*0a6a1f1dSLionel Sambuc       fillC = llvm::Constant::getNullValue(ElemTy);
760*0a6a1f1dSLionel Sambuc     if (!fillC)
761*0a6a1f1dSLionel Sambuc       return nullptr;
762*0a6a1f1dSLionel Sambuc 
763*0a6a1f1dSLionel Sambuc     // Try to use a ConstantAggregateZero if we can.
764*0a6a1f1dSLionel Sambuc     if (fillC->isNullValue() && !NumInitableElts)
765*0a6a1f1dSLionel Sambuc       return llvm::ConstantAggregateZero::get(AType);
766*0a6a1f1dSLionel Sambuc 
767f4a2713aSLionel Sambuc     // Copy initializer elements.
768f4a2713aSLionel Sambuc     std::vector<llvm::Constant*> Elts;
769f4a2713aSLionel Sambuc     Elts.reserve(NumInitableElts + NumElements);
770f4a2713aSLionel Sambuc 
771f4a2713aSLionel Sambuc     bool RewriteType = false;
772f4a2713aSLionel Sambuc     for (unsigned i = 0; i < NumInitableElts; ++i) {
773f4a2713aSLionel Sambuc       Expr *Init = ILE->getInit(i);
774f4a2713aSLionel Sambuc       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
775f4a2713aSLionel Sambuc       if (!C)
776*0a6a1f1dSLionel Sambuc         return nullptr;
777f4a2713aSLionel Sambuc       RewriteType |= (C->getType() != ElemTy);
778f4a2713aSLionel Sambuc       Elts.push_back(C);
779f4a2713aSLionel Sambuc     }
780f4a2713aSLionel Sambuc 
781f4a2713aSLionel Sambuc     RewriteType |= (fillC->getType() != ElemTy);
782f4a2713aSLionel Sambuc     Elts.resize(NumElements, fillC);
783f4a2713aSLionel Sambuc 
784f4a2713aSLionel Sambuc     if (RewriteType) {
785f4a2713aSLionel Sambuc       // FIXME: Try to avoid packing the array
786f4a2713aSLionel Sambuc       std::vector<llvm::Type*> Types;
787f4a2713aSLionel Sambuc       Types.reserve(NumInitableElts + NumElements);
788f4a2713aSLionel Sambuc       for (unsigned i = 0, e = Elts.size(); i < e; ++i)
789f4a2713aSLionel Sambuc         Types.push_back(Elts[i]->getType());
790f4a2713aSLionel Sambuc       llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
791f4a2713aSLionel Sambuc                                                             Types, true);
792f4a2713aSLionel Sambuc       return llvm::ConstantStruct::get(SType, Elts);
793f4a2713aSLionel Sambuc     }
794f4a2713aSLionel Sambuc 
795f4a2713aSLionel Sambuc     return llvm::ConstantArray::get(AType, Elts);
796f4a2713aSLionel Sambuc   }
797f4a2713aSLionel Sambuc 
EmitRecordInitialization(InitListExpr * ILE)798f4a2713aSLionel Sambuc   llvm::Constant *EmitRecordInitialization(InitListExpr *ILE) {
799f4a2713aSLionel Sambuc     return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
800f4a2713aSLionel Sambuc   }
801f4a2713aSLionel Sambuc 
VisitImplicitValueInitExpr(ImplicitValueInitExpr * E)802f4a2713aSLionel Sambuc   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
803f4a2713aSLionel Sambuc     return CGM.EmitNullConstant(E->getType());
804f4a2713aSLionel Sambuc   }
805f4a2713aSLionel Sambuc 
VisitInitListExpr(InitListExpr * ILE)806f4a2713aSLionel Sambuc   llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
807f4a2713aSLionel Sambuc     if (ILE->getType()->isArrayType())
808f4a2713aSLionel Sambuc       return EmitArrayInitialization(ILE);
809f4a2713aSLionel Sambuc 
810f4a2713aSLionel Sambuc     if (ILE->getType()->isRecordType())
811f4a2713aSLionel Sambuc       return EmitRecordInitialization(ILE);
812f4a2713aSLionel Sambuc 
813*0a6a1f1dSLionel Sambuc     return nullptr;
814f4a2713aSLionel Sambuc   }
815f4a2713aSLionel Sambuc 
VisitCXXConstructExpr(CXXConstructExpr * E)816f4a2713aSLionel Sambuc   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
817f4a2713aSLionel Sambuc     if (!E->getConstructor()->isTrivial())
818*0a6a1f1dSLionel Sambuc       return nullptr;
819f4a2713aSLionel Sambuc 
820f4a2713aSLionel Sambuc     QualType Ty = E->getType();
821f4a2713aSLionel Sambuc 
822f4a2713aSLionel Sambuc     // FIXME: We should not have to call getBaseElementType here.
823f4a2713aSLionel Sambuc     const RecordType *RT =
824f4a2713aSLionel Sambuc       CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
825f4a2713aSLionel Sambuc     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
826f4a2713aSLionel Sambuc 
827f4a2713aSLionel Sambuc     // If the class doesn't have a trivial destructor, we can't emit it as a
828f4a2713aSLionel Sambuc     // constant expr.
829f4a2713aSLionel Sambuc     if (!RD->hasTrivialDestructor())
830*0a6a1f1dSLionel Sambuc       return nullptr;
831f4a2713aSLionel Sambuc 
832f4a2713aSLionel Sambuc     // Only copy and default constructors can be trivial.
833f4a2713aSLionel Sambuc 
834f4a2713aSLionel Sambuc 
835f4a2713aSLionel Sambuc     if (E->getNumArgs()) {
836f4a2713aSLionel Sambuc       assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
837f4a2713aSLionel Sambuc       assert(E->getConstructor()->isCopyOrMoveConstructor() &&
838f4a2713aSLionel Sambuc              "trivial ctor has argument but isn't a copy/move ctor");
839f4a2713aSLionel Sambuc 
840f4a2713aSLionel Sambuc       Expr *Arg = E->getArg(0);
841f4a2713aSLionel Sambuc       assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
842f4a2713aSLionel Sambuc              "argument to copy ctor is of wrong type");
843f4a2713aSLionel Sambuc 
844f4a2713aSLionel Sambuc       return Visit(Arg);
845f4a2713aSLionel Sambuc     }
846f4a2713aSLionel Sambuc 
847f4a2713aSLionel Sambuc     return CGM.EmitNullConstant(Ty);
848f4a2713aSLionel Sambuc   }
849f4a2713aSLionel Sambuc 
VisitStringLiteral(StringLiteral * E)850f4a2713aSLionel Sambuc   llvm::Constant *VisitStringLiteral(StringLiteral *E) {
851f4a2713aSLionel Sambuc     return CGM.GetConstantArrayFromStringLiteral(E);
852f4a2713aSLionel Sambuc   }
853f4a2713aSLionel Sambuc 
VisitObjCEncodeExpr(ObjCEncodeExpr * E)854f4a2713aSLionel Sambuc   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
855f4a2713aSLionel Sambuc     // This must be an @encode initializing an array in a static initializer.
856f4a2713aSLionel Sambuc     // Don't emit it as the address of the string, emit the string data itself
857f4a2713aSLionel Sambuc     // as an inline array.
858f4a2713aSLionel Sambuc     std::string Str;
859f4a2713aSLionel Sambuc     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
860*0a6a1f1dSLionel Sambuc     QualType T = E->getType();
861*0a6a1f1dSLionel Sambuc     if (T->getTypeClass() == Type::TypeOfExpr)
862*0a6a1f1dSLionel Sambuc       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
863*0a6a1f1dSLionel Sambuc     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
864f4a2713aSLionel Sambuc 
865f4a2713aSLionel Sambuc     // Resize the string to the right size, adding zeros at the end, or
866f4a2713aSLionel Sambuc     // truncating as needed.
867f4a2713aSLionel Sambuc     Str.resize(CAT->getSize().getZExtValue(), '\0');
868f4a2713aSLionel Sambuc     return llvm::ConstantDataArray::getString(VMContext, Str, false);
869f4a2713aSLionel Sambuc   }
870f4a2713aSLionel Sambuc 
VisitUnaryExtension(const UnaryOperator * E)871f4a2713aSLionel Sambuc   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
872f4a2713aSLionel Sambuc     return Visit(E->getSubExpr());
873f4a2713aSLionel Sambuc   }
874f4a2713aSLionel Sambuc 
875f4a2713aSLionel Sambuc   // Utility methods
ConvertType(QualType T)876f4a2713aSLionel Sambuc   llvm::Type *ConvertType(QualType T) {
877f4a2713aSLionel Sambuc     return CGM.getTypes().ConvertType(T);
878f4a2713aSLionel Sambuc   }
879f4a2713aSLionel Sambuc 
880f4a2713aSLionel Sambuc public:
EmitLValue(APValue::LValueBase LVBase)881f4a2713aSLionel Sambuc   llvm::Constant *EmitLValue(APValue::LValueBase LVBase) {
882f4a2713aSLionel Sambuc     if (const ValueDecl *Decl = LVBase.dyn_cast<const ValueDecl*>()) {
883f4a2713aSLionel Sambuc       if (Decl->hasAttr<WeakRefAttr>())
884f4a2713aSLionel Sambuc         return CGM.GetWeakRefReference(Decl);
885f4a2713aSLionel Sambuc       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
886f4a2713aSLionel Sambuc         return CGM.GetAddrOfFunction(FD);
887f4a2713aSLionel Sambuc       if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
888f4a2713aSLionel Sambuc         // We can never refer to a variable with local storage.
889f4a2713aSLionel Sambuc         if (!VD->hasLocalStorage()) {
890f4a2713aSLionel Sambuc           if (VD->isFileVarDecl() || VD->hasExternalStorage())
891f4a2713aSLionel Sambuc             return CGM.GetAddrOfGlobalVar(VD);
892f4a2713aSLionel Sambuc           else if (VD->isLocalVarDecl())
893*0a6a1f1dSLionel Sambuc             return CGM.getOrCreateStaticVarDecl(
894*0a6a1f1dSLionel Sambuc                 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
895f4a2713aSLionel Sambuc         }
896f4a2713aSLionel Sambuc       }
897*0a6a1f1dSLionel Sambuc       return nullptr;
898f4a2713aSLionel Sambuc     }
899f4a2713aSLionel Sambuc 
900f4a2713aSLionel Sambuc     Expr *E = const_cast<Expr*>(LVBase.get<const Expr*>());
901f4a2713aSLionel Sambuc     switch (E->getStmtClass()) {
902f4a2713aSLionel Sambuc     default: break;
903f4a2713aSLionel Sambuc     case Expr::CompoundLiteralExprClass: {
904f4a2713aSLionel Sambuc       // Note that due to the nature of compound literals, this is guaranteed
905f4a2713aSLionel Sambuc       // to be the only use of the variable, so we just generate it here.
906f4a2713aSLionel Sambuc       CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
907f4a2713aSLionel Sambuc       llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(),
908f4a2713aSLionel Sambuc                                                CLE->getType(), CGF);
909f4a2713aSLionel Sambuc       // FIXME: "Leaked" on failure.
910f4a2713aSLionel Sambuc       if (C)
911f4a2713aSLionel Sambuc         C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
912f4a2713aSLionel Sambuc                                      E->getType().isConstant(CGM.getContext()),
913f4a2713aSLionel Sambuc                                      llvm::GlobalValue::InternalLinkage,
914*0a6a1f1dSLionel Sambuc                                      C, ".compoundliteral", nullptr,
915f4a2713aSLionel Sambuc                                      llvm::GlobalVariable::NotThreadLocal,
916f4a2713aSLionel Sambuc                           CGM.getContext().getTargetAddressSpace(E->getType()));
917f4a2713aSLionel Sambuc       return C;
918f4a2713aSLionel Sambuc     }
919f4a2713aSLionel Sambuc     case Expr::StringLiteralClass:
920f4a2713aSLionel Sambuc       return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
921f4a2713aSLionel Sambuc     case Expr::ObjCEncodeExprClass:
922f4a2713aSLionel Sambuc       return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
923f4a2713aSLionel Sambuc     case Expr::ObjCStringLiteralClass: {
924f4a2713aSLionel Sambuc       ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
925f4a2713aSLionel Sambuc       llvm::Constant *C =
926f4a2713aSLionel Sambuc           CGM.getObjCRuntime().GenerateConstantString(SL->getString());
927f4a2713aSLionel Sambuc       return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
928f4a2713aSLionel Sambuc     }
929f4a2713aSLionel Sambuc     case Expr::PredefinedExprClass: {
930f4a2713aSLionel Sambuc       unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
931f4a2713aSLionel Sambuc       if (CGF) {
932f4a2713aSLionel Sambuc         LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E));
933f4a2713aSLionel Sambuc         return cast<llvm::Constant>(Res.getAddress());
934f4a2713aSLionel Sambuc       } else if (Type == PredefinedExpr::PrettyFunction) {
935f4a2713aSLionel Sambuc         return CGM.GetAddrOfConstantCString("top level", ".tmp");
936f4a2713aSLionel Sambuc       }
937f4a2713aSLionel Sambuc 
938f4a2713aSLionel Sambuc       return CGM.GetAddrOfConstantCString("", ".tmp");
939f4a2713aSLionel Sambuc     }
940f4a2713aSLionel Sambuc     case Expr::AddrLabelExprClass: {
941f4a2713aSLionel Sambuc       assert(CGF && "Invalid address of label expression outside function.");
942f4a2713aSLionel Sambuc       llvm::Constant *Ptr =
943f4a2713aSLionel Sambuc         CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
944f4a2713aSLionel Sambuc       return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
945f4a2713aSLionel Sambuc     }
946f4a2713aSLionel Sambuc     case Expr::CallExprClass: {
947f4a2713aSLionel Sambuc       CallExpr* CE = cast<CallExpr>(E);
948*0a6a1f1dSLionel Sambuc       unsigned builtin = CE->getBuiltinCallee();
949f4a2713aSLionel Sambuc       if (builtin !=
950f4a2713aSLionel Sambuc             Builtin::BI__builtin___CFStringMakeConstantString &&
951f4a2713aSLionel Sambuc           builtin !=
952f4a2713aSLionel Sambuc             Builtin::BI__builtin___NSStringMakeConstantString)
953f4a2713aSLionel Sambuc         break;
954f4a2713aSLionel Sambuc       const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
955f4a2713aSLionel Sambuc       const StringLiteral *Literal = cast<StringLiteral>(Arg);
956f4a2713aSLionel Sambuc       if (builtin ==
957f4a2713aSLionel Sambuc             Builtin::BI__builtin___NSStringMakeConstantString) {
958f4a2713aSLionel Sambuc         return CGM.getObjCRuntime().GenerateConstantString(Literal);
959f4a2713aSLionel Sambuc       }
960f4a2713aSLionel Sambuc       // FIXME: need to deal with UCN conversion issues.
961f4a2713aSLionel Sambuc       return CGM.GetAddrOfConstantCFString(Literal);
962f4a2713aSLionel Sambuc     }
963f4a2713aSLionel Sambuc     case Expr::BlockExprClass: {
964f4a2713aSLionel Sambuc       std::string FunctionName;
965f4a2713aSLionel Sambuc       if (CGF)
966f4a2713aSLionel Sambuc         FunctionName = CGF->CurFn->getName();
967f4a2713aSLionel Sambuc       else
968f4a2713aSLionel Sambuc         FunctionName = "global";
969f4a2713aSLionel Sambuc 
970f4a2713aSLionel Sambuc       return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
971f4a2713aSLionel Sambuc     }
972f4a2713aSLionel Sambuc     case Expr::CXXTypeidExprClass: {
973f4a2713aSLionel Sambuc       CXXTypeidExpr *Typeid = cast<CXXTypeidExpr>(E);
974f4a2713aSLionel Sambuc       QualType T;
975f4a2713aSLionel Sambuc       if (Typeid->isTypeOperand())
976f4a2713aSLionel Sambuc         T = Typeid->getTypeOperand(CGM.getContext());
977f4a2713aSLionel Sambuc       else
978f4a2713aSLionel Sambuc         T = Typeid->getExprOperand()->getType();
979f4a2713aSLionel Sambuc       return CGM.GetAddrOfRTTIDescriptor(T);
980f4a2713aSLionel Sambuc     }
981f4a2713aSLionel Sambuc     case Expr::CXXUuidofExprClass: {
982f4a2713aSLionel Sambuc       return CGM.GetAddrOfUuidDescriptor(cast<CXXUuidofExpr>(E));
983f4a2713aSLionel Sambuc     }
984f4a2713aSLionel Sambuc     case Expr::MaterializeTemporaryExprClass: {
985f4a2713aSLionel Sambuc       MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
986f4a2713aSLionel Sambuc       assert(MTE->getStorageDuration() == SD_Static);
987f4a2713aSLionel Sambuc       SmallVector<const Expr *, 2> CommaLHSs;
988f4a2713aSLionel Sambuc       SmallVector<SubobjectAdjustment, 2> Adjustments;
989f4a2713aSLionel Sambuc       const Expr *Inner = MTE->GetTemporaryExpr()
990f4a2713aSLionel Sambuc           ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
991f4a2713aSLionel Sambuc       return CGM.GetAddrOfGlobalTemporary(MTE, Inner);
992f4a2713aSLionel Sambuc     }
993f4a2713aSLionel Sambuc     }
994f4a2713aSLionel Sambuc 
995*0a6a1f1dSLionel Sambuc     return nullptr;
996f4a2713aSLionel Sambuc   }
997f4a2713aSLionel Sambuc };
998f4a2713aSLionel Sambuc 
999f4a2713aSLionel Sambuc }  // end anonymous namespace.
1000f4a2713aSLionel Sambuc 
EmitConstantInit(const VarDecl & D,CodeGenFunction * CGF)1001f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D,
1002f4a2713aSLionel Sambuc                                                 CodeGenFunction *CGF) {
1003f4a2713aSLionel Sambuc   // Make a quick check if variable can be default NULL initialized
1004f4a2713aSLionel Sambuc   // and avoid going through rest of code which may do, for c++11,
1005f4a2713aSLionel Sambuc   // initialization of memory to all NULLs.
1006f4a2713aSLionel Sambuc   if (!D.hasLocalStorage()) {
1007f4a2713aSLionel Sambuc     QualType Ty = D.getType();
1008f4a2713aSLionel Sambuc     if (Ty->isArrayType())
1009f4a2713aSLionel Sambuc       Ty = Context.getBaseElementType(Ty);
1010f4a2713aSLionel Sambuc     if (Ty->isRecordType())
1011f4a2713aSLionel Sambuc       if (const CXXConstructExpr *E =
1012f4a2713aSLionel Sambuc           dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1013f4a2713aSLionel Sambuc         const CXXConstructorDecl *CD = E->getConstructor();
1014f4a2713aSLionel Sambuc         if (CD->isTrivial() && CD->isDefaultConstructor())
1015f4a2713aSLionel Sambuc           return EmitNullConstant(D.getType());
1016f4a2713aSLionel Sambuc       }
1017f4a2713aSLionel Sambuc   }
1018f4a2713aSLionel Sambuc 
1019f4a2713aSLionel Sambuc   if (const APValue *Value = D.evaluateValue())
1020f4a2713aSLionel Sambuc     return EmitConstantValueForMemory(*Value, D.getType(), CGF);
1021f4a2713aSLionel Sambuc 
1022f4a2713aSLionel Sambuc   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1023f4a2713aSLionel Sambuc   // reference is a constant expression, and the reference binds to a temporary,
1024f4a2713aSLionel Sambuc   // then constant initialization is performed. ConstExprEmitter will
1025f4a2713aSLionel Sambuc   // incorrectly emit a prvalue constant in this case, and the calling code
1026f4a2713aSLionel Sambuc   // interprets that as the (pointer) value of the reference, rather than the
1027f4a2713aSLionel Sambuc   // desired value of the referee.
1028f4a2713aSLionel Sambuc   if (D.getType()->isReferenceType())
1029*0a6a1f1dSLionel Sambuc     return nullptr;
1030f4a2713aSLionel Sambuc 
1031f4a2713aSLionel Sambuc   const Expr *E = D.getInit();
1032f4a2713aSLionel Sambuc   assert(E && "No initializer to emit");
1033f4a2713aSLionel Sambuc 
1034f4a2713aSLionel Sambuc   llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
1035f4a2713aSLionel Sambuc   if (C && C->getType()->isIntegerTy(1)) {
1036f4a2713aSLionel Sambuc     llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
1037f4a2713aSLionel Sambuc     C = llvm::ConstantExpr::getZExt(C, BoolTy);
1038f4a2713aSLionel Sambuc   }
1039f4a2713aSLionel Sambuc   return C;
1040f4a2713aSLionel Sambuc }
1041f4a2713aSLionel Sambuc 
EmitConstantExpr(const Expr * E,QualType DestType,CodeGenFunction * CGF)1042f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
1043f4a2713aSLionel Sambuc                                                 QualType DestType,
1044f4a2713aSLionel Sambuc                                                 CodeGenFunction *CGF) {
1045f4a2713aSLionel Sambuc   Expr::EvalResult Result;
1046f4a2713aSLionel Sambuc 
1047f4a2713aSLionel Sambuc   bool Success = false;
1048f4a2713aSLionel Sambuc 
1049f4a2713aSLionel Sambuc   if (DestType->isReferenceType())
1050f4a2713aSLionel Sambuc     Success = E->EvaluateAsLValue(Result, Context);
1051f4a2713aSLionel Sambuc   else
1052f4a2713aSLionel Sambuc     Success = E->EvaluateAsRValue(Result, Context);
1053f4a2713aSLionel Sambuc 
1054*0a6a1f1dSLionel Sambuc   llvm::Constant *C = nullptr;
1055f4a2713aSLionel Sambuc   if (Success && !Result.HasSideEffects)
1056f4a2713aSLionel Sambuc     C = EmitConstantValue(Result.Val, DestType, CGF);
1057f4a2713aSLionel Sambuc   else
1058f4a2713aSLionel Sambuc     C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
1059f4a2713aSLionel Sambuc 
1060f4a2713aSLionel Sambuc   if (C && C->getType()->isIntegerTy(1)) {
1061f4a2713aSLionel Sambuc     llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
1062f4a2713aSLionel Sambuc     C = llvm::ConstantExpr::getZExt(C, BoolTy);
1063f4a2713aSLionel Sambuc   }
1064f4a2713aSLionel Sambuc   return C;
1065f4a2713aSLionel Sambuc }
1066f4a2713aSLionel Sambuc 
EmitConstantValue(const APValue & Value,QualType DestType,CodeGenFunction * CGF)1067f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value,
1068f4a2713aSLionel Sambuc                                                  QualType DestType,
1069f4a2713aSLionel Sambuc                                                  CodeGenFunction *CGF) {
1070*0a6a1f1dSLionel Sambuc   // For an _Atomic-qualified constant, we may need to add tail padding.
1071*0a6a1f1dSLionel Sambuc   if (auto *AT = DestType->getAs<AtomicType>()) {
1072*0a6a1f1dSLionel Sambuc     QualType InnerType = AT->getValueType();
1073*0a6a1f1dSLionel Sambuc     auto *Inner = EmitConstantValue(Value, InnerType, CGF);
1074*0a6a1f1dSLionel Sambuc 
1075*0a6a1f1dSLionel Sambuc     uint64_t InnerSize = Context.getTypeSize(InnerType);
1076*0a6a1f1dSLionel Sambuc     uint64_t OuterSize = Context.getTypeSize(DestType);
1077*0a6a1f1dSLionel Sambuc     if (InnerSize == OuterSize)
1078*0a6a1f1dSLionel Sambuc       return Inner;
1079*0a6a1f1dSLionel Sambuc 
1080*0a6a1f1dSLionel Sambuc     assert(InnerSize < OuterSize && "emitted over-large constant for atomic");
1081*0a6a1f1dSLionel Sambuc     llvm::Constant *Elts[] = {
1082*0a6a1f1dSLionel Sambuc       Inner,
1083*0a6a1f1dSLionel Sambuc       llvm::ConstantAggregateZero::get(
1084*0a6a1f1dSLionel Sambuc           llvm::ArrayType::get(Int8Ty, (OuterSize - InnerSize) / 8))
1085*0a6a1f1dSLionel Sambuc     };
1086*0a6a1f1dSLionel Sambuc     return llvm::ConstantStruct::getAnon(Elts);
1087*0a6a1f1dSLionel Sambuc   }
1088*0a6a1f1dSLionel Sambuc 
1089f4a2713aSLionel Sambuc   switch (Value.getKind()) {
1090f4a2713aSLionel Sambuc   case APValue::Uninitialized:
1091f4a2713aSLionel Sambuc     llvm_unreachable("Constant expressions should be initialized.");
1092f4a2713aSLionel Sambuc   case APValue::LValue: {
1093f4a2713aSLionel Sambuc     llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
1094f4a2713aSLionel Sambuc     llvm::Constant *Offset =
1095f4a2713aSLionel Sambuc       llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity());
1096f4a2713aSLionel Sambuc 
1097f4a2713aSLionel Sambuc     llvm::Constant *C;
1098f4a2713aSLionel Sambuc     if (APValue::LValueBase LVBase = Value.getLValueBase()) {
1099f4a2713aSLionel Sambuc       // An array can be represented as an lvalue referring to the base.
1100f4a2713aSLionel Sambuc       if (isa<llvm::ArrayType>(DestTy)) {
1101f4a2713aSLionel Sambuc         assert(Offset->isNullValue() && "offset on array initializer");
1102f4a2713aSLionel Sambuc         return ConstExprEmitter(*this, CGF).Visit(
1103f4a2713aSLionel Sambuc           const_cast<Expr*>(LVBase.get<const Expr*>()));
1104f4a2713aSLionel Sambuc       }
1105f4a2713aSLionel Sambuc 
1106f4a2713aSLionel Sambuc       C = ConstExprEmitter(*this, CGF).EmitLValue(LVBase);
1107f4a2713aSLionel Sambuc 
1108f4a2713aSLionel Sambuc       // Apply offset if necessary.
1109f4a2713aSLionel Sambuc       if (!Offset->isNullValue()) {
1110*0a6a1f1dSLionel Sambuc         unsigned AS = C->getType()->getPointerAddressSpace();
1111*0a6a1f1dSLionel Sambuc         llvm::Type *CharPtrTy = Int8Ty->getPointerTo(AS);
1112*0a6a1f1dSLionel Sambuc         llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, CharPtrTy);
1113f4a2713aSLionel Sambuc         Casted = llvm::ConstantExpr::getGetElementPtr(Casted, Offset);
1114*0a6a1f1dSLionel Sambuc         C = llvm::ConstantExpr::getPointerCast(Casted, C->getType());
1115f4a2713aSLionel Sambuc       }
1116f4a2713aSLionel Sambuc 
1117f4a2713aSLionel Sambuc       // Convert to the appropriate type; this could be an lvalue for
1118f4a2713aSLionel Sambuc       // an integer.
1119f4a2713aSLionel Sambuc       if (isa<llvm::PointerType>(DestTy))
1120*0a6a1f1dSLionel Sambuc         return llvm::ConstantExpr::getPointerCast(C, DestTy);
1121f4a2713aSLionel Sambuc 
1122f4a2713aSLionel Sambuc       return llvm::ConstantExpr::getPtrToInt(C, DestTy);
1123f4a2713aSLionel Sambuc     } else {
1124f4a2713aSLionel Sambuc       C = Offset;
1125f4a2713aSLionel Sambuc 
1126f4a2713aSLionel Sambuc       // Convert to the appropriate type; this could be an lvalue for
1127f4a2713aSLionel Sambuc       // an integer.
1128f4a2713aSLionel Sambuc       if (isa<llvm::PointerType>(DestTy))
1129f4a2713aSLionel Sambuc         return llvm::ConstantExpr::getIntToPtr(C, DestTy);
1130f4a2713aSLionel Sambuc 
1131f4a2713aSLionel Sambuc       // If the types don't match this should only be a truncate.
1132f4a2713aSLionel Sambuc       if (C->getType() != DestTy)
1133f4a2713aSLionel Sambuc         return llvm::ConstantExpr::getTrunc(C, DestTy);
1134f4a2713aSLionel Sambuc 
1135f4a2713aSLionel Sambuc       return C;
1136f4a2713aSLionel Sambuc     }
1137f4a2713aSLionel Sambuc   }
1138f4a2713aSLionel Sambuc   case APValue::Int:
1139f4a2713aSLionel Sambuc     return llvm::ConstantInt::get(VMContext, Value.getInt());
1140f4a2713aSLionel Sambuc   case APValue::ComplexInt: {
1141f4a2713aSLionel Sambuc     llvm::Constant *Complex[2];
1142f4a2713aSLionel Sambuc 
1143f4a2713aSLionel Sambuc     Complex[0] = llvm::ConstantInt::get(VMContext,
1144f4a2713aSLionel Sambuc                                         Value.getComplexIntReal());
1145f4a2713aSLionel Sambuc     Complex[1] = llvm::ConstantInt::get(VMContext,
1146f4a2713aSLionel Sambuc                                         Value.getComplexIntImag());
1147f4a2713aSLionel Sambuc 
1148f4a2713aSLionel Sambuc     // FIXME: the target may want to specify that this is packed.
1149f4a2713aSLionel Sambuc     llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1150f4a2713aSLionel Sambuc                                                   Complex[1]->getType(),
1151*0a6a1f1dSLionel Sambuc                                                   nullptr);
1152f4a2713aSLionel Sambuc     return llvm::ConstantStruct::get(STy, Complex);
1153f4a2713aSLionel Sambuc   }
1154f4a2713aSLionel Sambuc   case APValue::Float: {
1155f4a2713aSLionel Sambuc     const llvm::APFloat &Init = Value.getFloat();
1156f4a2713aSLionel Sambuc     if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf &&
1157*0a6a1f1dSLionel Sambuc         !Context.getLangOpts().NativeHalfType &&
1158*0a6a1f1dSLionel Sambuc         !Context.getLangOpts().HalfArgsAndReturns)
1159f4a2713aSLionel Sambuc       return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
1160f4a2713aSLionel Sambuc     else
1161f4a2713aSLionel Sambuc       return llvm::ConstantFP::get(VMContext, Init);
1162f4a2713aSLionel Sambuc   }
1163f4a2713aSLionel Sambuc   case APValue::ComplexFloat: {
1164f4a2713aSLionel Sambuc     llvm::Constant *Complex[2];
1165f4a2713aSLionel Sambuc 
1166f4a2713aSLionel Sambuc     Complex[0] = llvm::ConstantFP::get(VMContext,
1167f4a2713aSLionel Sambuc                                        Value.getComplexFloatReal());
1168f4a2713aSLionel Sambuc     Complex[1] = llvm::ConstantFP::get(VMContext,
1169f4a2713aSLionel Sambuc                                        Value.getComplexFloatImag());
1170f4a2713aSLionel Sambuc 
1171f4a2713aSLionel Sambuc     // FIXME: the target may want to specify that this is packed.
1172f4a2713aSLionel Sambuc     llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1173f4a2713aSLionel Sambuc                                                   Complex[1]->getType(),
1174*0a6a1f1dSLionel Sambuc                                                   nullptr);
1175f4a2713aSLionel Sambuc     return llvm::ConstantStruct::get(STy, Complex);
1176f4a2713aSLionel Sambuc   }
1177f4a2713aSLionel Sambuc   case APValue::Vector: {
1178f4a2713aSLionel Sambuc     SmallVector<llvm::Constant *, 4> Inits;
1179f4a2713aSLionel Sambuc     unsigned NumElts = Value.getVectorLength();
1180f4a2713aSLionel Sambuc 
1181f4a2713aSLionel Sambuc     for (unsigned i = 0; i != NumElts; ++i) {
1182f4a2713aSLionel Sambuc       const APValue &Elt = Value.getVectorElt(i);
1183f4a2713aSLionel Sambuc       if (Elt.isInt())
1184f4a2713aSLionel Sambuc         Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
1185f4a2713aSLionel Sambuc       else
1186f4a2713aSLionel Sambuc         Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
1187f4a2713aSLionel Sambuc     }
1188f4a2713aSLionel Sambuc     return llvm::ConstantVector::get(Inits);
1189f4a2713aSLionel Sambuc   }
1190f4a2713aSLionel Sambuc   case APValue::AddrLabelDiff: {
1191f4a2713aSLionel Sambuc     const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1192f4a2713aSLionel Sambuc     const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1193f4a2713aSLionel Sambuc     llvm::Constant *LHS = EmitConstantExpr(LHSExpr, LHSExpr->getType(), CGF);
1194f4a2713aSLionel Sambuc     llvm::Constant *RHS = EmitConstantExpr(RHSExpr, RHSExpr->getType(), CGF);
1195f4a2713aSLionel Sambuc 
1196f4a2713aSLionel Sambuc     // Compute difference
1197f4a2713aSLionel Sambuc     llvm::Type *ResultType = getTypes().ConvertType(DestType);
1198f4a2713aSLionel Sambuc     LHS = llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy);
1199f4a2713aSLionel Sambuc     RHS = llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy);
1200f4a2713aSLionel Sambuc     llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1201f4a2713aSLionel Sambuc 
1202f4a2713aSLionel Sambuc     // LLVM is a bit sensitive about the exact format of the
1203f4a2713aSLionel Sambuc     // address-of-label difference; make sure to truncate after
1204f4a2713aSLionel Sambuc     // the subtraction.
1205f4a2713aSLionel Sambuc     return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1206f4a2713aSLionel Sambuc   }
1207f4a2713aSLionel Sambuc   case APValue::Struct:
1208f4a2713aSLionel Sambuc   case APValue::Union:
1209f4a2713aSLionel Sambuc     return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType);
1210f4a2713aSLionel Sambuc   case APValue::Array: {
1211f4a2713aSLionel Sambuc     const ArrayType *CAT = Context.getAsArrayType(DestType);
1212f4a2713aSLionel Sambuc     unsigned NumElements = Value.getArraySize();
1213f4a2713aSLionel Sambuc     unsigned NumInitElts = Value.getArrayInitializedElts();
1214f4a2713aSLionel Sambuc 
1215f4a2713aSLionel Sambuc     // Emit array filler, if there is one.
1216*0a6a1f1dSLionel Sambuc     llvm::Constant *Filler = nullptr;
1217f4a2713aSLionel Sambuc     if (Value.hasArrayFiller())
1218f4a2713aSLionel Sambuc       Filler = EmitConstantValueForMemory(Value.getArrayFiller(),
1219f4a2713aSLionel Sambuc                                           CAT->getElementType(), CGF);
1220f4a2713aSLionel Sambuc 
1221f4a2713aSLionel Sambuc     // Emit initializer elements.
1222*0a6a1f1dSLionel Sambuc     llvm::Type *CommonElementType =
1223*0a6a1f1dSLionel Sambuc         getTypes().ConvertType(CAT->getElementType());
1224*0a6a1f1dSLionel Sambuc 
1225*0a6a1f1dSLionel Sambuc     // Try to use a ConstantAggregateZero if we can.
1226*0a6a1f1dSLionel Sambuc     if (Filler && Filler->isNullValue() && !NumInitElts) {
1227*0a6a1f1dSLionel Sambuc       llvm::ArrayType *AType =
1228*0a6a1f1dSLionel Sambuc           llvm::ArrayType::get(CommonElementType, NumElements);
1229*0a6a1f1dSLionel Sambuc       return llvm::ConstantAggregateZero::get(AType);
1230*0a6a1f1dSLionel Sambuc     }
1231*0a6a1f1dSLionel Sambuc 
1232*0a6a1f1dSLionel Sambuc     std::vector<llvm::Constant*> Elts;
1233*0a6a1f1dSLionel Sambuc     Elts.reserve(NumElements);
1234f4a2713aSLionel Sambuc     for (unsigned I = 0; I < NumElements; ++I) {
1235f4a2713aSLionel Sambuc       llvm::Constant *C = Filler;
1236f4a2713aSLionel Sambuc       if (I < NumInitElts)
1237f4a2713aSLionel Sambuc         C = EmitConstantValueForMemory(Value.getArrayInitializedElt(I),
1238f4a2713aSLionel Sambuc                                        CAT->getElementType(), CGF);
1239f4a2713aSLionel Sambuc       else
1240f4a2713aSLionel Sambuc         assert(Filler && "Missing filler for implicit elements of initializer");
1241f4a2713aSLionel Sambuc       if (I == 0)
1242f4a2713aSLionel Sambuc         CommonElementType = C->getType();
1243f4a2713aSLionel Sambuc       else if (C->getType() != CommonElementType)
1244*0a6a1f1dSLionel Sambuc         CommonElementType = nullptr;
1245f4a2713aSLionel Sambuc       Elts.push_back(C);
1246f4a2713aSLionel Sambuc     }
1247f4a2713aSLionel Sambuc 
1248f4a2713aSLionel Sambuc     if (!CommonElementType) {
1249f4a2713aSLionel Sambuc       // FIXME: Try to avoid packing the array
1250f4a2713aSLionel Sambuc       std::vector<llvm::Type*> Types;
1251f4a2713aSLionel Sambuc       Types.reserve(NumElements);
1252f4a2713aSLionel Sambuc       for (unsigned i = 0, e = Elts.size(); i < e; ++i)
1253f4a2713aSLionel Sambuc         Types.push_back(Elts[i]->getType());
1254f4a2713aSLionel Sambuc       llvm::StructType *SType = llvm::StructType::get(VMContext, Types, true);
1255f4a2713aSLionel Sambuc       return llvm::ConstantStruct::get(SType, Elts);
1256f4a2713aSLionel Sambuc     }
1257f4a2713aSLionel Sambuc 
1258f4a2713aSLionel Sambuc     llvm::ArrayType *AType =
1259f4a2713aSLionel Sambuc       llvm::ArrayType::get(CommonElementType, NumElements);
1260f4a2713aSLionel Sambuc     return llvm::ConstantArray::get(AType, Elts);
1261f4a2713aSLionel Sambuc   }
1262f4a2713aSLionel Sambuc   case APValue::MemberPointer:
1263f4a2713aSLionel Sambuc     return getCXXABI().EmitMemberPointer(Value, DestType);
1264f4a2713aSLionel Sambuc   }
1265f4a2713aSLionel Sambuc   llvm_unreachable("Unknown APValue kind");
1266f4a2713aSLionel Sambuc }
1267f4a2713aSLionel Sambuc 
1268f4a2713aSLionel Sambuc llvm::Constant *
EmitConstantValueForMemory(const APValue & Value,QualType DestType,CodeGenFunction * CGF)1269f4a2713aSLionel Sambuc CodeGenModule::EmitConstantValueForMemory(const APValue &Value,
1270f4a2713aSLionel Sambuc                                           QualType DestType,
1271f4a2713aSLionel Sambuc                                           CodeGenFunction *CGF) {
1272f4a2713aSLionel Sambuc   llvm::Constant *C = EmitConstantValue(Value, DestType, CGF);
1273f4a2713aSLionel Sambuc   if (C->getType()->isIntegerTy(1)) {
1274f4a2713aSLionel Sambuc     llvm::Type *BoolTy = getTypes().ConvertTypeForMem(DestType);
1275f4a2713aSLionel Sambuc     C = llvm::ConstantExpr::getZExt(C, BoolTy);
1276f4a2713aSLionel Sambuc   }
1277f4a2713aSLionel Sambuc   return C;
1278f4a2713aSLionel Sambuc }
1279f4a2713aSLionel Sambuc 
1280f4a2713aSLionel Sambuc llvm::Constant *
GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr * E)1281f4a2713aSLionel Sambuc CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
1282f4a2713aSLionel Sambuc   assert(E->isFileScope() && "not a file-scope compound literal expr");
1283*0a6a1f1dSLionel Sambuc   return ConstExprEmitter(*this, nullptr).EmitLValue(E);
1284f4a2713aSLionel Sambuc }
1285f4a2713aSLionel Sambuc 
1286f4a2713aSLionel Sambuc llvm::Constant *
getMemberPointerConstant(const UnaryOperator * uo)1287f4a2713aSLionel Sambuc CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
1288f4a2713aSLionel Sambuc   // Member pointer constants always have a very particular form.
1289f4a2713aSLionel Sambuc   const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
1290f4a2713aSLionel Sambuc   const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
1291f4a2713aSLionel Sambuc 
1292f4a2713aSLionel Sambuc   // A member function pointer.
1293f4a2713aSLionel Sambuc   if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
1294f4a2713aSLionel Sambuc     return getCXXABI().EmitMemberPointer(method);
1295f4a2713aSLionel Sambuc 
1296f4a2713aSLionel Sambuc   // Otherwise, a member data pointer.
1297f4a2713aSLionel Sambuc   uint64_t fieldOffset = getContext().getFieldOffset(decl);
1298f4a2713aSLionel Sambuc   CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1299f4a2713aSLionel Sambuc   return getCXXABI().EmitMemberDataPointer(type, chars);
1300f4a2713aSLionel Sambuc }
1301f4a2713aSLionel Sambuc 
1302f4a2713aSLionel Sambuc static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1303f4a2713aSLionel Sambuc                                                llvm::Type *baseType,
1304f4a2713aSLionel Sambuc                                                const CXXRecordDecl *base);
1305f4a2713aSLionel Sambuc 
EmitNullConstant(CodeGenModule & CGM,const CXXRecordDecl * record,bool asCompleteObject)1306f4a2713aSLionel Sambuc static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
1307f4a2713aSLionel Sambuc                                         const CXXRecordDecl *record,
1308f4a2713aSLionel Sambuc                                         bool asCompleteObject) {
1309f4a2713aSLionel Sambuc   const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
1310f4a2713aSLionel Sambuc   llvm::StructType *structure =
1311f4a2713aSLionel Sambuc     (asCompleteObject ? layout.getLLVMType()
1312f4a2713aSLionel Sambuc                       : layout.getBaseSubobjectLLVMType());
1313f4a2713aSLionel Sambuc 
1314f4a2713aSLionel Sambuc   unsigned numElements = structure->getNumElements();
1315f4a2713aSLionel Sambuc   std::vector<llvm::Constant *> elements(numElements);
1316f4a2713aSLionel Sambuc 
1317f4a2713aSLionel Sambuc   // Fill in all the bases.
1318*0a6a1f1dSLionel Sambuc   for (const auto &I : record->bases()) {
1319*0a6a1f1dSLionel Sambuc     if (I.isVirtual()) {
1320f4a2713aSLionel Sambuc       // Ignore virtual bases; if we're laying out for a complete
1321f4a2713aSLionel Sambuc       // object, we'll lay these out later.
1322f4a2713aSLionel Sambuc       continue;
1323f4a2713aSLionel Sambuc     }
1324f4a2713aSLionel Sambuc 
1325f4a2713aSLionel Sambuc     const CXXRecordDecl *base =
1326*0a6a1f1dSLionel Sambuc       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1327f4a2713aSLionel Sambuc 
1328f4a2713aSLionel Sambuc     // Ignore empty bases.
1329f4a2713aSLionel Sambuc     if (base->isEmpty())
1330f4a2713aSLionel Sambuc       continue;
1331f4a2713aSLionel Sambuc 
1332f4a2713aSLionel Sambuc     unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
1333f4a2713aSLionel Sambuc     llvm::Type *baseType = structure->getElementType(fieldIndex);
1334f4a2713aSLionel Sambuc     elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1335f4a2713aSLionel Sambuc   }
1336f4a2713aSLionel Sambuc 
1337f4a2713aSLionel Sambuc   // Fill in all the fields.
1338*0a6a1f1dSLionel Sambuc   for (const auto *Field : record->fields()) {
1339f4a2713aSLionel Sambuc     // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
1340f4a2713aSLionel Sambuc     // will fill in later.)
1341*0a6a1f1dSLionel Sambuc     if (!Field->isBitField()) {
1342*0a6a1f1dSLionel Sambuc       unsigned fieldIndex = layout.getLLVMFieldNo(Field);
1343*0a6a1f1dSLionel Sambuc       elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
1344f4a2713aSLionel Sambuc     }
1345f4a2713aSLionel Sambuc 
1346f4a2713aSLionel Sambuc     // For unions, stop after the first named field.
1347*0a6a1f1dSLionel Sambuc     if (record->isUnion() && Field->getDeclName())
1348f4a2713aSLionel Sambuc       break;
1349f4a2713aSLionel Sambuc   }
1350f4a2713aSLionel Sambuc 
1351f4a2713aSLionel Sambuc   // Fill in the virtual bases, if we're working with the complete object.
1352f4a2713aSLionel Sambuc   if (asCompleteObject) {
1353*0a6a1f1dSLionel Sambuc     for (const auto &I : record->vbases()) {
1354f4a2713aSLionel Sambuc       const CXXRecordDecl *base =
1355*0a6a1f1dSLionel Sambuc         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1356f4a2713aSLionel Sambuc 
1357f4a2713aSLionel Sambuc       // Ignore empty bases.
1358f4a2713aSLionel Sambuc       if (base->isEmpty())
1359f4a2713aSLionel Sambuc         continue;
1360f4a2713aSLionel Sambuc 
1361f4a2713aSLionel Sambuc       unsigned fieldIndex = layout.getVirtualBaseIndex(base);
1362f4a2713aSLionel Sambuc 
1363f4a2713aSLionel Sambuc       // We might have already laid this field out.
1364f4a2713aSLionel Sambuc       if (elements[fieldIndex]) continue;
1365f4a2713aSLionel Sambuc 
1366f4a2713aSLionel Sambuc       llvm::Type *baseType = structure->getElementType(fieldIndex);
1367f4a2713aSLionel Sambuc       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1368f4a2713aSLionel Sambuc     }
1369f4a2713aSLionel Sambuc   }
1370f4a2713aSLionel Sambuc 
1371f4a2713aSLionel Sambuc   // Now go through all other fields and zero them out.
1372f4a2713aSLionel Sambuc   for (unsigned i = 0; i != numElements; ++i) {
1373f4a2713aSLionel Sambuc     if (!elements[i])
1374f4a2713aSLionel Sambuc       elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
1375f4a2713aSLionel Sambuc   }
1376f4a2713aSLionel Sambuc 
1377f4a2713aSLionel Sambuc   return llvm::ConstantStruct::get(structure, elements);
1378f4a2713aSLionel Sambuc }
1379f4a2713aSLionel Sambuc 
1380f4a2713aSLionel Sambuc /// Emit the null constant for a base subobject.
EmitNullConstantForBase(CodeGenModule & CGM,llvm::Type * baseType,const CXXRecordDecl * base)1381f4a2713aSLionel Sambuc static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1382f4a2713aSLionel Sambuc                                                llvm::Type *baseType,
1383f4a2713aSLionel Sambuc                                                const CXXRecordDecl *base) {
1384f4a2713aSLionel Sambuc   const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
1385f4a2713aSLionel Sambuc 
1386f4a2713aSLionel Sambuc   // Just zero out bases that don't have any pointer to data members.
1387f4a2713aSLionel Sambuc   if (baseLayout.isZeroInitializableAsBase())
1388f4a2713aSLionel Sambuc     return llvm::Constant::getNullValue(baseType);
1389f4a2713aSLionel Sambuc 
1390*0a6a1f1dSLionel Sambuc   // Otherwise, we can just use its null constant.
1391*0a6a1f1dSLionel Sambuc   return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
1392f4a2713aSLionel Sambuc }
1393f4a2713aSLionel Sambuc 
EmitNullConstant(QualType T)1394f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
1395f4a2713aSLionel Sambuc   if (getTypes().isZeroInitializable(T))
1396f4a2713aSLionel Sambuc     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
1397f4a2713aSLionel Sambuc 
1398f4a2713aSLionel Sambuc   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
1399f4a2713aSLionel Sambuc     llvm::ArrayType *ATy =
1400f4a2713aSLionel Sambuc       cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
1401f4a2713aSLionel Sambuc 
1402f4a2713aSLionel Sambuc     QualType ElementTy = CAT->getElementType();
1403f4a2713aSLionel Sambuc 
1404f4a2713aSLionel Sambuc     llvm::Constant *Element = EmitNullConstant(ElementTy);
1405f4a2713aSLionel Sambuc     unsigned NumElements = CAT->getSize().getZExtValue();
1406f4a2713aSLionel Sambuc 
1407f4a2713aSLionel Sambuc     if (Element->isNullValue())
1408f4a2713aSLionel Sambuc       return llvm::ConstantAggregateZero::get(ATy);
1409f4a2713aSLionel Sambuc 
1410f4a2713aSLionel Sambuc     SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
1411f4a2713aSLionel Sambuc     return llvm::ConstantArray::get(ATy, Array);
1412f4a2713aSLionel Sambuc   }
1413f4a2713aSLionel Sambuc 
1414f4a2713aSLionel Sambuc   if (const RecordType *RT = T->getAs<RecordType>()) {
1415f4a2713aSLionel Sambuc     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1416f4a2713aSLionel Sambuc     return ::EmitNullConstant(*this, RD, /*complete object*/ true);
1417f4a2713aSLionel Sambuc   }
1418f4a2713aSLionel Sambuc 
1419f4a2713aSLionel Sambuc   assert(T->isMemberPointerType() && "Should only see member pointers here!");
1420f4a2713aSLionel Sambuc   assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1421f4a2713aSLionel Sambuc          "Should only see pointers to data members here!");
1422f4a2713aSLionel Sambuc 
1423f4a2713aSLionel Sambuc   return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
1424f4a2713aSLionel Sambuc }
1425f4a2713aSLionel Sambuc 
1426f4a2713aSLionel Sambuc llvm::Constant *
EmitNullConstantForBase(const CXXRecordDecl * Record)1427f4a2713aSLionel Sambuc CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
1428f4a2713aSLionel Sambuc   return ::EmitNullConstant(*this, Record, false);
1429f4a2713aSLionel Sambuc }
1430