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