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