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 = CGM.getLLVMContext().getArrayType(Ty, NumBytes);
87 
88           llvm::Constant *Padding = CGM.getLLVMContext().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 = CGM.getLLVMContext().getArrayType(Ty, NumBytes);
255 
256     llvm::Constant *C = CGM.getLLVMContext().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(const InitListExpr *ILE) {
274     RecordDecl *RD = ILE->getType()->getAsRecordType()->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 (Field->isBitField()) {
284         if (!Field->getIdentifier())
285           continue;
286 
287         if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
288                             ILE->getInit(ElementNo)))
289           return false;
290       } else {
291         if (!AppendField(*Field, Layout.getFieldOffset(FieldNo),
292                          ILE->getInit(ElementNo)))
293           return false;
294       }
295 
296       ElementNo++;
297     }
298 
299     uint64_t LayoutSizeInBytes = Layout.getSize() / 8;
300 
301     if (NextFieldOffsetInBytes > LayoutSizeInBytes) {
302       // If the struct is bigger than the size of the record type,
303       // we must have a flexible array member at the end.
304       assert(RD->hasFlexibleArrayMember() &&
305              "Must have flexible array member if struct is bigger than type!");
306 
307       // No tail padding is necessary.
308       return true;
309     }
310 
311     // Append tail padding if necessary.
312     AppendTailPadding(Layout.getSize());
313 
314     assert(Layout.getSize() / 8 == NextFieldOffsetInBytes &&
315            "Tail padding mismatch!");
316 
317     return true;
318   }
319 
320   unsigned getAlignment(const llvm::Constant *C) const {
321     if (Packed)
322       return 1;
323 
324     return CGM.getTargetData().getABITypeAlignment(C->getType());
325   }
326 
327   uint64_t getSizeInBytes(const llvm::Constant *C) const {
328     return CGM.getTargetData().getTypeAllocSize(C->getType());
329   }
330 
331 public:
332   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
333                                      const InitListExpr *ILE) {
334     ConstStructBuilder Builder(CGM, CGF);
335 
336     if (!Builder.Build(ILE))
337       return 0;
338 
339     llvm::Constant *Result =
340       CGM.getLLVMContext().getConstantStruct(Builder.Elements, Builder.Packed);
341 
342     assert(llvm::RoundUpToAlignment(Builder.NextFieldOffsetInBytes,
343                                     Builder.getAlignment(Result)) ==
344            Builder.getSizeInBytes(Result) && "Size mismatch!");
345 
346     return Result;
347   }
348 };
349 
350 class VISIBILITY_HIDDEN ConstExprEmitter :
351   public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
352   CodeGenModule &CGM;
353   CodeGenFunction *CGF;
354   llvm::LLVMContext &VMContext;
355 public:
356   ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
357     : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
358   }
359 
360   //===--------------------------------------------------------------------===//
361   //                            Visitor Methods
362   //===--------------------------------------------------------------------===//
363 
364   llvm::Constant *VisitStmt(Stmt *S) {
365     return 0;
366   }
367 
368   llvm::Constant *VisitParenExpr(ParenExpr *PE) {
369     return Visit(PE->getSubExpr());
370   }
371 
372   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
373     return Visit(E->getInitializer());
374   }
375 
376   llvm::Constant *VisitCastExpr(CastExpr* E) {
377     // GCC cast to union extension
378     if (E->getType()->isUnionType()) {
379       const llvm::Type *Ty = ConvertType(E->getType());
380       Expr *SubExpr = E->getSubExpr();
381       return EmitUnion(CGM.EmitConstantExpr(SubExpr, SubExpr->getType(), CGF),
382                        Ty);
383     }
384     // Explicit and implicit no-op casts
385     QualType Ty = E->getType(), SubTy = E->getSubExpr()->getType();
386     if (CGM.getContext().hasSameUnqualifiedType(Ty, SubTy)) {
387       return Visit(E->getSubExpr());
388     }
389     return 0;
390   }
391 
392   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
393     return Visit(DAE->getExpr());
394   }
395 
396   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
397     std::vector<llvm::Constant*> Elts;
398     const llvm::ArrayType *AType =
399         cast<llvm::ArrayType>(ConvertType(ILE->getType()));
400     unsigned NumInitElements = ILE->getNumInits();
401     // FIXME: Check for wide strings
402     // FIXME: Check for NumInitElements exactly equal to 1??
403     if (NumInitElements > 0 &&
404         (isa<StringLiteral>(ILE->getInit(0)) ||
405          isa<ObjCEncodeExpr>(ILE->getInit(0))) &&
406         ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType())
407       return Visit(ILE->getInit(0));
408     const llvm::Type *ElemTy = AType->getElementType();
409     unsigned NumElements = AType->getNumElements();
410 
411     // Initialising an array requires us to automatically
412     // initialise any elements that have not been initialised explicitly
413     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
414 
415     // Copy initializer elements.
416     unsigned i = 0;
417     bool RewriteType = false;
418     for (; i < NumInitableElts; ++i) {
419       Expr *Init = ILE->getInit(i);
420       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
421       if (!C)
422         return 0;
423       RewriteType |= (C->getType() != ElemTy);
424       Elts.push_back(C);
425     }
426 
427     // Initialize remaining array elements.
428     // FIXME: This doesn't handle member pointers correctly!
429     for (; i < NumElements; ++i)
430       Elts.push_back(VMContext.getNullValue(ElemTy));
431 
432     if (RewriteType) {
433       // FIXME: Try to avoid packing the array
434       std::vector<const llvm::Type*> Types;
435       for (unsigned i = 0; i < Elts.size(); ++i)
436         Types.push_back(Elts[i]->getType());
437       const llvm::StructType *SType = VMContext.getStructType(Types, true);
438       return VMContext.getConstantStruct(SType, Elts);
439     }
440 
441     return VMContext.getConstantArray(AType, Elts);
442   }
443 
444   void InsertBitfieldIntoStruct(std::vector<llvm::Constant*>& Elts,
445                                 FieldDecl* Field, Expr* E) {
446     // Calculate the value to insert
447     llvm::Constant *C = CGM.EmitConstantExpr(E, Field->getType(), CGF);
448     if (!C)
449       return;
450 
451     llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C);
452     if (!CI) {
453       CGM.ErrorUnsupported(E, "bitfield initialization");
454       return;
455     }
456     llvm::APInt V = CI->getValue();
457 
458     // Calculate information about the relevant field
459     const llvm::Type* Ty = CI->getType();
460     const llvm::TargetData &TD = CGM.getTypes().getTargetData();
461     unsigned size = TD.getTypeAllocSizeInBits(Ty);
462     CodeGenTypes::BitFieldInfo Info = CGM.getTypes().getBitFieldInfo(Field);
463     unsigned FieldOffset = Info.FieldNo * size;
464 
465     FieldOffset += Info.Start;
466 
467     // Find where to start the insertion
468     // FIXME: This is O(n^2) in the number of bit-fields!
469     // FIXME: This won't work if the struct isn't completely packed!
470     unsigned offset = 0, i = 0;
471     while (offset < (FieldOffset & -8))
472       offset += TD.getTypeAllocSizeInBits(Elts[i++]->getType());
473 
474     // Advance over 0 sized elements (must terminate in bounds since
475     // the bitfield must have a size).
476     while (TD.getTypeAllocSizeInBits(Elts[i]->getType()) == 0)
477       ++i;
478 
479     // Promote the size of V if necessary
480     // FIXME: This should never occur, but currently it can because initializer
481     // constants are cast to bool, and because clang is not enforcing bitfield
482     // width limits.
483     if (Info.Size > V.getBitWidth())
484       V.zext(Info.Size);
485 
486     // Insert the bits into the struct
487     // FIXME: This algorthm is only correct on X86!
488     // FIXME: THis algorthm assumes bit-fields only have byte-size elements!
489     unsigned bitsToInsert = Info.Size;
490     unsigned curBits = std::min(8 - (FieldOffset & 7), bitsToInsert);
491     unsigned byte = V.getLoBits(curBits).getZExtValue() << (FieldOffset & 7);
492     do {
493       llvm::Constant* byteC =
494         llvm::ConstantInt::get(llvm::Type::Int8Ty, byte);
495       Elts[i] = VMContext.getConstantExprOr(Elts[i], byteC);
496       ++i;
497       V = V.lshr(curBits);
498       bitsToInsert -= curBits;
499 
500       if (!bitsToInsert)
501         break;
502 
503       curBits = bitsToInsert > 8 ? 8 : bitsToInsert;
504       byte = V.getLoBits(curBits).getZExtValue();
505     } while (true);
506   }
507 
508   llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
509     // FIXME: Use the returned struct when the builder works well enough.
510     ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
511 
512     const llvm::StructType *SType =
513         cast<llvm::StructType>(ConvertType(ILE->getType()));
514     RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
515     std::vector<llvm::Constant*> Elts;
516 
517     // Initialize the whole structure to zero.
518     // FIXME: This doesn't handle member pointers correctly!
519     for (unsigned i = 0; i < SType->getNumElements(); ++i) {
520       const llvm::Type *FieldTy = SType->getElementType(i);
521       Elts.push_back(VMContext.getNullValue(FieldTy));
522     }
523 
524     // Copy initializer elements. Skip padding fields.
525     unsigned EltNo = 0;  // Element no in ILE
526     bool RewriteType = false;
527     for (RecordDecl::field_iterator Field = RD->field_begin(),
528                                  FieldEnd = RD->field_end();
529          EltNo < ILE->getNumInits() && Field != FieldEnd; ++Field) {
530       if (Field->isBitField()) {
531         if (!Field->getIdentifier())
532           continue;
533         InsertBitfieldIntoStruct(Elts, *Field, ILE->getInit(EltNo));
534       } else {
535         unsigned FieldNo = CGM.getTypes().getLLVMFieldNo(*Field);
536         llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(EltNo),
537                                                  Field->getType(), CGF);
538         if (!C) return 0;
539         RewriteType |= (C->getType() != Elts[FieldNo]->getType());
540         Elts[FieldNo] = C;
541       }
542       EltNo++;
543     }
544 
545     if (RewriteType) {
546       // FIXME: Make this work for non-packed structs
547       assert(SType->isPacked() && "Cannot recreate unpacked structs");
548       std::vector<const llvm::Type*> Types;
549       for (unsigned i = 0; i < Elts.size(); ++i)
550         Types.push_back(Elts[i]->getType());
551       SType = VMContext.getStructType(Types, true);
552     }
553 
554     return VMContext.getConstantStruct(SType, Elts);
555   }
556 
557   llvm::Constant *EmitUnion(llvm::Constant *C, const llvm::Type *Ty) {
558     if (!C)
559       return 0;
560 
561     // Build a struct with the union sub-element as the first member,
562     // and padded to the appropriate size
563     std::vector<llvm::Constant*> Elts;
564     std::vector<const llvm::Type*> Types;
565     Elts.push_back(C);
566     Types.push_back(C->getType());
567     unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType());
568     unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(Ty);
569 
570     assert(CurSize <= TotalSize && "Union size mismatch!");
571     if (unsigned NumPadBytes = TotalSize - CurSize) {
572       const llvm::Type *Ty = llvm::Type::Int8Ty;
573       if (NumPadBytes > 1)
574         Ty = VMContext.getArrayType(Ty, NumPadBytes);
575 
576       Elts.push_back(VMContext.getNullValue(Ty));
577       Types.push_back(Ty);
578     }
579 
580     llvm::StructType* STy = VMContext.getStructType(Types, false);
581     return VMContext.getConstantStruct(STy, Elts);
582   }
583 
584   llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
585     const llvm::Type *Ty = ConvertType(ILE->getType());
586 
587     FieldDecl* curField = ILE->getInitializedFieldInUnion();
588     if (!curField) {
589       // There's no field to initialize, so value-initialize the union.
590 #ifndef NDEBUG
591       // Make sure that it's really an empty and not a failure of
592       // semantic analysis.
593       RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
594       for (RecordDecl::field_iterator Field = RD->field_begin(),
595                                    FieldEnd = RD->field_end();
596            Field != FieldEnd; ++Field)
597         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
598 #endif
599       return VMContext.getNullValue(Ty);
600     }
601 
602     if (curField->isBitField()) {
603       // Create a dummy struct for bit-field insertion
604       unsigned NumElts = CGM.getTargetData().getTypeAllocSize(Ty);
605       llvm::Constant* NV =
606         VMContext.getNullValue(llvm::Type::Int8Ty);
607       std::vector<llvm::Constant*> Elts(NumElts, NV);
608 
609       InsertBitfieldIntoStruct(Elts, curField, ILE->getInit(0));
610       const llvm::ArrayType *RetTy =
611           VMContext.getArrayType(NV->getType(), NumElts);
612       return VMContext.getConstantArray(RetTy, Elts);
613     }
614 
615     llvm::Constant *InitElem;
616     if (ILE->getNumInits() > 0) {
617       Expr *Init = ILE->getInit(0);
618       InitElem = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
619     } else {
620       InitElem = CGM.EmitNullConstant(curField->getType());
621     }
622     return EmitUnion(InitElem, Ty);
623   }
624 
625   llvm::Constant *EmitVectorInitialization(InitListExpr *ILE) {
626     const llvm::VectorType *VType =
627         cast<llvm::VectorType>(ConvertType(ILE->getType()));
628     const llvm::Type *ElemTy = VType->getElementType();
629     std::vector<llvm::Constant*> Elts;
630     unsigned NumElements = VType->getNumElements();
631     unsigned NumInitElements = ILE->getNumInits();
632 
633     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
634 
635     // Copy initializer elements.
636     unsigned i = 0;
637     for (; i < NumInitableElts; ++i) {
638       Expr *Init = ILE->getInit(i);
639       llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
640       if (!C)
641         return 0;
642       Elts.push_back(C);
643     }
644 
645     for (; i < NumElements; ++i)
646       Elts.push_back(VMContext.getNullValue(ElemTy));
647 
648     return VMContext.getConstantVector(VType, Elts);
649   }
650 
651   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
652     return CGM.EmitNullConstant(E->getType());
653   }
654 
655   llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
656     if (ILE->getType()->isScalarType()) {
657       // We have a scalar in braces. Just use the first element.
658       if (ILE->getNumInits() > 0) {
659         Expr *Init = ILE->getInit(0);
660         return CGM.EmitConstantExpr(Init, Init->getType(), CGF);
661       }
662       return CGM.EmitNullConstant(ILE->getType());
663     }
664 
665     if (ILE->getType()->isArrayType())
666       return EmitArrayInitialization(ILE);
667 
668     if (ILE->getType()->isStructureType())
669       return EmitStructInitialization(ILE);
670 
671     if (ILE->getType()->isUnionType())
672       return EmitUnionInitialization(ILE);
673 
674     if (ILE->getType()->isVectorType())
675       return EmitVectorInitialization(ILE);
676 
677     assert(0 && "Unable to handle InitListExpr");
678     // Get rid of control reaches end of void function warning.
679     // Not reached.
680     return 0;
681   }
682 
683   llvm::Constant *VisitStringLiteral(StringLiteral *E) {
684     assert(!E->getType()->isPointerType() && "Strings are always arrays");
685 
686     // This must be a string initializing an array in a static initializer.
687     // Don't emit it as the address of the string, emit the string data itself
688     // as an inline array.
689     return VMContext.getConstantArray(CGM.GetStringForStringLiteral(E), false);
690   }
691 
692   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
693     // This must be an @encode initializing an array in a static initializer.
694     // Don't emit it as the address of the string, emit the string data itself
695     // as an inline array.
696     std::string Str;
697     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
698     const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
699 
700     // Resize the string to the right size, adding zeros at the end, or
701     // truncating as needed.
702     Str.resize(CAT->getSize().getZExtValue(), '\0');
703     return VMContext.getConstantArray(Str, false);
704   }
705 
706   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
707     return Visit(E->getSubExpr());
708   }
709 
710   // Utility methods
711   const llvm::Type *ConvertType(QualType T) {
712     return CGM.getTypes().ConvertType(T);
713   }
714 
715 public:
716   llvm::Constant *EmitLValue(Expr *E) {
717     switch (E->getStmtClass()) {
718     default: break;
719     case Expr::CompoundLiteralExprClass: {
720       // Note that due to the nature of compound literals, this is guaranteed
721       // to be the only use of the variable, so we just generate it here.
722       CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
723       llvm::Constant* C = Visit(CLE->getInitializer());
724       // FIXME: "Leaked" on failure.
725       if (C)
726         C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
727                                      E->getType().isConstQualified(),
728                                      llvm::GlobalValue::InternalLinkage,
729                                      C, ".compoundliteral");
730       return C;
731     }
732     case Expr::DeclRefExprClass:
733     case Expr::QualifiedDeclRefExprClass: {
734       NamedDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
735       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
736         return CGM.GetAddrOfFunction(GlobalDecl(FD));
737       if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
738         // We can never refer to a variable with local storage.
739         if (!VD->hasLocalStorage()) {
740           if (VD->isFileVarDecl() || VD->hasExternalStorage())
741             return CGM.GetAddrOfGlobalVar(VD);
742           else if (VD->isBlockVarDecl()) {
743             assert(CGF && "Can't access static local vars without CGF");
744             return CGF->GetAddrOfStaticLocalVar(VD);
745           }
746         }
747       }
748       break;
749     }
750     case Expr::StringLiteralClass:
751       return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
752     case Expr::ObjCEncodeExprClass:
753       return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
754     case Expr::ObjCStringLiteralClass: {
755       ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
756       llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(SL);
757       return VMContext.getConstantExprBitCast(C, ConvertType(E->getType()));
758     }
759     case Expr::PredefinedExprClass: {
760       // __func__/__FUNCTION__ -> "".  __PRETTY_FUNCTION__ -> "top level".
761       std::string Str;
762       if (cast<PredefinedExpr>(E)->getIdentType() ==
763           PredefinedExpr::PrettyFunction)
764         Str = "top level";
765 
766       return CGM.GetAddrOfConstantCString(Str, ".tmp");
767     }
768     case Expr::AddrLabelExprClass: {
769       assert(CGF && "Invalid address of label expression outside function.");
770       unsigned id = CGF->GetIDForAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
771       llvm::Constant *C = llvm::ConstantInt::get(llvm::Type::Int32Ty, id);
772       return VMContext.getConstantExprIntToPtr(C, ConvertType(E->getType()));
773     }
774     case Expr::CallExprClass: {
775       CallExpr* CE = cast<CallExpr>(E);
776       if (CE->isBuiltinCall(CGM.getContext()) !=
777             Builtin::BI__builtin___CFStringMakeConstantString)
778         break;
779       const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
780       const StringLiteral *Literal = cast<StringLiteral>(Arg);
781       // FIXME: need to deal with UCN conversion issues.
782       return CGM.GetAddrOfConstantCFString(Literal);
783     }
784     case Expr::BlockExprClass: {
785       std::string FunctionName;
786       if (CGF)
787         FunctionName = CGF->CurFn->getName();
788       else
789         FunctionName = "global";
790 
791       return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
792     }
793     }
794 
795     return 0;
796   }
797 };
798 
799 }  // end anonymous namespace.
800 
801 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
802                                                 QualType DestType,
803                                                 CodeGenFunction *CGF) {
804   Expr::EvalResult Result;
805 
806   bool Success = false;
807 
808   if (DestType->isReferenceType())
809     Success = E->EvaluateAsLValue(Result, Context);
810   else
811     Success = E->Evaluate(Result, Context);
812 
813   if (Success) {
814     assert(!Result.HasSideEffects &&
815            "Constant expr should not have any side effects!");
816     switch (Result.Val.getKind()) {
817     case APValue::Uninitialized:
818       assert(0 && "Constant expressions should be initialized.");
819       return 0;
820     case APValue::LValue: {
821       const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
822       llvm::Constant *Offset =
823         llvm::ConstantInt::get(llvm::Type::Int64Ty,
824                                Result.Val.getLValueOffset());
825 
826       llvm::Constant *C;
827       if (const Expr *LVBase = Result.Val.getLValueBase()) {
828         C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
829 
830         // Apply offset if necessary.
831         if (!Offset->isNullValue()) {
832           const llvm::Type *Type =
833             VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
834           llvm::Constant *Casted = VMContext.getConstantExprBitCast(C, Type);
835           Casted = VMContext.getConstantExprGetElementPtr(Casted, &Offset, 1);
836           C = VMContext.getConstantExprBitCast(Casted, C->getType());
837         }
838 
839         // Convert to the appropriate type; this could be an lvalue for
840         // an integer.
841         if (isa<llvm::PointerType>(DestTy))
842           return VMContext.getConstantExprBitCast(C, DestTy);
843 
844         return VMContext.getConstantExprPtrToInt(C, DestTy);
845       } else {
846         C = Offset;
847 
848         // Convert to the appropriate type; this could be an lvalue for
849         // an integer.
850         if (isa<llvm::PointerType>(DestTy))
851           return VMContext.getConstantExprIntToPtr(C, DestTy);
852 
853         // If the types don't match this should only be a truncate.
854         if (C->getType() != DestTy)
855           return VMContext.getConstantExprTrunc(C, DestTy);
856 
857         return C;
858       }
859     }
860     case APValue::Int: {
861       llvm::Constant *C = llvm::ConstantInt::get(VMContext,
862                                                  Result.Val.getInt());
863 
864       if (C->getType() == llvm::Type::Int1Ty) {
865         const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
866         C = VMContext.getConstantExprZExt(C, BoolTy);
867       }
868       return C;
869     }
870     case APValue::ComplexInt: {
871       llvm::Constant *Complex[2];
872 
873       Complex[0] = llvm::ConstantInt::get(VMContext,
874                                           Result.Val.getComplexIntReal());
875       Complex[1] = llvm::ConstantInt::get(VMContext,
876                                           Result.Val.getComplexIntImag());
877 
878       return VMContext.getConstantStruct(Complex, 2);
879     }
880     case APValue::Float:
881       return VMContext.getConstantFP(Result.Val.getFloat());
882     case APValue::ComplexFloat: {
883       llvm::Constant *Complex[2];
884 
885       Complex[0] = VMContext.getConstantFP(Result.Val.getComplexFloatReal());
886       Complex[1] = VMContext.getConstantFP(Result.Val.getComplexFloatImag());
887 
888       return VMContext.getConstantStruct(Complex, 2);
889     }
890     case APValue::Vector: {
891       llvm::SmallVector<llvm::Constant *, 4> Inits;
892       unsigned NumElts = Result.Val.getVectorLength();
893 
894       for (unsigned i = 0; i != NumElts; ++i) {
895         APValue &Elt = Result.Val.getVectorElt(i);
896         if (Elt.isInt())
897           Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
898         else
899           Inits.push_back(VMContext.getConstantFP(Elt.getFloat()));
900       }
901       return VMContext.getConstantVector(&Inits[0], Inits.size());
902     }
903     }
904   }
905 
906   llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
907   if (C && C->getType() == llvm::Type::Int1Ty) {
908     const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
909     C = VMContext.getConstantExprZExt(C, BoolTy);
910   }
911   return C;
912 }
913 
914 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
915   // Always return an LLVM null constant for now; this will change when we
916   // get support for IRGen of member pointers.
917   return getLLVMContext().getNullValue(getTypes().ConvertType(T));
918 }
919