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 "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "clang/AST/APValue.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "llvm/Constants.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Target/TargetData.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 namespace  {
31 class ConstStructBuilder {
32   CodeGenModule &CGM;
33   CodeGenFunction *CGF;
34 
35   bool Packed;
36 
37   unsigned NextFieldOffsetInBytes;
38 
39   unsigned LLVMStructAlignment;
40 
41   std::vector<llvm::Constant *> Elements;
42 
43   ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
44     : CGM(CGM), CGF(CGF), Packed(false), NextFieldOffsetInBytes(0),
45     LLVMStructAlignment(1) { }
46 
47   bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
48                    const Expr *InitExpr) {
49     uint64_t FieldOffsetInBytes = FieldOffset / 8;
50 
51     assert(NextFieldOffsetInBytes <= FieldOffsetInBytes
52            && "Field offset mismatch!");
53 
54     // Emit the field.
55     llvm::Constant *C = CGM.EmitConstantExpr(InitExpr, Field->getType(), CGF);
56     if (!C)
57       return false;
58 
59     unsigned FieldAlignment = getAlignment(C);
60 
61     // Round up the field offset to the alignment of the field type.
62     uint64_t AlignedNextFieldOffsetInBytes =
63       llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
64 
65     if (AlignedNextFieldOffsetInBytes > FieldOffsetInBytes) {
66       assert(!Packed && "Alignment is wrong even with a packed struct!");
67 
68       // Convert the struct to a packed struct.
69       ConvertStructToPacked();
70 
71       AlignedNextFieldOffsetInBytes = NextFieldOffsetInBytes;
72     }
73 
74     if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
75       // We need to append padding.
76       AppendPadding(FieldOffsetInBytes - NextFieldOffsetInBytes);
77 
78       assert(NextFieldOffsetInBytes == FieldOffsetInBytes &&
79              "Did not add enough padding!");
80 
81       AlignedNextFieldOffsetInBytes = NextFieldOffsetInBytes;
82     }
83 
84     // Add the field.
85     Elements.push_back(C);
86     NextFieldOffsetInBytes = AlignedNextFieldOffsetInBytes + getSizeInBytes(C);
87 
88     if (Packed)
89       assert(LLVMStructAlignment == 1 && "Packed struct not byte-aligned!");
90     else
91       LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
92 
93     return true;
94   }
95 
96   bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
97                       const Expr *InitExpr) {
98     llvm::ConstantInt *CI =
99       cast_or_null<llvm::ConstantInt>(CGM.EmitConstantExpr(InitExpr,
100                                                            Field->getType(),
101                                                            CGF));
102     // FIXME: Can this ever happen?
103     if (!CI)
104       return false;
105 
106     if (FieldOffset > NextFieldOffsetInBytes * 8) {
107       // We need to add padding.
108       uint64_t NumBytes =
109         llvm::RoundUpToAlignment(FieldOffset -
110                                  NextFieldOffsetInBytes * 8, 8) / 8;
111 
112       AppendPadding(NumBytes);
113     }
114 
115     uint64_t FieldSize =
116       Field->getBitWidth()->EvaluateAsInt(CGM.getContext()).getZExtValue();
117 
118     llvm::APInt FieldValue = CI->getValue();
119 
120     // Promote the size of FieldValue if necessary
121     // FIXME: This should never occur, but currently it can because initializer
122     // constants are cast to bool, and because clang is not enforcing bitfield
123     // width limits.
124     if (FieldSize > FieldValue.getBitWidth())
125       FieldValue.zext(FieldSize);
126 
127     // Truncate the size of FieldValue to the bit field size.
128     if (FieldSize < FieldValue.getBitWidth())
129       FieldValue.trunc(FieldSize);
130 
131     if (FieldOffset < NextFieldOffsetInBytes * 8) {
132       // Either part of the field or the entire field can go into the previous
133       // byte.
134       assert(!Elements.empty() && "Elements can't be empty!");
135 
136       unsigned BitsInPreviousByte =
137         NextFieldOffsetInBytes * 8 - FieldOffset;
138 
139       bool FitsCompletelyInPreviousByte =
140         BitsInPreviousByte >= FieldValue.getBitWidth();
141 
142       llvm::APInt Tmp = FieldValue;
143 
144       if (!FitsCompletelyInPreviousByte) {
145         unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
146 
147         if (CGM.getTargetData().isBigEndian()) {
148           Tmp = Tmp.lshr(NewFieldWidth);
149           Tmp.trunc(BitsInPreviousByte);
150 
151           // We want the remaining high bits.
152           FieldValue.trunc(NewFieldWidth);
153         } else {
154           Tmp.trunc(BitsInPreviousByte);
155 
156           // We want the remaining low bits.
157           FieldValue = FieldValue.lshr(BitsInPreviousByte);
158           FieldValue.trunc(NewFieldWidth);
159         }
160       }
161 
162       Tmp.zext(8);
163       if (CGM.getTargetData().isBigEndian()) {
164         if (FitsCompletelyInPreviousByte)
165           Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
166       } else {
167         Tmp = Tmp.shl(8 - BitsInPreviousByte);
168       }
169 
170       // Or in the bits that go into the previous byte.
171       if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(Elements.back()))
172         Tmp |= Val->getValue();
173       else
174         assert(isa<llvm::UndefValue>(Elements.back()));
175 
176       Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
177 
178       if (FitsCompletelyInPreviousByte)
179         return true;
180     }
181 
182     while (FieldValue.getBitWidth() > 8) {
183       llvm::APInt Tmp;
184 
185       if (CGM.getTargetData().isBigEndian()) {
186         // We want the high bits.
187         Tmp = FieldValue;
188         Tmp = Tmp.lshr(Tmp.getBitWidth() - 8);
189         Tmp.trunc(8);
190       } else {
191         // We want the low bits.
192         Tmp = FieldValue;
193         Tmp.trunc(8);
194 
195         FieldValue = FieldValue.lshr(8);
196       }
197 
198       Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
199       NextFieldOffsetInBytes++;
200 
201       FieldValue.trunc(FieldValue.getBitWidth() - 8);
202     }
203 
204     assert(FieldValue.getBitWidth() > 0 &&
205            "Should have at least one bit left!");
206     assert(FieldValue.getBitWidth() <= 8 &&
207            "Should not have more than a byte left!");
208 
209     if (FieldValue.getBitWidth() < 8) {
210       if (CGM.getTargetData().isBigEndian()) {
211         unsigned BitWidth = FieldValue.getBitWidth();
212 
213         FieldValue.zext(8);
214         FieldValue = FieldValue << (8 - BitWidth);
215       } else
216         FieldValue.zext(8);
217     }
218 
219     // Append the last element.
220     Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
221                                               FieldValue));
222     NextFieldOffsetInBytes++;
223     return true;
224   }
225 
226   void AppendPadding(uint64_t NumBytes) {
227     if (!NumBytes)
228       return;
229 
230     const llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext());
231     if (NumBytes > 1)
232       Ty = llvm::ArrayType::get(Ty, NumBytes);
233 
234     llvm::Constant *C = llvm::UndefValue::get(Ty);
235     Elements.push_back(C);
236     assert(getAlignment(C) == 1 && "Padding must have 1 byte alignment!");
237 
238     NextFieldOffsetInBytes += getSizeInBytes(C);
239   }
240 
241   void AppendTailPadding(uint64_t RecordSize) {
242     assert(RecordSize % 8 == 0 && "Invalid record size!");
243 
244     uint64_t RecordSizeInBytes = RecordSize / 8;
245     assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
246 
247     unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
248     AppendPadding(NumPadBytes);
249   }
250 
251   void ConvertStructToPacked() {
252     std::vector<llvm::Constant *> PackedElements;
253     uint64_t ElementOffsetInBytes = 0;
254 
255     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
256       llvm::Constant *C = Elements[i];
257 
258       unsigned ElementAlign =
259         CGM.getTargetData().getABITypeAlignment(C->getType());
260       uint64_t AlignedElementOffsetInBytes =
261         llvm::RoundUpToAlignment(ElementOffsetInBytes, ElementAlign);
262 
263       if (AlignedElementOffsetInBytes > ElementOffsetInBytes) {
264         // We need some padding.
265         uint64_t NumBytes =
266           AlignedElementOffsetInBytes - ElementOffsetInBytes;
267 
268         const llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext());
269         if (NumBytes > 1)
270           Ty = llvm::ArrayType::get(Ty, NumBytes);
271 
272         llvm::Constant *Padding = llvm::UndefValue::get(Ty);
273         PackedElements.push_back(Padding);
274         ElementOffsetInBytes += getSizeInBytes(Padding);
275       }
276 
277       PackedElements.push_back(C);
278       ElementOffsetInBytes += getSizeInBytes(C);
279     }
280 
281     assert(ElementOffsetInBytes == NextFieldOffsetInBytes &&
282            "Packing the struct changed its size!");
283 
284     Elements = PackedElements;
285     LLVMStructAlignment = 1;
286     Packed = true;
287   }
288 
289   bool Build(InitListExpr *ILE) {
290     RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
291     const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
292 
293     unsigned FieldNo = 0;
294     unsigned ElementNo = 0;
295     for (RecordDecl::field_iterator Field = RD->field_begin(),
296          FieldEnd = RD->field_end();
297          ElementNo < ILE->getNumInits() && Field != FieldEnd;
298          ++Field, ++FieldNo) {
299       if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
300         continue;
301 
302       if (Field->isBitField()) {
303         if (!Field->getIdentifier())
304           continue;
305 
306         if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
307                             ILE->getInit(ElementNo)))
308           return false;
309       } else {
310         if (!AppendField(*Field, Layout.getFieldOffset(FieldNo),
311                          ILE->getInit(ElementNo)))
312           return false;
313       }
314 
315       ElementNo++;
316     }
317 
318     uint64_t LayoutSizeInBytes = Layout.getSize() / 8;
319 
320     if (NextFieldOffsetInBytes > LayoutSizeInBytes) {
321       // If the struct is bigger than the size of the record type,
322       // we must have a flexible array member at the end.
323       assert(RD->hasFlexibleArrayMember() &&
324              "Must have flexible array member if struct is bigger than type!");
325 
326       // No tail padding is necessary.
327       return true;
328     }
329 
330     uint64_t LLVMSizeInBytes = llvm::RoundUpToAlignment(NextFieldOffsetInBytes,
331                                                         LLVMStructAlignment);
332 
333     // Check if we need to convert the struct to a packed struct.
334     if (NextFieldOffsetInBytes <= LayoutSizeInBytes &&
335         LLVMSizeInBytes > LayoutSizeInBytes) {
336       assert(!Packed && "Size mismatch!");
337 
338       ConvertStructToPacked();
339       assert(NextFieldOffsetInBytes == LayoutSizeInBytes &&
340              "Converting to packed did not help!");
341     }
342 
343     // Append tail padding if necessary.
344     AppendTailPadding(Layout.getSize());
345 
346     assert(Layout.getSize() / 8 == NextFieldOffsetInBytes &&
347            "Tail padding mismatch!");
348 
349     return true;
350   }
351 
352   unsigned getAlignment(const llvm::Constant *C) const {
353     if (Packed)
354       return 1;
355 
356     return CGM.getTargetData().getABITypeAlignment(C->getType());
357   }
358 
359   uint64_t getSizeInBytes(const llvm::Constant *C) const {
360     return CGM.getTargetData().getTypeAllocSize(C->getType());
361   }
362 
363 public:
364   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
365                                      InitListExpr *ILE) {
366     ConstStructBuilder Builder(CGM, CGF);
367 
368     if (!Builder.Build(ILE))
369       return 0;
370 
371     llvm::Constant *Result =
372       llvm::ConstantStruct::get(CGM.getLLVMContext(),
373                                 Builder.Elements, Builder.Packed);
374 
375     assert(llvm::RoundUpToAlignment(Builder.NextFieldOffsetInBytes,
376                                     Builder.getAlignment(Result)) ==
377            Builder.getSizeInBytes(Result) && "Size mismatch!");
378 
379     return Result;
380   }
381 };
382 
383 class ConstExprEmitter :
384   public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
385   CodeGenModule &CGM;
386   CodeGenFunction *CGF;
387   llvm::LLVMContext &VMContext;
388 public:
389   ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
390     : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
391   }
392 
393   //===--------------------------------------------------------------------===//
394   //                            Visitor Methods
395   //===--------------------------------------------------------------------===//
396 
397   llvm::Constant *VisitStmt(Stmt *S) {
398     return 0;
399   }
400 
401   llvm::Constant *VisitParenExpr(ParenExpr *PE) {
402     return Visit(PE->getSubExpr());
403   }
404 
405   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
406     return Visit(E->getInitializer());
407   }
408 
409   llvm::Constant *EmitMemberFunctionPointer(CXXMethodDecl *MD) {
410     assert(MD->isInstance() && "Member function must not be static!");
411 
412     MD = MD->getCanonicalDecl();
413 
414     const llvm::Type *PtrDiffTy =
415       CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
416 
417     llvm::Constant *Values[2];
418 
419     // Get the function pointer (or index if this is a virtual function).
420     if (MD->isVirtual()) {
421       uint64_t Index = CGM.getVTables().getMethodVtableIndex(MD);
422 
423       // Itanium C++ ABI 2.3:
424       //   For a non-virtual function, this field is a simple function pointer.
425       //   For a virtual function, it is 1 plus the virtual table offset
426       //   (in bytes) of the function, represented as a ptrdiff_t.
427       Values[0] = llvm::ConstantInt::get(PtrDiffTy, (Index * 8) + 1);
428     } else {
429       const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
430       const llvm::Type *Ty =
431         CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
432                                        FPT->isVariadic());
433 
434       llvm::Constant *FuncPtr = CGM.GetAddrOfFunction(MD, Ty);
435       Values[0] = llvm::ConstantExpr::getPtrToInt(FuncPtr, PtrDiffTy);
436     }
437 
438     // The adjustment will always be 0.
439     Values[1] = llvm::ConstantInt::get(PtrDiffTy, 0);
440 
441     return llvm::ConstantStruct::get(CGM.getLLVMContext(),
442                                      Values, 2, /*Packed=*/false);
443   }
444 
445   llvm::Constant *VisitUnaryAddrOf(UnaryOperator *E) {
446     if (const MemberPointerType *MPT =
447         E->getType()->getAs<MemberPointerType>()) {
448       QualType T = MPT->getPointeeType();
449       DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
450 
451       NamedDecl *ND = DRE->getDecl();
452       if (T->isFunctionProtoType())
453         return EmitMemberFunctionPointer(cast<CXXMethodDecl>(ND));
454 
455       // We have a pointer to data member.
456       return CGM.EmitPointerToDataMember(cast<FieldDecl>(ND));
457     }
458 
459     return 0;
460   }
461 
462   llvm::Constant *VisitBinSub(BinaryOperator *E) {
463     // This must be a pointer/pointer subtraction.  This only happens for
464     // address of label.
465     if (!isa<AddrLabelExpr>(E->getLHS()->IgnoreParenNoopCasts(CGM.getContext())) ||
466        !isa<AddrLabelExpr>(E->getRHS()->IgnoreParenNoopCasts(CGM.getContext())))
467       return 0;
468 
469     llvm::Constant *LHS = CGM.EmitConstantExpr(E->getLHS(),
470                                                E->getLHS()->getType(), CGF);
471     llvm::Constant *RHS = CGM.EmitConstantExpr(E->getRHS(),
472                                                E->getRHS()->getType(), CGF);
473 
474     const llvm::Type *ResultType = ConvertType(E->getType());
475     LHS = llvm::ConstantExpr::getPtrToInt(LHS, ResultType);
476     RHS = llvm::ConstantExpr::getPtrToInt(RHS, ResultType);
477 
478     // No need to divide by element size, since addr of label is always void*,
479     // which has size 1 in GNUish.
480     return llvm::ConstantExpr::getSub(LHS, RHS);
481   }
482 
483   llvm::Constant *VisitCastExpr(CastExpr* E) {
484     switch (E->getCastKind()) {
485     case CastExpr::CK_ToUnion: {
486       // GCC cast to union extension
487       assert(E->getType()->isUnionType() &&
488              "Destination type is not union type!");
489       const llvm::Type *Ty = ConvertType(E->getType());
490       Expr *SubExpr = E->getSubExpr();
491 
492       llvm::Constant *C =
493         CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF);
494       if (!C)
495         return 0;
496 
497       // Build a struct with the union sub-element as the first member,
498       // and padded to the appropriate size
499       std::vector<llvm::Constant*> Elts;
500       std::vector<const llvm::Type*> Types;
501       Elts.push_back(C);
502       Types.push_back(C->getType());
503       unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType());
504       unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(Ty);
505 
506       assert(CurSize <= TotalSize && "Union size mismatch!");
507       if (unsigned NumPadBytes = TotalSize - CurSize) {
508         const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
509         if (NumPadBytes > 1)
510           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
511 
512         Elts.push_back(llvm::UndefValue::get(Ty));
513         Types.push_back(Ty);
514       }
515 
516       llvm::StructType* STy =
517         llvm::StructType::get(C->getType()->getContext(), Types, false);
518       return llvm::ConstantStruct::get(STy, Elts);
519     }
520     case CastExpr::CK_NullToMemberPointer:
521       return CGM.EmitNullConstant(E->getType());
522 
523     case CastExpr::CK_BaseToDerivedMemberPointer: {
524       Expr *SubExpr = E->getSubExpr();
525 
526       const MemberPointerType *SrcTy =
527         SubExpr->getType()->getAs<MemberPointerType>();
528       const MemberPointerType *DestTy =
529         E->getType()->getAs<MemberPointerType>();
530 
531       const CXXRecordDecl *BaseClass =
532         cast<CXXRecordDecl>(cast<RecordType>(SrcTy->getClass())->getDecl());
533       const CXXRecordDecl *DerivedClass =
534         cast<CXXRecordDecl>(cast<RecordType>(DestTy->getClass())->getDecl());
535 
536       if (SrcTy->getPointeeType()->isFunctionProtoType()) {
537         llvm::Constant *C =
538           CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF);
539         if (!C)
540           return 0;
541 
542         llvm::ConstantStruct *CS = cast<llvm::ConstantStruct>(C);
543 
544         // Check if we need to update the adjustment.
545         if (llvm::Constant *Offset =
546               CGM.GetNonVirtualBaseClassOffset(DerivedClass, BaseClass)) {
547           llvm::Constant *Values[2];
548 
549           Values[0] = CS->getOperand(0);
550           Values[1] = llvm::ConstantExpr::getAdd(CS->getOperand(1), Offset);
551           return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2,
552                                            /*Packed=*/false);
553         }
554 
555         return CS;
556       }
557     }
558 
559     case CastExpr::CK_BitCast:
560       // This must be a member function pointer cast.
561       return Visit(E->getSubExpr());
562 
563     default: {
564       // FIXME: This should be handled by the CK_NoOp cast kind.
565       // Explicit and implicit no-op casts
566       QualType Ty = E->getType(), SubTy = E->getSubExpr()->getType();
567       if (CGM.getContext().hasSameUnqualifiedType(Ty, SubTy))
568         return Visit(E->getSubExpr());
569 
570       // Handle integer->integer casts for address-of-label differences.
571       if (Ty->isIntegerType() && SubTy->isIntegerType() &&
572           CGF) {
573         llvm::Value *Src = Visit(E->getSubExpr());
574         if (Src == 0) return 0;
575 
576         // Use EmitScalarConversion to perform the conversion.
577         return cast<llvm::Constant>(CGF->EmitScalarConversion(Src, SubTy, Ty));
578       }
579 
580       return 0;
581     }
582     }
583   }
584 
585   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
586     return Visit(DAE->getExpr());
587   }
588 
589   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
590     std::vector<llvm::Constant*> Elts;
591     const llvm::ArrayType *AType =
592         cast<llvm::ArrayType>(ConvertType(ILE->getType()));
593     unsigned NumInitElements = ILE->getNumInits();
594     // FIXME: Check for wide strings
595     // FIXME: Check for NumInitElements exactly equal to 1??
596     if (NumInitElements > 0 &&
597         (isa<StringLiteral>(ILE->getInit(0)) ||
598          isa<ObjCEncodeExpr>(ILE->getInit(0))) &&
599         ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType())
600       return Visit(ILE->getInit(0));
601     const llvm::Type *ElemTy = AType->getElementType();
602     unsigned NumElements = AType->getNumElements();
603 
604     // Initialising an array requires us to automatically
605     // initialise any elements that have not been initialised explicitly
606     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
607 
608     // Copy initializer elements.
609     unsigned i = 0;
610     bool RewriteType = false;
611     for (; i < NumInitableElts; ++i) {
612       Expr *Init = ILE->getInit(i);
613       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
614       if (!C)
615         return 0;
616       RewriteType |= (C->getType() != ElemTy);
617       Elts.push_back(C);
618     }
619 
620     // Initialize remaining array elements.
621     // FIXME: This doesn't handle member pointers correctly!
622     for (; i < NumElements; ++i)
623       Elts.push_back(llvm::Constant::getNullValue(ElemTy));
624 
625     if (RewriteType) {
626       // FIXME: Try to avoid packing the array
627       std::vector<const llvm::Type*> Types;
628       for (unsigned i = 0; i < Elts.size(); ++i)
629         Types.push_back(Elts[i]->getType());
630       const llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
631                                                             Types, true);
632       return llvm::ConstantStruct::get(SType, Elts);
633     }
634 
635     return llvm::ConstantArray::get(AType, Elts);
636   }
637 
638   llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
639     return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
640   }
641 
642   llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
643     return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
644   }
645 
646   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
647     return CGM.EmitNullConstant(E->getType());
648   }
649 
650   llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
651     if (ILE->getType()->isScalarType()) {
652       // We have a scalar in braces. Just use the first element.
653       if (ILE->getNumInits() > 0) {
654         Expr *Init = ILE->getInit(0);
655         return CGM.EmitConstantExpr(Init, Init->getType(), CGF);
656       }
657       return CGM.EmitNullConstant(ILE->getType());
658     }
659 
660     if (ILE->getType()->isArrayType())
661       return EmitArrayInitialization(ILE);
662 
663     if (ILE->getType()->isRecordType())
664       return EmitStructInitialization(ILE);
665 
666     if (ILE->getType()->isUnionType())
667       return EmitUnionInitialization(ILE);
668 
669     // If ILE was a constant vector, we would have handled it already.
670     if (ILE->getType()->isVectorType())
671       return 0;
672 
673     assert(0 && "Unable to handle InitListExpr");
674     // Get rid of control reaches end of void function warning.
675     // Not reached.
676     return 0;
677   }
678 
679   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
680     if (!E->getConstructor()->isTrivial())
681       return 0;
682 
683     QualType Ty = E->getType();
684 
685     // FIXME: We should not have to call getBaseElementType here.
686     const RecordType *RT =
687       CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
688     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
689 
690     // If the class doesn't have a trivial destructor, we can't emit it as a
691     // constant expr.
692     if (!RD->hasTrivialDestructor())
693       return 0;
694 
695     // Only copy and default constructors can be trivial.
696 
697 
698     if (E->getNumArgs()) {
699       assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
700       assert(E->getConstructor()->isCopyConstructor() &&
701              "trivial ctor has argument but isn't a copy ctor");
702 
703       Expr *Arg = E->getArg(0);
704       assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
705              "argument to copy ctor is of wrong type");
706 
707       return Visit(Arg);
708     }
709 
710     return CGM.EmitNullConstant(Ty);
711   }
712 
713   llvm::Constant *VisitStringLiteral(StringLiteral *E) {
714     assert(!E->getType()->isPointerType() && "Strings are always arrays");
715 
716     // This must be a string initializing an array in a static initializer.
717     // Don't emit it as the address of the string, emit the string data itself
718     // as an inline array.
719     return llvm::ConstantArray::get(VMContext,
720                                     CGM.GetStringForStringLiteral(E), false);
721   }
722 
723   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
724     // This must be an @encode initializing an array in a static initializer.
725     // Don't emit it as the address of the string, emit the string data itself
726     // as an inline array.
727     std::string Str;
728     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
729     const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
730 
731     // Resize the string to the right size, adding zeros at the end, or
732     // truncating as needed.
733     Str.resize(CAT->getSize().getZExtValue(), '\0');
734     return llvm::ConstantArray::get(VMContext, Str, false);
735   }
736 
737   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
738     return Visit(E->getSubExpr());
739   }
740 
741   // Utility methods
742   const llvm::Type *ConvertType(QualType T) {
743     return CGM.getTypes().ConvertType(T);
744   }
745 
746 public:
747   llvm::Constant *EmitLValue(Expr *E) {
748     switch (E->getStmtClass()) {
749     default: break;
750     case Expr::CompoundLiteralExprClass: {
751       // Note that due to the nature of compound literals, this is guaranteed
752       // to be the only use of the variable, so we just generate it here.
753       CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
754       llvm::Constant* C = Visit(CLE->getInitializer());
755       // FIXME: "Leaked" on failure.
756       if (C)
757         C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
758                                      E->getType().isConstant(CGM.getContext()),
759                                      llvm::GlobalValue::InternalLinkage,
760                                      C, ".compoundliteral", 0, false,
761                                      E->getType().getAddressSpace());
762       return C;
763     }
764     case Expr::DeclRefExprClass: {
765       ValueDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
766       if (Decl->hasAttr<WeakRefAttr>())
767 	return CGM.GetWeakRefReference(Decl);
768       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
769         return CGM.GetAddrOfFunction(FD);
770       if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
771         // We can never refer to a variable with local storage.
772         if (!VD->hasLocalStorage()) {
773           if (VD->isFileVarDecl() || VD->hasExternalStorage())
774             return CGM.GetAddrOfGlobalVar(VD);
775           else if (VD->isBlockVarDecl()) {
776             assert(CGF && "Can't access static local vars without CGF");
777             return CGF->GetAddrOfStaticLocalVar(VD);
778           }
779         }
780       }
781       break;
782     }
783     case Expr::StringLiteralClass:
784       return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
785     case Expr::ObjCEncodeExprClass:
786       return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
787     case Expr::ObjCStringLiteralClass: {
788       ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
789       llvm::Constant *C =
790           CGM.getObjCRuntime().GenerateConstantString(SL->getString());
791       return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
792     }
793     case Expr::PredefinedExprClass: {
794       unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
795       if (CGF) {
796         LValue Res = CGF->EmitPredefinedFunctionName(Type);
797         return cast<llvm::Constant>(Res.getAddress());
798       } else if (Type == PredefinedExpr::PrettyFunction) {
799         return CGM.GetAddrOfConstantCString("top level", ".tmp");
800       }
801 
802       return CGM.GetAddrOfConstantCString("", ".tmp");
803     }
804     case Expr::AddrLabelExprClass: {
805       assert(CGF && "Invalid address of label expression outside function.");
806       llvm::Constant *Ptr =
807         CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
808       return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
809     }
810     case Expr::CallExprClass: {
811       CallExpr* CE = cast<CallExpr>(E);
812       unsigned builtin = CE->isBuiltinCall(CGM.getContext());
813       if (builtin !=
814             Builtin::BI__builtin___CFStringMakeConstantString &&
815           builtin !=
816             Builtin::BI__builtin___NSStringMakeConstantString)
817         break;
818       const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
819       const StringLiteral *Literal = cast<StringLiteral>(Arg);
820       if (builtin ==
821             Builtin::BI__builtin___NSStringMakeConstantString) {
822         return CGM.getObjCRuntime().GenerateConstantString(Literal);
823       }
824       // FIXME: need to deal with UCN conversion issues.
825       return CGM.GetAddrOfConstantCFString(Literal);
826     }
827     case Expr::BlockExprClass: {
828       std::string FunctionName;
829       if (CGF)
830         FunctionName = CGF->CurFn->getName();
831       else
832         FunctionName = "global";
833 
834       return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
835     }
836     }
837 
838     return 0;
839   }
840 };
841 
842 }  // end anonymous namespace.
843 
844 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
845                                                 QualType DestType,
846                                                 CodeGenFunction *CGF) {
847   Expr::EvalResult Result;
848 
849   bool Success = false;
850 
851   if (DestType->isReferenceType())
852     Success = E->EvaluateAsLValue(Result, Context);
853   else
854     Success = E->Evaluate(Result, Context);
855 
856   if (Success && !Result.HasSideEffects) {
857     switch (Result.Val.getKind()) {
858     case APValue::Uninitialized:
859       assert(0 && "Constant expressions should be initialized.");
860       return 0;
861     case APValue::LValue: {
862       const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
863       llvm::Constant *Offset =
864         llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
865                                Result.Val.getLValueOffset().getQuantity());
866 
867       llvm::Constant *C;
868       if (const Expr *LVBase = Result.Val.getLValueBase()) {
869         C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
870 
871         // Apply offset if necessary.
872         if (!Offset->isNullValue()) {
873           const llvm::Type *Type = llvm::Type::getInt8PtrTy(VMContext);
874           llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type);
875           Casted = llvm::ConstantExpr::getGetElementPtr(Casted, &Offset, 1);
876           C = llvm::ConstantExpr::getBitCast(Casted, C->getType());
877         }
878 
879         // Convert to the appropriate type; this could be an lvalue for
880         // an integer.
881         if (isa<llvm::PointerType>(DestTy))
882           return llvm::ConstantExpr::getBitCast(C, DestTy);
883 
884         return llvm::ConstantExpr::getPtrToInt(C, DestTy);
885       } else {
886         C = Offset;
887 
888         // Convert to the appropriate type; this could be an lvalue for
889         // an integer.
890         if (isa<llvm::PointerType>(DestTy))
891           return llvm::ConstantExpr::getIntToPtr(C, DestTy);
892 
893         // If the types don't match this should only be a truncate.
894         if (C->getType() != DestTy)
895           return llvm::ConstantExpr::getTrunc(C, DestTy);
896 
897         return C;
898       }
899     }
900     case APValue::Int: {
901       llvm::Constant *C = llvm::ConstantInt::get(VMContext,
902                                                  Result.Val.getInt());
903 
904       if (C->getType() == llvm::Type::getInt1Ty(VMContext)) {
905         const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
906         C = llvm::ConstantExpr::getZExt(C, BoolTy);
907       }
908       return C;
909     }
910     case APValue::ComplexInt: {
911       llvm::Constant *Complex[2];
912 
913       Complex[0] = llvm::ConstantInt::get(VMContext,
914                                           Result.Val.getComplexIntReal());
915       Complex[1] = llvm::ConstantInt::get(VMContext,
916                                           Result.Val.getComplexIntImag());
917 
918       // FIXME: the target may want to specify that this is packed.
919       return llvm::ConstantStruct::get(VMContext, Complex, 2, false);
920     }
921     case APValue::Float:
922       return llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
923     case APValue::ComplexFloat: {
924       llvm::Constant *Complex[2];
925 
926       Complex[0] = llvm::ConstantFP::get(VMContext,
927                                          Result.Val.getComplexFloatReal());
928       Complex[1] = llvm::ConstantFP::get(VMContext,
929                                          Result.Val.getComplexFloatImag());
930 
931       // FIXME: the target may want to specify that this is packed.
932       return llvm::ConstantStruct::get(VMContext, Complex, 2, false);
933     }
934     case APValue::Vector: {
935       llvm::SmallVector<llvm::Constant *, 4> Inits;
936       unsigned NumElts = Result.Val.getVectorLength();
937 
938       for (unsigned i = 0; i != NumElts; ++i) {
939         APValue &Elt = Result.Val.getVectorElt(i);
940         if (Elt.isInt())
941           Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
942         else
943           Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
944       }
945       return llvm::ConstantVector::get(&Inits[0], Inits.size());
946     }
947     }
948   }
949 
950   llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
951   if (C && C->getType() == llvm::Type::getInt1Ty(VMContext)) {
952     const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
953     C = llvm::ConstantExpr::getZExt(C, BoolTy);
954   }
955   return C;
956 }
957 
958 static bool containsPointerToDataMember(CodeGenTypes &Types, QualType T) {
959   // No need to check for member pointers when not compiling C++.
960   if (!Types.getContext().getLangOptions().CPlusPlus)
961     return false;
962 
963   T = Types.getContext().getBaseElementType(T);
964 
965   if (const RecordType *RT = T->getAs<RecordType>()) {
966     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
967 
968     // FIXME: It would be better if there was a way to explicitly compute the
969     // record layout instead of converting to a type.
970     Types.ConvertTagDeclType(RD);
971 
972     const CGRecordLayout &Layout = Types.getCGRecordLayout(RD);
973     return Layout.containsPointerToDataMember();
974   }
975 
976   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
977     return !MPT->getPointeeType()->isFunctionType();
978 
979   return false;
980 }
981 
982 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
983   if (!containsPointerToDataMember(getTypes(), T))
984     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
985 
986   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
987 
988     QualType ElementTy = CAT->getElementType();
989 
990     llvm::Constant *Element = EmitNullConstant(ElementTy);
991     unsigned NumElements = CAT->getSize().getZExtValue();
992     std::vector<llvm::Constant *> Array(NumElements);
993     for (unsigned i = 0; i != NumElements; ++i)
994       Array[i] = Element;
995 
996     const llvm::ArrayType *ATy =
997       cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
998     return llvm::ConstantArray::get(ATy, Array);
999   }
1000 
1001   if (const RecordType *RT = T->getAs<RecordType>()) {
1002     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1003     assert(!RD->getNumBases() &&
1004            "FIXME: Handle zero-initializing structs with bases and "
1005            "pointers to data members.");
1006     const llvm::StructType *STy =
1007       cast<llvm::StructType>(getTypes().ConvertTypeForMem(T));
1008     unsigned NumElements = STy->getNumElements();
1009     std::vector<llvm::Constant *> Elements(NumElements);
1010 
1011     for (RecordDecl::field_iterator I = RD->field_begin(),
1012          E = RD->field_end(); I != E; ++I) {
1013       const FieldDecl *FD = *I;
1014 
1015       unsigned FieldNo = getTypes().getLLVMFieldNo(FD);
1016       Elements[FieldNo] = EmitNullConstant(FD->getType());
1017     }
1018 
1019     // Now go through all other fields and zero them out.
1020     for (unsigned i = 0; i != NumElements; ++i) {
1021       if (!Elements[i])
1022         Elements[i] = llvm::Constant::getNullValue(STy->getElementType(i));
1023     }
1024 
1025     return llvm::ConstantStruct::get(STy, Elements);
1026   }
1027 
1028   assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1029          "Should only see pointers to data members here!");
1030 
1031   // Itanium C++ ABI 2.3:
1032   //   A NULL pointer is represented as -1.
1033   return llvm::ConstantInt::get(getTypes().ConvertTypeForMem(T), -1ULL,
1034                                 /*isSigned=*/true);
1035 }
1036 
1037 llvm::Constant *
1038 CodeGenModule::EmitPointerToDataMember(const FieldDecl *FD) {
1039 
1040   // Itanium C++ ABI 2.3:
1041   //   A pointer to data member is an offset from the base address of the class
1042   //   object containing it, represented as a ptrdiff_t
1043 
1044   const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(FD->getParent());
1045   QualType ClassType =
1046     getContext().getTypeDeclType(const_cast<CXXRecordDecl *>(ClassDecl));
1047 
1048   const llvm::StructType *ClassLTy =
1049     cast<llvm::StructType>(getTypes().ConvertType(ClassType));
1050 
1051   unsigned FieldNo = getTypes().getLLVMFieldNo(FD);
1052   uint64_t Offset =
1053     getTargetData().getStructLayout(ClassLTy)->getElementOffset(FieldNo);
1054 
1055   const llvm::Type *PtrDiffTy =
1056     getTypes().ConvertType(getContext().getPointerDiffType());
1057 
1058   return llvm::ConstantInt::get(PtrDiffTy, Offset);
1059 }
1060