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 *VisitCastExpr(CastExpr* E) {
407     switch (E->getCastKind()) {
408     case CastExpr::CK_ToUnion: {
409       // GCC cast to union extension
410       assert(E->getType()->isUnionType() &&
411              "Destination type is not union type!");
412       const llvm::Type *Ty = ConvertType(E->getType());
413       Expr *SubExpr = E->getSubExpr();
414 
415       llvm::Constant *C =
416         CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF);
417       if (!C)
418         return 0;
419 
420       // Build a struct with the union sub-element as the first member,
421       // and padded to the appropriate size
422       std::vector<llvm::Constant*> Elts;
423       std::vector<const llvm::Type*> Types;
424       Elts.push_back(C);
425       Types.push_back(C->getType());
426       unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType());
427       unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(Ty);
428 
429       assert(CurSize <= TotalSize && "Union size mismatch!");
430       if (unsigned NumPadBytes = TotalSize - CurSize) {
431         const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
432         if (NumPadBytes > 1)
433           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
434 
435         Elts.push_back(llvm::Constant::getNullValue(Ty));
436         Types.push_back(Ty);
437       }
438 
439       llvm::StructType* STy =
440         llvm::StructType::get(C->getType()->getContext(), Types, false);
441       return llvm::ConstantStruct::get(STy, Elts);
442     }
443     case CastExpr::CK_NullToMemberPointer:
444       return CGM.EmitNullConstant(E->getType());
445     default: {
446       // FIXME: This should be handled by the CK_NoOp cast kind.
447       // Explicit and implicit no-op casts
448       QualType Ty = E->getType(), SubTy = E->getSubExpr()->getType();
449       if (CGM.getContext().hasSameUnqualifiedType(Ty, SubTy))
450           return Visit(E->getSubExpr());
451       return 0;
452     }
453     }
454   }
455 
456   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
457     return Visit(DAE->getExpr());
458   }
459 
460   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
461     std::vector<llvm::Constant*> Elts;
462     const llvm::ArrayType *AType =
463         cast<llvm::ArrayType>(ConvertType(ILE->getType()));
464     unsigned NumInitElements = ILE->getNumInits();
465     // FIXME: Check for wide strings
466     // FIXME: Check for NumInitElements exactly equal to 1??
467     if (NumInitElements > 0 &&
468         (isa<StringLiteral>(ILE->getInit(0)) ||
469          isa<ObjCEncodeExpr>(ILE->getInit(0))) &&
470         ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType())
471       return Visit(ILE->getInit(0));
472     const llvm::Type *ElemTy = AType->getElementType();
473     unsigned NumElements = AType->getNumElements();
474 
475     // Initialising an array requires us to automatically
476     // initialise any elements that have not been initialised explicitly
477     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
478 
479     // Copy initializer elements.
480     unsigned i = 0;
481     bool RewriteType = false;
482     for (; i < NumInitableElts; ++i) {
483       Expr *Init = ILE->getInit(i);
484       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
485       if (!C)
486         return 0;
487       RewriteType |= (C->getType() != ElemTy);
488       Elts.push_back(C);
489     }
490 
491     // Initialize remaining array elements.
492     // FIXME: This doesn't handle member pointers correctly!
493     for (; i < NumElements; ++i)
494       Elts.push_back(llvm::Constant::getNullValue(ElemTy));
495 
496     if (RewriteType) {
497       // FIXME: Try to avoid packing the array
498       std::vector<const llvm::Type*> Types;
499       for (unsigned i = 0; i < Elts.size(); ++i)
500         Types.push_back(Elts[i]->getType());
501       const llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
502                                                             Types, true);
503       return llvm::ConstantStruct::get(SType, Elts);
504     }
505 
506     return llvm::ConstantArray::get(AType, Elts);
507   }
508 
509   llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
510     return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
511   }
512 
513   llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
514     return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
515   }
516 
517   llvm::Constant *EmitVectorInitialization(InitListExpr *ILE) {
518     const llvm::VectorType *VType =
519         cast<llvm::VectorType>(ConvertType(ILE->getType()));
520     const llvm::Type *ElemTy = VType->getElementType();
521     std::vector<llvm::Constant*> Elts;
522     unsigned NumElements = VType->getNumElements();
523     unsigned NumInitElements = ILE->getNumInits();
524 
525     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
526 
527     // Copy initializer elements.
528     unsigned i = 0;
529     for (; i < NumInitableElts; ++i) {
530       Expr *Init = ILE->getInit(i);
531       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
532       if (!C)
533         return 0;
534       Elts.push_back(C);
535     }
536 
537     for (; i < NumElements; ++i)
538       Elts.push_back(llvm::Constant::getNullValue(ElemTy));
539 
540     return llvm::ConstantVector::get(VType, Elts);
541   }
542 
543   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
544     return CGM.EmitNullConstant(E->getType());
545   }
546 
547   llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
548     if (ILE->getType()->isScalarType()) {
549       // We have a scalar in braces. Just use the first element.
550       if (ILE->getNumInits() > 0) {
551         Expr *Init = ILE->getInit(0);
552         return CGM.EmitConstantExpr(Init, Init->getType(), CGF);
553       }
554       return CGM.EmitNullConstant(ILE->getType());
555     }
556 
557     if (ILE->getType()->isArrayType())
558       return EmitArrayInitialization(ILE);
559 
560     if (ILE->getType()->isStructureType())
561       return EmitStructInitialization(ILE);
562 
563     if (ILE->getType()->isUnionType())
564       return EmitUnionInitialization(ILE);
565 
566     if (ILE->getType()->isVectorType())
567       return EmitVectorInitialization(ILE);
568 
569     assert(0 && "Unable to handle InitListExpr");
570     // Get rid of control reaches end of void function warning.
571     // Not reached.
572     return 0;
573   }
574 
575   llvm::Constant *VisitStringLiteral(StringLiteral *E) {
576     assert(!E->getType()->isPointerType() && "Strings are always arrays");
577 
578     // This must be a string initializing an array in a static initializer.
579     // Don't emit it as the address of the string, emit the string data itself
580     // as an inline array.
581     return llvm::ConstantArray::get(VMContext,
582                                     CGM.GetStringForStringLiteral(E), false);
583   }
584 
585   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
586     // This must be an @encode initializing an array in a static initializer.
587     // Don't emit it as the address of the string, emit the string data itself
588     // as an inline array.
589     std::string Str;
590     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
591     const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
592 
593     // Resize the string to the right size, adding zeros at the end, or
594     // truncating as needed.
595     Str.resize(CAT->getSize().getZExtValue(), '\0');
596     return llvm::ConstantArray::get(VMContext, Str, false);
597   }
598 
599   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
600     return Visit(E->getSubExpr());
601   }
602 
603   // Utility methods
604   const llvm::Type *ConvertType(QualType T) {
605     return CGM.getTypes().ConvertType(T);
606   }
607 
608 public:
609   llvm::Constant *EmitLValue(Expr *E) {
610     switch (E->getStmtClass()) {
611     default: break;
612     case Expr::CompoundLiteralExprClass: {
613       // Note that due to the nature of compound literals, this is guaranteed
614       // to be the only use of the variable, so we just generate it here.
615       CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
616       llvm::Constant* C = Visit(CLE->getInitializer());
617       // FIXME: "Leaked" on failure.
618       if (C)
619         C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
620                                      E->getType().isConstant(CGM.getContext()),
621                                      llvm::GlobalValue::InternalLinkage,
622                                      C, ".compoundliteral", 0, false,
623                                      E->getType().getAddressSpace());
624       return C;
625     }
626     case Expr::DeclRefExprClass:
627     case Expr::QualifiedDeclRefExprClass: {
628       NamedDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
629       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
630         return CGM.GetAddrOfFunction(FD);
631       if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
632         // We can never refer to a variable with local storage.
633         if (!VD->hasLocalStorage()) {
634           if (VD->isFileVarDecl() || VD->hasExternalStorage())
635             return CGM.GetAddrOfGlobalVar(VD);
636           else if (VD->isBlockVarDecl()) {
637             assert(CGF && "Can't access static local vars without CGF");
638             return CGF->GetAddrOfStaticLocalVar(VD);
639           }
640         }
641       }
642       break;
643     }
644     case Expr::StringLiteralClass:
645       return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
646     case Expr::ObjCEncodeExprClass:
647       return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
648     case Expr::ObjCStringLiteralClass: {
649       ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
650       llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(SL);
651       return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
652     }
653     case Expr::PredefinedExprClass: {
654       // __func__/__FUNCTION__ -> "".  __PRETTY_FUNCTION__ -> "top level".
655       std::string Str;
656       if (cast<PredefinedExpr>(E)->getIdentType() ==
657           PredefinedExpr::PrettyFunction)
658         Str = "top level";
659 
660       return CGM.GetAddrOfConstantCString(Str, ".tmp");
661     }
662     case Expr::AddrLabelExprClass: {
663       assert(CGF && "Invalid address of label expression outside function.");
664       unsigned id =
665           CGF->GetIDForAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
666       llvm::Constant *C =
667             llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), id);
668       return llvm::ConstantExpr::getIntToPtr(C, ConvertType(E->getType()));
669     }
670     case Expr::CallExprClass: {
671       CallExpr* CE = cast<CallExpr>(E);
672       if (CE->isBuiltinCall(CGM.getContext()) !=
673             Builtin::BI__builtin___CFStringMakeConstantString)
674         break;
675       const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
676       const StringLiteral *Literal = cast<StringLiteral>(Arg);
677       // FIXME: need to deal with UCN conversion issues.
678       return CGM.GetAddrOfConstantCFString(Literal);
679     }
680     case Expr::BlockExprClass: {
681       std::string FunctionName;
682       if (CGF)
683         FunctionName = CGF->CurFn->getName();
684       else
685         FunctionName = "global";
686 
687       return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
688     }
689     }
690 
691     return 0;
692   }
693 };
694 
695 }  // end anonymous namespace.
696 
697 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
698                                                 QualType DestType,
699                                                 CodeGenFunction *CGF) {
700   Expr::EvalResult Result;
701 
702   bool Success = false;
703 
704   if (DestType->isReferenceType())
705     Success = E->EvaluateAsLValue(Result, Context);
706   else
707     Success = E->Evaluate(Result, Context);
708 
709   if (Success) {
710     assert(!Result.HasSideEffects &&
711            "Constant expr should not have any side effects!");
712     switch (Result.Val.getKind()) {
713     case APValue::Uninitialized:
714       assert(0 && "Constant expressions should be initialized.");
715       return 0;
716     case APValue::LValue: {
717       const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
718       llvm::Constant *Offset =
719         llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
720                                Result.Val.getLValueOffset());
721 
722       llvm::Constant *C;
723       if (const Expr *LVBase = Result.Val.getLValueBase()) {
724         C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
725 
726         // Apply offset if necessary.
727         if (!Offset->isNullValue()) {
728           const llvm::Type *Type =
729             llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
730           llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type);
731           Casted = llvm::ConstantExpr::getGetElementPtr(Casted, &Offset, 1);
732           C = llvm::ConstantExpr::getBitCast(Casted, C->getType());
733         }
734 
735         // Convert to the appropriate type; this could be an lvalue for
736         // an integer.
737         if (isa<llvm::PointerType>(DestTy))
738           return llvm::ConstantExpr::getBitCast(C, DestTy);
739 
740         return llvm::ConstantExpr::getPtrToInt(C, DestTy);
741       } else {
742         C = Offset;
743 
744         // Convert to the appropriate type; this could be an lvalue for
745         // an integer.
746         if (isa<llvm::PointerType>(DestTy))
747           return llvm::ConstantExpr::getIntToPtr(C, DestTy);
748 
749         // If the types don't match this should only be a truncate.
750         if (C->getType() != DestTy)
751           return llvm::ConstantExpr::getTrunc(C, DestTy);
752 
753         return C;
754       }
755     }
756     case APValue::Int: {
757       llvm::Constant *C = llvm::ConstantInt::get(VMContext,
758                                                  Result.Val.getInt());
759 
760       if (C->getType() == llvm::Type::getInt1Ty(VMContext)) {
761         const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
762         C = llvm::ConstantExpr::getZExt(C, BoolTy);
763       }
764       return C;
765     }
766     case APValue::ComplexInt: {
767       llvm::Constant *Complex[2];
768 
769       Complex[0] = llvm::ConstantInt::get(VMContext,
770                                           Result.Val.getComplexIntReal());
771       Complex[1] = llvm::ConstantInt::get(VMContext,
772                                           Result.Val.getComplexIntImag());
773 
774       // FIXME: the target may want to specify that this is packed.
775       return llvm::ConstantStruct::get(VMContext, Complex, 2, false);
776     }
777     case APValue::Float:
778       return llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
779     case APValue::ComplexFloat: {
780       llvm::Constant *Complex[2];
781 
782       Complex[0] = llvm::ConstantFP::get(VMContext,
783                                          Result.Val.getComplexFloatReal());
784       Complex[1] = llvm::ConstantFP::get(VMContext,
785                                          Result.Val.getComplexFloatImag());
786 
787       // FIXME: the target may want to specify that this is packed.
788       return llvm::ConstantStruct::get(VMContext, Complex, 2, false);
789     }
790     case APValue::Vector: {
791       llvm::SmallVector<llvm::Constant *, 4> Inits;
792       unsigned NumElts = Result.Val.getVectorLength();
793 
794       for (unsigned i = 0; i != NumElts; ++i) {
795         APValue &Elt = Result.Val.getVectorElt(i);
796         if (Elt.isInt())
797           Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
798         else
799           Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
800       }
801       return llvm::ConstantVector::get(&Inits[0], Inits.size());
802     }
803     }
804   }
805 
806   llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
807   if (C && C->getType() == llvm::Type::getInt1Ty(VMContext)) {
808     const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
809     C = llvm::ConstantExpr::getZExt(C, BoolTy);
810   }
811   return C;
812 }
813 
814 static inline bool isDataMemberPointerType(QualType T) {
815   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
816     return !MPT->getPointeeType()->isFunctionType();
817 
818   return false;
819 }
820 
821 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
822   // No need to check for member pointers when not compiling C++.
823   if (!getContext().getLangOptions().CPlusPlus)
824     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
825 
826   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
827 
828     QualType ElementTy = CAT->getElementType();
829 
830     // FIXME: Handle arrays of structs that contain member pointers.
831     if (isDataMemberPointerType(Context.getBaseElementType(ElementTy))) {
832       llvm::Constant *Element = EmitNullConstant(ElementTy);
833       uint64_t NumElements = CAT->getSize().getZExtValue();
834       std::vector<llvm::Constant *> Array(NumElements);
835       for (uint64_t i = 0; i != NumElements; ++i)
836         Array[i] = Element;
837 
838       const llvm::ArrayType *ATy =
839         cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
840       return llvm::ConstantArray::get(ATy, Array);
841     }
842   }
843 
844   if (const RecordType *RT = T->getAs<RecordType>()) {
845     const RecordDecl *RD = RT->getDecl();
846     // FIXME: It would be better if there was a way to explicitly compute the
847     // record layout instead of converting to a type.
848     Types.ConvertTagDeclType(RD);
849 
850     const CGRecordLayout &Layout = Types.getCGRecordLayout(RD);
851     if (Layout.containsMemberPointer()) {
852       assert(0 && "FIXME: No support for structs with member pointers yet!");
853     }
854   }
855 
856   // FIXME: Handle structs that contain member pointers.
857   if (isDataMemberPointerType(T))
858     return llvm::Constant::getAllOnesValue(getTypes().ConvertTypeForMem(T));
859 
860   return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
861 }
862