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