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