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