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