1 //===--- CGExpr.cpp - Emit LLVM Code from 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 Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/AST.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Target/TargetData.h"
24 using namespace clang;
25 using namespace CodeGen;
26 
27 //===--------------------------------------------------------------------===//
28 //                        Miscellaneous Helper Methods
29 //===--------------------------------------------------------------------===//
30 
31 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
32 /// block.
33 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
34                                                     const char *Name) {
35   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
36 }
37 
38 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
39 /// expression and compare the result against zero, returning an Int1Ty value.
40 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
41   QualType BoolTy = getContext().BoolTy;
42   if (!E->getType()->isAnyComplexType())
43     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
44 
45   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
46 }
47 
48 /// EmitAnyExpr - Emit code to compute the specified expression which can have
49 /// any type.  The result is returned as an RValue struct.  If this is an
50 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
51 /// the result should be returned.
52 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
53                                     bool isAggLocVolatile) {
54   if (!hasAggregateLLVMType(E->getType()))
55     return RValue::get(EmitScalarExpr(E));
56   else if (E->getType()->isAnyComplexType())
57     return RValue::getComplex(EmitComplexExpr(E));
58 
59   EmitAggExpr(E, AggLoc, isAggLocVolatile);
60   return RValue::getAggregate(AggLoc);
61 }
62 
63 /// getAccessedFieldNo - Given an encoded value and a result number, return
64 /// the input field number being accessed.
65 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
66                                              const llvm::Constant *Elts) {
67   if (isa<llvm::ConstantAggregateZero>(Elts))
68     return 0;
69 
70   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
71 }
72 
73 
74 //===----------------------------------------------------------------------===//
75 //                         LValue Expression Emission
76 //===----------------------------------------------------------------------===//
77 
78 /// EmitLValue - Emit code to compute a designator that specifies the location
79 /// of the expression.
80 ///
81 /// This can return one of two things: a simple address or a bitfield
82 /// reference.  In either case, the LLVM Value* in the LValue structure is
83 /// guaranteed to be an LLVM pointer type.
84 ///
85 /// If this returns a bitfield reference, nothing about the pointee type of
86 /// the LLVM value is known: For example, it may not be a pointer to an
87 /// integer.
88 ///
89 /// If this returns a normal address, and if the lvalue's C type is fixed
90 /// size, this method guarantees that the returned pointer type will point to
91 /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
92 /// variable length type, this is not possible.
93 ///
94 LValue CodeGenFunction::EmitLValue(const Expr *E) {
95   switch (E->getStmtClass()) {
96   default: {
97     printf("Statement class: %d\n", E->getStmtClass());
98     WarnUnsupported(E, "l-value expression");
99     llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
100     return LValue::MakeAddr(llvm::UndefValue::get(Ty));
101   }
102 
103   case Expr::CallExprClass: return EmitCallExprLValue(cast<CallExpr>(E));
104   case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
105   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
106   case Expr::PreDefinedExprClass:
107     return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
108   case Expr::StringLiteralClass:
109     return EmitStringLiteralLValue(cast<StringLiteral>(E));
110 
111   case Expr::ObjCIvarRefExprClass:
112     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
113 
114   case Expr::UnaryOperatorClass:
115     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
116   case Expr::ArraySubscriptExprClass:
117     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
118   case Expr::ExtVectorElementExprClass:
119     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
120   case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E));
121   case Expr::CompoundLiteralExprClass:
122     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
123   }
124 }
125 
126 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
127 /// this method emits the address of the lvalue, then loads the result as an
128 /// rvalue, returning the rvalue.
129 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
130   if (LV.isSimple()) {
131     llvm::Value *Ptr = LV.getAddress();
132     const llvm::Type *EltTy =
133       cast<llvm::PointerType>(Ptr->getType())->getElementType();
134 
135     // Simple scalar l-value.
136     if (EltTy->isFirstClassType()) {
137       llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
138 
139       // Bool can have different representation in memory than in registers.
140       if (ExprType->isBooleanType()) {
141         if (V->getType() != llvm::Type::Int1Ty)
142           V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool");
143       }
144 
145       return RValue::get(V);
146     }
147 
148     assert(ExprType->isFunctionType() && "Unknown scalar value");
149     return RValue::get(Ptr);
150   }
151 
152   if (LV.isVectorElt()) {
153     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
154     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
155                                                     "vecext"));
156   }
157 
158   // If this is a reference to a subset of the elements of a vector, either
159   // shuffle the input or extract/insert them as appropriate.
160   if (LV.isExtVectorElt())
161     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
162 
163   if (LV.isBitfield())
164     return EmitLoadOfBitfieldLValue(LV, ExprType);
165 
166   assert(0 && "Unknown LValue type!");
167   //an invalid RValue, but the assert will
168   //ensure that this point is never reached
169   return RValue();
170 }
171 
172 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
173                                                  QualType ExprType) {
174   llvm::Value *Ptr = LV.getBitfieldAddr();
175   const llvm::Type *EltTy =
176     cast<llvm::PointerType>(Ptr->getType())->getElementType();
177   unsigned EltTySize = EltTy->getPrimitiveSizeInBits();
178   unsigned short BitfieldSize = LV.getBitfieldSize();
179   unsigned short EndBit = LV.getBitfieldStartBit() + BitfieldSize;
180 
181   llvm::Value *V = Builder.CreateLoad(Ptr, "tmp");
182 
183   llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - EndBit);
184   V = Builder.CreateShl(V, ShAmt, "tmp");
185 
186   ShAmt = llvm::ConstantInt::get(EltTy, EltTySize - BitfieldSize);
187   V = LV.isBitfieldSigned() ?
188     Builder.CreateAShr(V, ShAmt, "tmp") :
189     Builder.CreateLShr(V, ShAmt, "tmp");
190 
191   // The bitfield type and the normal type differ when the storage sizes
192   // differ (currently just _Bool).
193   V = Builder.CreateIntCast(V, ConvertType(ExprType), false, "tmp");
194 
195   return RValue::get(V);
196 }
197 
198 // If this is a reference to a subset of the elements of a vector, either
199 // shuffle the input or extract/insert them as appropriate.
200 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
201                                                          QualType ExprType) {
202   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), "tmp");
203 
204   const llvm::Constant *Elts = LV.getExtVectorElts();
205 
206   // If the result of the expression is a non-vector type, we must be
207   // extracting a single element.  Just codegen as an extractelement.
208   const VectorType *ExprVT = ExprType->getAsVectorType();
209   if (!ExprVT) {
210     unsigned InIdx = getAccessedFieldNo(0, Elts);
211     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
212     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
213   }
214 
215   // If the source and destination have the same number of elements, use a
216   // vector shuffle instead of insert/extracts.
217   unsigned NumResultElts = ExprVT->getNumElements();
218   unsigned NumSourceElts =
219     cast<llvm::VectorType>(Vec->getType())->getNumElements();
220 
221   if (NumResultElts == NumSourceElts) {
222     llvm::SmallVector<llvm::Constant*, 4> Mask;
223     for (unsigned i = 0; i != NumResultElts; ++i) {
224       unsigned InIdx = getAccessedFieldNo(i, Elts);
225       Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
226     }
227 
228     llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
229     Vec = Builder.CreateShuffleVector(Vec,
230                                       llvm::UndefValue::get(Vec->getType()),
231                                       MaskV, "tmp");
232     return RValue::get(Vec);
233   }
234 
235   // Start out with an undef of the result type.
236   llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
237 
238   // Extract/Insert each element of the result.
239   for (unsigned i = 0; i != NumResultElts; ++i) {
240     unsigned InIdx = getAccessedFieldNo(i, Elts);
241     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
242     Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
243 
244     llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
245     Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
246   }
247 
248   return RValue::get(Result);
249 }
250 
251 
252 
253 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
254 /// lvalue, where both are guaranteed to the have the same type, and that type
255 /// is 'Ty'.
256 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
257                                              QualType Ty) {
258   if (!Dst.isSimple()) {
259     if (Dst.isVectorElt()) {
260       // Read/modify/write the vector, inserting the new element.
261       // FIXME: Volatility.
262       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
263       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
264                                         Dst.getVectorIdx(), "vecins");
265       Builder.CreateStore(Vec, Dst.getVectorAddr());
266       return;
267     }
268 
269     // If this is an update of extended vector elements, insert them as
270     // appropriate.
271     if (Dst.isExtVectorElt())
272       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
273 
274     if (Dst.isBitfield())
275       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
276 
277     assert(0 && "Unknown LValue type");
278   }
279 
280   llvm::Value *DstAddr = Dst.getAddress();
281   assert(Src.isScalar() && "Can't emit an agg store with this method");
282   // FIXME: Handle volatility etc.
283   const llvm::Type *SrcTy = Src.getScalarVal()->getType();
284   const llvm::PointerType *DstPtr = cast<llvm::PointerType>(DstAddr->getType());
285   const llvm::Type *AddrTy = DstPtr->getElementType();
286   unsigned AS = DstPtr->getAddressSpace();
287 
288   if (AddrTy != SrcTy)
289     DstAddr = Builder.CreateBitCast(DstAddr,
290                                     llvm::PointerType::get(SrcTy, AS),
291                                     "storetmp");
292   Builder.CreateStore(Src.getScalarVal(), DstAddr);
293 }
294 
295 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
296                                                      QualType Ty) {
297   unsigned short StartBit = Dst.getBitfieldStartBit();
298   unsigned short BitfieldSize = Dst.getBitfieldSize();
299   llvm::Value *Ptr = Dst.getBitfieldAddr();
300 
301   llvm::Value *NewVal = Src.getScalarVal();
302   llvm::Value *OldVal = Builder.CreateLoad(Ptr, "tmp");
303 
304   // The bitfield type and the normal type differ when the storage sizes
305   // differ (currently just _Bool).
306   const llvm::Type *EltTy = OldVal->getType();
307   unsigned EltTySize = CGM.getTargetData().getABITypeSizeInBits(EltTy);
308 
309   NewVal = Builder.CreateIntCast(NewVal, EltTy, false, "tmp");
310 
311   // Move the bits into the appropriate location
312   llvm::Value *ShAmt = llvm::ConstantInt::get(EltTy, StartBit);
313   NewVal = Builder.CreateShl(NewVal, ShAmt, "tmp");
314 
315   llvm::Constant *Mask = llvm::ConstantInt::get(
316            llvm::APInt::getBitsSet(EltTySize, StartBit,
317                                    StartBit + BitfieldSize));
318 
319   // Mask out any bits that shouldn't be set in the result.
320   NewVal = Builder.CreateAnd(NewVal, Mask, "tmp");
321 
322   // Next, mask out the bits this bit-field should include from the old value.
323   Mask = llvm::ConstantExpr::getNot(Mask);
324   OldVal = Builder.CreateAnd(OldVal, Mask, "tmp");
325 
326   // Finally, merge the two together and store it.
327   NewVal = Builder.CreateOr(OldVal, NewVal, "tmp");
328 
329   Builder.CreateStore(NewVal, Ptr);
330 }
331 
332 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
333                                                                LValue Dst,
334                                                                QualType Ty) {
335   // This access turns into a read/modify/write of the vector.  Load the input
336   // value now.
337   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), "tmp");
338   // FIXME: Volatility.
339   const llvm::Constant *Elts = Dst.getExtVectorElts();
340 
341   llvm::Value *SrcVal = Src.getScalarVal();
342 
343   if (const VectorType *VTy = Ty->getAsVectorType()) {
344     unsigned NumSrcElts = VTy->getNumElements();
345 
346     // Extract/Insert each element.
347     for (unsigned i = 0; i != NumSrcElts; ++i) {
348       llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
349       Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
350 
351       unsigned Idx = getAccessedFieldNo(i, Elts);
352       llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
353       Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
354     }
355   } else {
356     // If the Src is a scalar (not a vector) it must be updating one element.
357     unsigned InIdx = getAccessedFieldNo(0, Elts);
358     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
359     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
360   }
361 
362   Builder.CreateStore(Vec, Dst.getExtVectorAddr());
363 }
364 
365 
366 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
367   const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
368 
369   if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD))) {
370     if (VD->getStorageClass() == VarDecl::Extern)
371       return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false));
372     else {
373       llvm::Value *V = LocalDeclMap[VD];
374       assert(V && "BlockVarDecl not entered in LocalDeclMap?");
375       return LValue::MakeAddr(V);
376     }
377   } else if (VD && VD->isFileVarDecl()) {
378     return LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD, false));
379   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
380     return LValue::MakeAddr(CGM.GetAddrOfFunctionDecl(FD, false));
381   }
382   assert(0 && "Unimp declref");
383   //an invalid LValue, but the assert will
384   //ensure that this point is never reached.
385   return LValue();
386 }
387 
388 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
389   // __extension__ doesn't affect lvalue-ness.
390   if (E->getOpcode() == UnaryOperator::Extension)
391     return EmitLValue(E->getSubExpr());
392 
393   switch (E->getOpcode()) {
394   default: assert(0 && "Unknown unary operator lvalue!");
395   case UnaryOperator::Deref:
396     return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
397   case UnaryOperator::Real:
398   case UnaryOperator::Imag:
399     LValue LV = EmitLValue(E->getSubExpr());
400     unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
401     return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
402                                                     Idx, "idx"));
403   }
404 }
405 
406 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
407   assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
408   // Get the string data
409   const char *StrData = E->getStrData();
410   unsigned Len = E->getByteLength();
411   std::string StringLiteral(StrData, StrData+Len);
412 
413   // Resize the string to the right size
414   const ConstantArrayType *CAT = E->getType()->getAsConstantArrayType();
415   uint64_t RealLen = CAT->getSize().getZExtValue();
416   StringLiteral.resize(RealLen, '\0');
417 
418   return LValue::MakeAddr(CGM.GetAddrOfConstantString(StringLiteral));
419 }
420 
421 LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
422   std::string FunctionName;
423   if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) {
424     FunctionName = FD->getName();
425   }
426   else {
427     assert(0 && "Attempting to load predefined constant for invalid decl type");
428   }
429   std::string GlobalVarName;
430 
431   switch (E->getIdentType()) {
432     default:
433       assert(0 && "unknown pre-defined ident type");
434     case PreDefinedExpr::Func:
435       GlobalVarName = "__func__.";
436       break;
437     case PreDefinedExpr::Function:
438       GlobalVarName = "__FUNCTION__.";
439       break;
440     case PreDefinedExpr::PrettyFunction:
441       // FIXME:: Demangle C++ method names
442       GlobalVarName = "__PRETTY_FUNCTION__.";
443       break;
444   }
445 
446   GlobalVarName += FunctionName;
447 
448   // FIXME: Can cache/reuse these within the module.
449   llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
450 
451   // Create a global variable for this.
452   C = new llvm::GlobalVariable(C->getType(), true,
453                                llvm::GlobalValue::InternalLinkage,
454                                C, GlobalVarName, CurFn->getParent());
455   return LValue::MakeAddr(C);
456 }
457 
458 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
459   // The index must always be an integer, which is not an aggregate.  Emit it.
460   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
461 
462   // If the base is a vector type, then we are forming a vector element lvalue
463   // with this subscript.
464   if (E->getLHS()->getType()->isVectorType()) {
465     // Emit the vector as an lvalue to get its address.
466     LValue LHS = EmitLValue(E->getLHS());
467     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
468     // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
469     return LValue::MakeVectorElt(LHS.getAddress(), Idx);
470   }
471 
472   // The base must be a pointer, which is not an aggregate.  Emit it.
473   llvm::Value *Base = EmitScalarExpr(E->getBase());
474 
475   // Extend or truncate the index type to 32 or 64-bits.
476   QualType IdxTy  = E->getIdx()->getType();
477   bool IdxSigned = IdxTy->isSignedIntegerType();
478   unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
479   if (IdxBitwidth != LLVMPointerWidth)
480     Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
481                                 IdxSigned, "idxprom");
482 
483   // We know that the pointer points to a type of the correct size, unless the
484   // size is a VLA.
485   if (!E->getType()->isConstantSizeType())
486     assert(0 && "VLA idx not implemented");
487   return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
488 }
489 
490 static
491 llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) {
492   llvm::SmallVector<llvm::Constant *, 4> CElts;
493 
494   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
495     CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i]));
496 
497   return llvm::ConstantVector::get(&CElts[0], CElts.size());
498 }
499 
500 LValue CodeGenFunction::
501 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
502   // Emit the base vector as an l-value.
503   LValue Base = EmitLValue(E->getBase());
504 
505   // Encode the element access list into a vector of unsigned indices.
506   llvm::SmallVector<unsigned, 4> Indices;
507   E->getEncodedElementAccess(Indices);
508 
509   if (Base.isSimple()) {
510     llvm::Constant *CV = GenerateConstantVector(Indices);
511     return LValue::MakeExtVectorElt(Base.getAddress(), CV);
512   }
513   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
514 
515   llvm::Constant *BaseElts = Base.getExtVectorElts();
516   llvm::SmallVector<llvm::Constant *, 4> CElts;
517 
518   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
519     if (isa<llvm::ConstantAggregateZero>(BaseElts))
520       CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
521     else
522       CElts.push_back(BaseElts->getOperand(Indices[i]));
523   }
524   llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
525   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV);
526 }
527 
528 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
529   bool isUnion = false;
530   Expr *BaseExpr = E->getBase();
531   llvm::Value *BaseValue = NULL;
532 
533   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
534   if (E->isArrow()) {
535     BaseValue = EmitScalarExpr(BaseExpr);
536     const PointerType *PTy =
537       cast<PointerType>(BaseExpr->getType().getCanonicalType());
538     if (PTy->getPointeeType()->isUnionType())
539       isUnion = true;
540   }
541   else {
542     LValue BaseLV = EmitLValue(BaseExpr);
543     // FIXME: this isn't right for bitfields.
544     BaseValue = BaseLV.getAddress();
545     if (BaseExpr->getType()->isUnionType())
546       isUnion = true;
547   }
548 
549   FieldDecl *Field = E->getMemberDecl();
550   return EmitLValueForField(BaseValue, Field, isUnion);
551 }
552 
553 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
554                                            FieldDecl* Field,
555                                            bool isUnion)
556 {
557   llvm::Value *V;
558   unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
559 
560   if (!Field->isBitField()) {
561     V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
562   } else {
563     // FIXME: CodeGenTypes should expose a method to get the appropriate
564     // type for FieldTy (the appropriate type is ABI-dependent).
565     unsigned EltTySize =
566       CGM.getTargetData().getABITypeSizeInBits(ConvertType(Field->getType()));
567     const llvm::Type *FieldTy = llvm::IntegerType::get(EltTySize);
568     const llvm::PointerType *BaseTy =
569       cast<llvm::PointerType>(BaseValue->getType());
570     unsigned AS = BaseTy->getAddressSpace();
571     BaseValue = Builder.CreateBitCast(BaseValue,
572                                       llvm::PointerType::get(FieldTy, AS),
573                                       "tmp");
574     V = Builder.CreateGEP(BaseValue,
575                           llvm::ConstantInt::get(llvm::Type::Int32Ty, idx),
576                           "tmp");
577   }
578 
579   // Match union field type.
580   if (isUnion) {
581     const llvm::Type * FieldTy = ConvertType(Field->getType());
582     const llvm::PointerType * BaseTy =
583       cast<llvm::PointerType>(BaseValue->getType());
584     unsigned AS = BaseTy->getAddressSpace();
585     V = Builder.CreateBitCast(V,
586                               llvm::PointerType::get(FieldTy, AS),
587                               "tmp");
588   }
589 
590   if (!Field->isBitField())
591     return LValue::MakeAddr(V);
592 
593   CodeGenTypes::BitFieldInfo bitFieldInfo =
594     CGM.getTypes().getBitFieldInfo(Field);
595   return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
596                               Field->getType()->isSignedIntegerType());
597 }
598 
599 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E) {
600   const llvm::Type *LTy = ConvertType(E->getType());
601   llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
602 
603   const Expr* InitExpr = E->getInitializer();
604   LValue Result = LValue::MakeAddr(DeclPtr);
605 
606   if (E->getType()->isComplexType()) {
607     EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
608   } else if (hasAggregateLLVMType(E->getType())) {
609     EmitAnyExpr(InitExpr, DeclPtr, false);
610   } else {
611     EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
612   }
613 
614   return Result;
615 }
616 
617 //===--------------------------------------------------------------------===//
618 //                             Expression Emission
619 //===--------------------------------------------------------------------===//
620 
621 
622 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
623   if (const ImplicitCastExpr *IcExpr =
624       dyn_cast<const ImplicitCastExpr>(E->getCallee()))
625     if (const DeclRefExpr *DRExpr =
626         dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
627       if (const FunctionDecl *FDecl =
628           dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
629         if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
630           return EmitBuiltinExpr(builtinID, E);
631 
632   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
633   return EmitCallExpr(Callee, E->getCallee()->getType(),
634                       E->arg_begin(), E->getNumArgs());
635 }
636 
637 RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr, Expr *const *Args,
638                                      unsigned NumArgs) {
639   llvm::Value *Callee = EmitScalarExpr(FnExpr);
640   return EmitCallExpr(Callee, FnExpr->getType(), Args, NumArgs);
641 }
642 
643 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
644   // Can only get l-value for call expression returning aggregate type
645   RValue RV = EmitCallExpr(E);
646   return LValue::MakeAddr(RV.getAggregateAddr());
647 }
648 
649 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
650   // Objective-C objects are traditionally C structures with their layout
651   // defined at compile-time.  In some implementations, their layout is not
652   // defined until run time in order to allow instance variables to be added to
653   // a class without recompiling all of the subclasses.  If this is the case
654   // then the CGObjCRuntime subclass must return true to LateBoundIvars and
655   // implement the lookup itself.
656   if (CGM.getObjCRuntime()->LateBoundIVars()) {
657     assert(0 && "FIXME: Implement support for late-bound instance variables");
658     return LValue(); // Not reached.
659   }
660 
661   // Get a structure type for the object
662   QualType ExprTy = E->getBase()->getType();
663   const llvm::Type *ObjectType = ConvertType(ExprTy);
664   // TODO:  Add a special case for isa (index 0)
665   // Work out which index the ivar is
666   const ObjCIvarDecl *Decl = E->getDecl();
667   unsigned Index = CGM.getTypes().getLLVMFieldNo(Decl);
668 
669   // Get object pointer and coerce object pointer to correct type.
670   llvm::Value *Object = EmitLValue(E->getBase()).getAddress();
671   Object = Builder.CreateLoad(Object, E->getDecl()->getName());
672   if (Object->getType() != ObjectType)
673     Object = Builder.CreateBitCast(Object, ObjectType);
674 
675 
676   // Return a pointer to the right element.
677   return LValue::MakeAddr(Builder.CreateStructGEP(Object, Index,
678                                                   Decl->getName()));
679 }
680 
681 RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType FnType,
682                                      Expr *const *ArgExprs, unsigned NumArgs) {
683   // The callee type will always be a pointer to function type, get the function
684   // type.
685   FnType = cast<PointerType>(FnType.getCanonicalType())->getPointeeType();
686   QualType ResultType = cast<FunctionType>(FnType)->getResultType();
687 
688   llvm::SmallVector<llvm::Value*, 16> Args;
689 
690   // Handle struct-return functions by passing a pointer to the location that
691   // we would like to return into.
692   if (hasAggregateLLVMType(ResultType)) {
693     // Create a temporary alloca to hold the result of the call. :(
694     Args.push_back(CreateTempAlloca(ConvertType(ResultType)));
695     // FIXME: set the stret attribute on the argument.
696   }
697 
698   for (unsigned i = 0, e = NumArgs; i != e; ++i) {
699     QualType ArgTy = ArgExprs[i]->getType();
700 
701     if (!hasAggregateLLVMType(ArgTy)) {
702       // Scalar argument is passed by-value.
703       Args.push_back(EmitScalarExpr(ArgExprs[i]));
704     } else if (ArgTy->isAnyComplexType()) {
705       // Make a temporary alloca to pass the argument.
706       llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
707       EmitComplexExprIntoAddr(ArgExprs[i], DestMem, false);
708       Args.push_back(DestMem);
709     } else {
710       llvm::Value *DestMem = CreateTempAlloca(ConvertType(ArgTy));
711       EmitAggExpr(ArgExprs[i], DestMem, false);
712       Args.push_back(DestMem);
713     }
714   }
715 
716   llvm::CallInst *CI = Builder.CreateCall(Callee,&Args[0],&Args[0]+Args.size());
717   if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee))
718     CI->setCallingConv(F->getCallingConv());
719   if (CI->getType() != llvm::Type::VoidTy)
720     CI->setName("call");
721   else if (ResultType->isAnyComplexType())
722     return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
723   else if (hasAggregateLLVMType(ResultType))
724     // Struct return.
725     return RValue::getAggregate(Args[0]);
726   else {
727     // void return.
728     assert(ResultType->isVoidType() && "Should only have a void expr here");
729     CI = 0;
730   }
731 
732   return RValue::get(CI);
733 }
734