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