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 "CGCall.h"
17 #include "CGObjCRuntime.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "llvm/Target/TargetData.h"
21 using namespace clang;
22 using namespace CodeGen;
23 
24 //===--------------------------------------------------------------------===//
25 //                        Miscellaneous Helper Methods
26 //===--------------------------------------------------------------------===//
27 
28 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
29 /// block.
30 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
31                                                     const char *Name) {
32   if (!Builder.isNamePreserving())
33     Name = "";
34   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
35 }
36 
37 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38 /// expression and compare the result against zero, returning an Int1Ty value.
39 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
40   QualType BoolTy = getContext().BoolTy;
41   if (!E->getType()->isAnyComplexType())
42     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
43 
44   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
45 }
46 
47 /// EmitAnyExpr - Emit code to compute the specified expression which can have
48 /// any type.  The result is returned as an RValue struct.  If this is an
49 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where the
50 /// result should be returned.
51 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
52                                     bool IsAggLocVolatile, bool IgnoreResult,
53                                     bool IsInitializer) {
54   if (!hasAggregateLLVMType(E->getType()))
55     return RValue::get(EmitScalarExpr(E, IgnoreResult));
56   else if (E->getType()->isAnyComplexType())
57     return RValue::getComplex(EmitComplexExpr(E, false, false,
58                                               IgnoreResult, IgnoreResult));
59 
60   EmitAggExpr(E, AggLoc, IsAggLocVolatile, IgnoreResult, IsInitializer);
61   return RValue::getAggregate(AggLoc, IsAggLocVolatile);
62 }
63 
64 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
65 /// always be accessible even if no aggregate location is provided.
66 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E,
67                                           bool IsAggLocVolatile,
68                                           bool IsInitializer) {
69   llvm::Value *AggLoc = 0;
70 
71   if (hasAggregateLLVMType(E->getType()) &&
72       !E->getType()->isAnyComplexType())
73     AggLoc = CreateTempAlloca(ConvertType(E->getType()), "agg.tmp");
74   return EmitAnyExpr(E, AggLoc, IsAggLocVolatile, /*IgnoreResult=*/false,
75                      IsInitializer);
76 }
77 
78 RValue CodeGenFunction::EmitReferenceBindingToExpr(const Expr* E,
79                                                    QualType DestType,
80                                                    bool IsInitializer) {
81   RValue Val;
82   if (E->isLvalue(getContext()) == Expr::LV_Valid) {
83     // Emit the expr as an lvalue.
84     LValue LV = EmitLValue(E);
85     if (LV.isSimple())
86       return RValue::get(LV.getAddress());
87     Val = EmitLoadOfLValue(LV, E->getType());
88   } else {
89     // FIXME: Initializers don't work with casts yet. For example
90     // const A& a = B();
91     // if B inherits from A.
92     Val = EmitAnyExprToTemp(E, /*IsAggLocVolatile=*/false,
93                             IsInitializer);
94 
95     if (IsInitializer) {
96       // We might have to destroy the temporary variable.
97       if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
98         if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
99           if (!ClassDecl->hasTrivialDestructor()) {
100             const CXXDestructorDecl *Dtor =
101               ClassDecl->getDestructor(getContext());
102 
103             CleanupScope scope(*this);
104             EmitCXXDestructorCall(Dtor, Dtor_Complete, Val.getAggregateAddr());
105           }
106         }
107       }
108     }
109   }
110 
111   if (Val.isAggregate()) {
112     Val = RValue::get(Val.getAggregateAddr());
113   } else {
114     // Create a temporary variable that we can bind the reference to.
115     llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()),
116                                          "reftmp");
117     if (Val.isScalar())
118       EmitStoreOfScalar(Val.getScalarVal(), Temp, false, E->getType());
119     else
120       StoreComplexToAddr(Val.getComplexVal(), Temp, false);
121     Val = RValue::get(Temp);
122   }
123 
124   return Val;
125 }
126 
127 
128 /// getAccessedFieldNo - Given an encoded value and a result number, return the
129 /// input field number being accessed.
130 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
131                                              const llvm::Constant *Elts) {
132   if (isa<llvm::ConstantAggregateZero>(Elts))
133     return 0;
134 
135   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
136 }
137 
138 
139 //===----------------------------------------------------------------------===//
140 //                         LValue Expression Emission
141 //===----------------------------------------------------------------------===//
142 
143 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
144   if (Ty->isVoidType()) {
145     return RValue::get(0);
146   } else if (const ComplexType *CTy = Ty->getAsComplexType()) {
147     const llvm::Type *EltTy = ConvertType(CTy->getElementType());
148     llvm::Value *U = llvm::UndefValue::get(EltTy);
149     return RValue::getComplex(std::make_pair(U, U));
150   } else if (hasAggregateLLVMType(Ty)) {
151     const llvm::Type *LTy = llvm::PointerType::getUnqual(ConvertType(Ty));
152     return RValue::getAggregate(llvm::UndefValue::get(LTy));
153   } else {
154     return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
155   }
156 }
157 
158 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
159                                               const char *Name) {
160   ErrorUnsupported(E, Name);
161   return GetUndefRValue(E->getType());
162 }
163 
164 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
165                                               const char *Name) {
166   ErrorUnsupported(E, Name);
167   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
168   return LValue::MakeAddr(llvm::UndefValue::get(Ty),
169                           E->getType().getCVRQualifiers(),
170                           getContext().getObjCGCAttrKind(E->getType()),
171                           E->getType().getAddressSpace());
172 }
173 
174 /// EmitLValue - Emit code to compute a designator that specifies the location
175 /// of the expression.
176 ///
177 /// This can return one of two things: a simple address or a bitfield reference.
178 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
179 /// an LLVM pointer type.
180 ///
181 /// If this returns a bitfield reference, nothing about the pointee type of the
182 /// LLVM value is known: For example, it may not be a pointer to an integer.
183 ///
184 /// If this returns a normal address, and if the lvalue's C type is fixed size,
185 /// this method guarantees that the returned pointer type will point to an LLVM
186 /// type of the same size of the lvalue's type.  If the lvalue has a variable
187 /// length type, this is not possible.
188 ///
189 LValue CodeGenFunction::EmitLValue(const Expr *E) {
190   switch (E->getStmtClass()) {
191   default: return EmitUnsupportedLValue(E, "l-value expression");
192 
193   case Expr::BinaryOperatorClass:
194     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
195   case Expr::CallExprClass:
196   case Expr::CXXMemberCallExprClass:
197   case Expr::CXXOperatorCallExprClass:
198     return EmitCallExprLValue(cast<CallExpr>(E));
199   case Expr::VAArgExprClass:
200     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
201   case Expr::DeclRefExprClass:
202   case Expr::QualifiedDeclRefExprClass:
203     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
204   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
205   case Expr::PredefinedExprClass:
206     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
207   case Expr::StringLiteralClass:
208     return EmitStringLiteralLValue(cast<StringLiteral>(E));
209   case Expr::ObjCEncodeExprClass:
210     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
211 
212   case Expr::BlockDeclRefExprClass:
213     return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
214 
215   case Expr::CXXConditionDeclExprClass:
216     return EmitCXXConditionDeclLValue(cast<CXXConditionDeclExpr>(E));
217   case Expr::CXXTemporaryObjectExprClass:
218   case Expr::CXXConstructExprClass:
219     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
220   case Expr::CXXBindTemporaryExprClass:
221     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
222   case Expr::CXXExprWithTemporariesClass:
223     return EmitCXXExprWithTemporariesLValue(cast<CXXExprWithTemporaries>(E));
224 
225   case Expr::ObjCMessageExprClass:
226     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
227   case Expr::ObjCIvarRefExprClass:
228     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
229   case Expr::ObjCPropertyRefExprClass:
230     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
231   case Expr::ObjCImplicitSetterGetterRefExprClass:
232     return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E));
233   case Expr::ObjCSuperExprClass:
234     return EmitObjCSuperExprLValue(cast<ObjCSuperExpr>(E));
235 
236   case Expr::StmtExprClass:
237     return EmitStmtExprLValue(cast<StmtExpr>(E));
238   case Expr::UnaryOperatorClass:
239     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
240   case Expr::ArraySubscriptExprClass:
241     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
242   case Expr::ExtVectorElementExprClass:
243     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
244   case Expr::MemberExprClass:
245     return EmitMemberExpr(cast<MemberExpr>(E));
246   case Expr::CompoundLiteralExprClass:
247     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
248   case Expr::ConditionalOperatorClass:
249     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
250   case Expr::ChooseExprClass:
251     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
252   case Expr::ImplicitCastExprClass:
253   case Expr::CStyleCastExprClass:
254   case Expr::CXXFunctionalCastExprClass:
255   case Expr::CXXStaticCastExprClass:
256   case Expr::CXXDynamicCastExprClass:
257   case Expr::CXXReinterpretCastExprClass:
258   case Expr::CXXConstCastExprClass:
259     return EmitCastLValue(cast<CastExpr>(E));
260   }
261 }
262 
263 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
264                                                QualType Ty) {
265   llvm::Value *V = Builder.CreateLoad(Addr, Volatile, "tmp");
266 
267   // Bool can have different representation in memory than in registers.
268   if (Ty->isBooleanType())
269     if (V->getType() != llvm::Type::getInt1Ty(VMContext))
270       V = Builder.CreateTrunc(V, llvm::Type::getInt1Ty(VMContext), "tobool");
271 
272   return V;
273 }
274 
275 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
276                                         bool Volatile, QualType Ty) {
277 
278   if (Ty->isBooleanType()) {
279     // Bool can have different representation in memory than in registers.
280     const llvm::Type *SrcTy = Value->getType();
281     const llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
282     if (DstPtr->getElementType() != SrcTy) {
283       const llvm::Type *MemTy =
284         llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
285       Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
286     }
287   }
288   Builder.CreateStore(Value, Addr, Volatile);
289 }
290 
291 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
292 /// method emits the address of the lvalue, then loads the result as an rvalue,
293 /// returning the rvalue.
294 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
295   if (LV.isObjCWeak()) {
296     // load of a __weak object.
297     llvm::Value *AddrWeakObj = LV.getAddress();
298     llvm::Value *read_weak = CGM.getObjCRuntime().EmitObjCWeakRead(*this,
299                                                                    AddrWeakObj);
300     return RValue::get(read_weak);
301   }
302 
303   if (LV.isSimple()) {
304     llvm::Value *Ptr = LV.getAddress();
305     const llvm::Type *EltTy =
306       cast<llvm::PointerType>(Ptr->getType())->getElementType();
307 
308     // Simple scalar l-value.
309     if (EltTy->isSingleValueType())
310       return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
311                                           ExprType));
312 
313     assert(ExprType->isFunctionType() && "Unknown scalar value");
314     return RValue::get(Ptr);
315   }
316 
317   if (LV.isVectorElt()) {
318     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
319                                           LV.isVolatileQualified(), "tmp");
320     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
321                                                     "vecext"));
322   }
323 
324   // If this is a reference to a subset of the elements of a vector, either
325   // shuffle the input or extract/insert them as appropriate.
326   if (LV.isExtVectorElt())
327     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
328 
329   if (LV.isBitfield())
330     return EmitLoadOfBitfieldLValue(LV, ExprType);
331 
332   if (LV.isPropertyRef())
333     return EmitLoadOfPropertyRefLValue(LV, ExprType);
334 
335   assert(LV.isKVCRef() && "Unknown LValue type!");
336   return EmitLoadOfKVCRefLValue(LV, ExprType);
337 }
338 
339 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
340                                                  QualType ExprType) {
341   unsigned StartBit = LV.getBitfieldStartBit();
342   unsigned BitfieldSize = LV.getBitfieldSize();
343   llvm::Value *Ptr = LV.getBitfieldAddr();
344 
345   const llvm::Type *EltTy =
346     cast<llvm::PointerType>(Ptr->getType())->getElementType();
347   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
348 
349   // In some cases the bitfield may straddle two memory locations.  Currently we
350   // load the entire bitfield, then do the magic to sign-extend it if
351   // necessary. This results in somewhat more code than necessary for the common
352   // case (one load), since two shifts accomplish both the masking and sign
353   // extension.
354   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
355   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp");
356 
357   // Shift to proper location.
358   if (StartBit)
359     Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit),
360                              "bf.lo");
361 
362   // Mask off unused bits.
363   llvm::Constant *LowMask = llvm::ConstantInt::get(VMContext,
364                                 llvm::APInt::getLowBitsSet(EltTySize, LowBits));
365   Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared");
366 
367   // Fetch the high bits if necessary.
368   if (LowBits < BitfieldSize) {
369     unsigned HighBits = BitfieldSize - LowBits;
370     llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get(
371                             llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi");
372     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
373                                               LV.isVolatileQualified(),
374                                               "tmp");
375 
376     // Mask off unused bits.
377     llvm::Constant *HighMask = llvm::ConstantInt::get(VMContext,
378                                llvm::APInt::getLowBitsSet(EltTySize, HighBits));
379     HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared");
380 
381     // Shift to proper location and or in to bitfield value.
382     HighVal = Builder.CreateShl(HighVal,
383                                 llvm::ConstantInt::get(EltTy, LowBits));
384     Val = Builder.CreateOr(Val, HighVal, "bf.val");
385   }
386 
387   // Sign extend if necessary.
388   if (LV.isBitfieldSigned()) {
389     llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy,
390                                                     EltTySize - BitfieldSize);
391     Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits),
392                              ExtraBits, "bf.val.sext");
393   }
394 
395   // The bitfield type and the normal type differ when the storage sizes differ
396   // (currently just _Bool).
397   Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp");
398 
399   return RValue::get(Val);
400 }
401 
402 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
403                                                     QualType ExprType) {
404   return EmitObjCPropertyGet(LV.getPropertyRefExpr());
405 }
406 
407 RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV,
408                                                QualType ExprType) {
409   return EmitObjCPropertyGet(LV.getKVCRefExpr());
410 }
411 
412 // If this is a reference to a subset of the elements of a vector, create an
413 // appropriate shufflevector.
414 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
415                                                          QualType ExprType) {
416   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
417                                         LV.isVolatileQualified(), "tmp");
418 
419   const llvm::Constant *Elts = LV.getExtVectorElts();
420 
421   // If the result of the expression is a non-vector type, we must be extracting
422   // a single element.  Just codegen as an extractelement.
423   const VectorType *ExprVT = ExprType->getAsVectorType();
424   if (!ExprVT) {
425     unsigned InIdx = getAccessedFieldNo(0, Elts);
426     llvm::Value *Elt = llvm::ConstantInt::get(
427                                       llvm::Type::getInt32Ty(VMContext), InIdx);
428     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
429   }
430 
431   // Always use shuffle vector to try to retain the original program structure
432   unsigned NumResultElts = ExprVT->getNumElements();
433 
434   llvm::SmallVector<llvm::Constant*, 4> Mask;
435   for (unsigned i = 0; i != NumResultElts; ++i) {
436     unsigned InIdx = getAccessedFieldNo(i, Elts);
437     Mask.push_back(llvm::ConstantInt::get(
438                                      llvm::Type::getInt32Ty(VMContext), InIdx));
439   }
440 
441   llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
442   Vec = Builder.CreateShuffleVector(Vec,
443                                     llvm::UndefValue::get(Vec->getType()),
444                                     MaskV, "tmp");
445   return RValue::get(Vec);
446 }
447 
448 
449 
450 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
451 /// lvalue, where both are guaranteed to the have the same type, and that type
452 /// is 'Ty'.
453 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
454                                              QualType Ty) {
455   if (!Dst.isSimple()) {
456     if (Dst.isVectorElt()) {
457       // Read/modify/write the vector, inserting the new element.
458       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
459                                             Dst.isVolatileQualified(), "tmp");
460       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
461                                         Dst.getVectorIdx(), "vecins");
462       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
463       return;
464     }
465 
466     // If this is an update of extended vector elements, insert them as
467     // appropriate.
468     if (Dst.isExtVectorElt())
469       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
470 
471     if (Dst.isBitfield())
472       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
473 
474     if (Dst.isPropertyRef())
475       return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
476 
477     if (Dst.isKVCRef())
478       return EmitStoreThroughKVCRefLValue(Src, Dst, Ty);
479 
480     assert(0 && "Unknown LValue type");
481   }
482 
483   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
484     // load of a __weak object.
485     llvm::Value *LvalueDst = Dst.getAddress();
486     llvm::Value *src = Src.getScalarVal();
487      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
488     return;
489   }
490 
491   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
492     // load of a __strong object.
493     llvm::Value *LvalueDst = Dst.getAddress();
494     llvm::Value *src = Src.getScalarVal();
495     if (Dst.isObjCIvar())
496       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, LvalueDst);
497     else if (Dst.isGlobalObjCRef())
498       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst);
499     else
500       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
501     return;
502   }
503 
504   assert(Src.isScalar() && "Can't emit an agg store with this method");
505   EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
506                     Dst.isVolatileQualified(), Ty);
507 }
508 
509 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
510                                                      QualType Ty,
511                                                      llvm::Value **Result) {
512   unsigned StartBit = Dst.getBitfieldStartBit();
513   unsigned BitfieldSize = Dst.getBitfieldSize();
514   llvm::Value *Ptr = Dst.getBitfieldAddr();
515 
516   const llvm::Type *EltTy =
517     cast<llvm::PointerType>(Ptr->getType())->getElementType();
518   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
519 
520   // Get the new value, cast to the appropriate type and masked to exactly the
521   // size of the bit-field.
522   llvm::Value *SrcVal = Src.getScalarVal();
523   llvm::Value *NewVal = Builder.CreateIntCast(SrcVal, EltTy, false, "tmp");
524   llvm::Constant *Mask = llvm::ConstantInt::get(VMContext,
525                            llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize));
526   NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value");
527 
528   // Return the new value of the bit-field, if requested.
529   if (Result) {
530     // Cast back to the proper type for result.
531     const llvm::Type *SrcTy = SrcVal->getType();
532     llvm::Value *SrcTrunc = Builder.CreateIntCast(NewVal, SrcTy, false,
533                                                   "bf.reload.val");
534 
535     // Sign extend if necessary.
536     if (Dst.isBitfieldSigned()) {
537       unsigned SrcTySize = CGM.getTargetData().getTypeSizeInBits(SrcTy);
538       llvm::Value *ExtraBits = llvm::ConstantInt::get(SrcTy,
539                                                       SrcTySize - BitfieldSize);
540       SrcTrunc = Builder.CreateAShr(Builder.CreateShl(SrcTrunc, ExtraBits),
541                                     ExtraBits, "bf.reload.sext");
542     }
543 
544     *Result = SrcTrunc;
545   }
546 
547   // In some cases the bitfield may straddle two memory locations.  Emit the low
548   // part first and check to see if the high needs to be done.
549   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
550   llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
551                                            "bf.prev.low");
552 
553   // Compute the mask for zero-ing the low part of this bitfield.
554   llvm::Constant *InvMask =
555     llvm::ConstantInt::get(VMContext,
556              ~llvm::APInt::getBitsSet(EltTySize, StartBit, StartBit + LowBits));
557 
558   // Compute the new low part as
559   //   LowVal = (LowVal & InvMask) | (NewVal << StartBit),
560   // with the shift of NewVal implicitly stripping the high bits.
561   llvm::Value *NewLowVal =
562     Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit),
563                       "bf.value.lo");
564   LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared");
565   LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo");
566 
567   // Write back.
568   Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified());
569 
570   // If the low part doesn't cover the bitfield emit a high part.
571   if (LowBits < BitfieldSize) {
572     unsigned HighBits = BitfieldSize - LowBits;
573     llvm::Value *HighPtr =  Builder.CreateGEP(Ptr, llvm::ConstantInt::get(
574                             llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi");
575     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
576                                               Dst.isVolatileQualified(),
577                                               "bf.prev.hi");
578 
579     // Compute the mask for zero-ing the high part of this bitfield.
580     llvm::Constant *InvMask =
581       llvm::ConstantInt::get(VMContext, ~llvm::APInt::getLowBitsSet(EltTySize,
582                                HighBits));
583 
584     // Compute the new high part as
585     //   HighVal = (HighVal & InvMask) | (NewVal lshr LowBits),
586     // where the high bits of NewVal have already been cleared and the
587     // shift stripping the low bits.
588     llvm::Value *NewHighVal =
589       Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits),
590                         "bf.value.high");
591     HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared");
592     HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi");
593 
594     // Write back.
595     Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified());
596   }
597 }
598 
599 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
600                                                         LValue Dst,
601                                                         QualType Ty) {
602   EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
603 }
604 
605 void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src,
606                                                    LValue Dst,
607                                                    QualType Ty) {
608   EmitObjCPropertySet(Dst.getKVCRefExpr(), Src);
609 }
610 
611 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
612                                                                LValue Dst,
613                                                                QualType Ty) {
614   // This access turns into a read/modify/write of the vector.  Load the input
615   // value now.
616   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
617                                         Dst.isVolatileQualified(), "tmp");
618   const llvm::Constant *Elts = Dst.getExtVectorElts();
619 
620   llvm::Value *SrcVal = Src.getScalarVal();
621 
622   if (const VectorType *VTy = Ty->getAsVectorType()) {
623     unsigned NumSrcElts = VTy->getNumElements();
624     unsigned NumDstElts =
625        cast<llvm::VectorType>(Vec->getType())->getNumElements();
626     if (NumDstElts == NumSrcElts) {
627       // Use shuffle vector is the src and destination are the same number of
628       // elements and restore the vector mask since it is on the side it will be
629       // stored.
630       llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
631       for (unsigned i = 0; i != NumSrcElts; ++i) {
632         unsigned InIdx = getAccessedFieldNo(i, Elts);
633         Mask[InIdx] = llvm::ConstantInt::get(
634                                           llvm::Type::getInt32Ty(VMContext), i);
635       }
636 
637       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
638       Vec = Builder.CreateShuffleVector(SrcVal,
639                                         llvm::UndefValue::get(Vec->getType()),
640                                         MaskV, "tmp");
641     } else if (NumDstElts > NumSrcElts) {
642       // Extended the source vector to the same length and then shuffle it
643       // into the destination.
644       // FIXME: since we're shuffling with undef, can we just use the indices
645       //        into that?  This could be simpler.
646       llvm::SmallVector<llvm::Constant*, 4> ExtMask;
647       unsigned i;
648       for (i = 0; i != NumSrcElts; ++i)
649         ExtMask.push_back(llvm::ConstantInt::get(
650                                          llvm::Type::getInt32Ty(VMContext), i));
651       for (; i != NumDstElts; ++i)
652         ExtMask.push_back(llvm::UndefValue::get(
653                                             llvm::Type::getInt32Ty(VMContext)));
654       llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0],
655                                                         ExtMask.size());
656       llvm::Value *ExtSrcVal =
657         Builder.CreateShuffleVector(SrcVal,
658                                     llvm::UndefValue::get(SrcVal->getType()),
659                                     ExtMaskV, "tmp");
660       // build identity
661       llvm::SmallVector<llvm::Constant*, 4> Mask;
662       for (unsigned i = 0; i != NumDstElts; ++i) {
663         Mask.push_back(llvm::ConstantInt::get(
664                                         llvm::Type::getInt32Ty(VMContext), i));
665       }
666       // modify when what gets shuffled in
667       for (unsigned i = 0; i != NumSrcElts; ++i) {
668         unsigned Idx = getAccessedFieldNo(i, Elts);
669         Mask[Idx] = llvm::ConstantInt::get(
670                                llvm::Type::getInt32Ty(VMContext), i+NumDstElts);
671       }
672       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
673       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
674     } else {
675       // We should never shorten the vector
676       assert(0 && "unexpected shorten vector length");
677     }
678   } else {
679     // If the Src is a scalar (not a vector) it must be updating one element.
680     unsigned InIdx = getAccessedFieldNo(0, Elts);
681     llvm::Value *Elt = llvm::ConstantInt::get(
682                                       llvm::Type::getInt32Ty(VMContext), InIdx);
683     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
684   }
685 
686   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
687 }
688 
689 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
690 // generating write-barries API. It is currently a global, ivar,
691 // or neither.
692 static
693 void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, LValue &LV) {
694   if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC ||
695       !Ctx.getLangOptions().ObjCNewGCAPI)
696     return;
697 
698   if (isa<ObjCIvarRefExpr>(E)) {
699     LV.SetObjCIvar(LV, true);
700     LV.SetObjCIvarArray(LV, E->getType()->isArrayType());
701     return;
702   }
703   if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
704     if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
705       if ((VD->isBlockVarDecl() && !VD->hasLocalStorage()) ||
706           VD->isFileVarDecl())
707         LV.SetGlobalObjCRef(LV, true);
708     }
709   }
710   else if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E))
711     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
712   else if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E))
713     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
714   else if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E))
715     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
716   else if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E))
717     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
718   else if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
719     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
720     if (LV.isObjCIvar() && !LV.isObjCIvarArray()) {
721       // Using array syntax to assigning to what an ivar points to is not
722       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
723       LV.SetObjCIvar(LV, false);
724     }
725   }
726   else if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
727     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
728     // We don't know if member is an 'ivar', but this flag is looked at
729     // only in the context of LV.isObjCIvar().
730     LV.SetObjCIvarArray(LV, E->getType()->isArrayType());
731   }
732 }
733 
734 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
735   const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
736 
737   if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD) ||
738         isa<ImplicitParamDecl>(VD))) {
739     LValue LV;
740     bool NonGCable = VD->hasLocalStorage() &&
741       !VD->hasAttr<BlocksAttr>();
742     if (VD->hasExternalStorage()) {
743       llvm::Value *V = CGM.GetAddrOfGlobalVar(VD);
744       if (VD->getType()->isReferenceType())
745         V = Builder.CreateLoad(V, "tmp");
746       LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
747                             getContext().getObjCGCAttrKind(E->getType()),
748                             E->getType().getAddressSpace());
749     } else {
750       llvm::Value *V = LocalDeclMap[VD];
751       assert(V && "DeclRefExpr not entered in LocalDeclMap?");
752       // local variables do not get their gc attribute set.
753       QualType::GCAttrTypes attr = QualType::GCNone;
754       // local static?
755       if (!NonGCable)
756         attr = getContext().getObjCGCAttrKind(E->getType());
757       if (VD->hasAttr<BlocksAttr>()) {
758         V = Builder.CreateStructGEP(V, 1, "forwarding");
759         V = Builder.CreateLoad(V, false);
760         V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
761                                     VD->getNameAsString());
762       }
763       if (VD->getType()->isReferenceType())
764         V = Builder.CreateLoad(V, "tmp");
765       LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), attr,
766                             E->getType().getAddressSpace());
767     }
768     LValue::SetObjCNonGC(LV, NonGCable);
769     setObjCGCLValueClass(getContext(), E, LV);
770     return LV;
771   } else if (VD && VD->isFileVarDecl()) {
772     llvm::Value *V = CGM.GetAddrOfGlobalVar(VD);
773     if (VD->getType()->isReferenceType())
774       V = Builder.CreateLoad(V, "tmp");
775     LValue LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
776                                  getContext().getObjCGCAttrKind(E->getType()),
777                                  E->getType().getAddressSpace());
778     setObjCGCLValueClass(getContext(), E, LV);
779     return LV;
780   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
781     llvm::Value* V = CGM.GetAddrOfFunction(FD);
782     if (!FD->hasPrototype()) {
783       if (const FunctionProtoType *Proto =
784               FD->getType()->getAsFunctionProtoType()) {
785         // Ugly case: for a K&R-style definition, the type of the definition
786         // isn't the same as the type of a use.  Correct for this with a
787         // bitcast.
788         QualType NoProtoType =
789             getContext().getFunctionNoProtoType(Proto->getResultType());
790         NoProtoType = getContext().getPointerType(NoProtoType);
791         V = Builder.CreateBitCast(V, ConvertType(NoProtoType), "tmp");
792       }
793     }
794     return LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
795                             getContext().getObjCGCAttrKind(E->getType()),
796                             E->getType().getAddressSpace());
797   } else if (const ImplicitParamDecl *IPD =
798       dyn_cast<ImplicitParamDecl>(E->getDecl())) {
799     llvm::Value *V = LocalDeclMap[IPD];
800     assert(V && "BlockVarDecl not entered in LocalDeclMap?");
801     return LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
802                             getContext().getObjCGCAttrKind(E->getType()),
803                             E->getType().getAddressSpace());
804   }
805   assert(0 && "Unimp declref");
806   //an invalid LValue, but the assert will
807   //ensure that this point is never reached.
808   return LValue();
809 }
810 
811 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
812   return LValue::MakeAddr(GetAddrOfBlockDecl(E),
813                           E->getType().getCVRQualifiers(),
814                           getContext().getObjCGCAttrKind(E->getType()),
815                           E->getType().getAddressSpace());
816 }
817 
818 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
819   // __extension__ doesn't affect lvalue-ness.
820   if (E->getOpcode() == UnaryOperator::Extension)
821     return EmitLValue(E->getSubExpr());
822 
823   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
824   switch (E->getOpcode()) {
825   default: assert(0 && "Unknown unary operator lvalue!");
826   case UnaryOperator::Deref:
827     {
828       QualType T = E->getSubExpr()->getType()->getPointeeType();
829       assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
830 
831       LValue LV = LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()),
832                                    T.getCVRQualifiers(),
833                                    getContext().getObjCGCAttrKind(T),
834                                    ExprTy.getAddressSpace());
835      // We should not generate __weak write barrier on indirect reference
836      // of a pointer to object; as in void foo (__weak id *param); *param = 0;
837      // But, we continue to generate __strong write barrier on indirect write
838      // into a pointer to object.
839      if (getContext().getLangOptions().ObjC1 &&
840          getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
841          LV.isObjCWeak())
842        LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
843      return LV;
844     }
845   case UnaryOperator::Real:
846   case UnaryOperator::Imag:
847     LValue LV = EmitLValue(E->getSubExpr());
848     unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
849     return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
850                                                     Idx, "idx"),
851                             ExprTy.getCVRQualifiers(),
852                             QualType::GCNone,
853                             ExprTy.getAddressSpace());
854   }
855 }
856 
857 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
858   return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0);
859 }
860 
861 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
862   return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromObjCEncode(E), 0);
863 }
864 
865 
866 LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) {
867   std::string GlobalVarName;
868 
869   switch (Type) {
870   default:
871     assert(0 && "Invalid type");
872   case PredefinedExpr::Func:
873     GlobalVarName = "__func__.";
874     break;
875   case PredefinedExpr::Function:
876     GlobalVarName = "__FUNCTION__.";
877     break;
878   case PredefinedExpr::PrettyFunction:
879     GlobalVarName = "__PRETTY_FUNCTION__.";
880     break;
881   }
882 
883   llvm::StringRef FnName = CurFn->getName();
884   if (FnName.startswith("\01"))
885     FnName = FnName.substr(1);
886   GlobalVarName += FnName;
887 
888   std::string FunctionName =
889     PredefinedExpr::ComputeName(getContext(), (PredefinedExpr::IdentType)Type,
890                                 CurCodeDecl);
891 
892   llvm::Constant *C =
893     CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
894   return LValue::MakeAddr(C, 0);
895 }
896 
897 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
898   switch (E->getIdentType()) {
899   default:
900     return EmitUnsupportedLValue(E, "predefined expression");
901   case PredefinedExpr::Func:
902   case PredefinedExpr::Function:
903   case PredefinedExpr::PrettyFunction:
904     return EmitPredefinedFunctionName(E->getIdentType());
905   }
906 }
907 
908 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
909   // The index must always be an integer, which is not an aggregate.  Emit it.
910   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
911   QualType IdxTy  = E->getIdx()->getType();
912   bool IdxSigned = IdxTy->isSignedIntegerType();
913 
914   // If the base is a vector type, then we are forming a vector element lvalue
915   // with this subscript.
916   if (E->getBase()->getType()->isVectorType()) {
917     // Emit the vector as an lvalue to get its address.
918     LValue LHS = EmitLValue(E->getBase());
919     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
920     Idx = Builder.CreateIntCast(Idx,
921                           llvm::Type::getInt32Ty(VMContext), IdxSigned, "vidx");
922     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
923       E->getBase()->getType().getCVRQualifiers());
924   }
925 
926   // The base must be a pointer, which is not an aggregate.  Emit it.
927   llvm::Value *Base = EmitScalarExpr(E->getBase());
928 
929   // Extend or truncate the index type to 32 or 64-bits.
930   unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
931   if (IdxBitwidth != LLVMPointerWidth)
932     Idx = Builder.CreateIntCast(Idx,
933                             llvm::IntegerType::get(VMContext, LLVMPointerWidth),
934                                 IdxSigned, "idxprom");
935 
936   // We know that the pointer points to a type of the correct size, unless the
937   // size is a VLA or Objective-C interface.
938   llvm::Value *Address = 0;
939   if (const VariableArrayType *VAT =
940         getContext().getAsVariableArrayType(E->getType())) {
941     llvm::Value *VLASize = GetVLASize(VAT);
942 
943     Idx = Builder.CreateMul(Idx, VLASize);
944 
945     QualType BaseType = getContext().getBaseElementType(VAT);
946 
947     uint64_t BaseTypeSize = getContext().getTypeSize(BaseType) / 8;
948     Idx = Builder.CreateUDiv(Idx,
949                              llvm::ConstantInt::get(Idx->getType(),
950                                                     BaseTypeSize));
951     Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
952   } else if (const ObjCInterfaceType *OIT =
953              dyn_cast<ObjCInterfaceType>(E->getType())) {
954     llvm::Value *InterfaceSize =
955       llvm::ConstantInt::get(Idx->getType(),
956                              getContext().getTypeSize(OIT) / 8);
957 
958     Idx = Builder.CreateMul(Idx, InterfaceSize);
959 
960     llvm::Type *i8PTy =
961             llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
962     Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy),
963                                 Idx, "arrayidx");
964     Address = Builder.CreateBitCast(Address, Base->getType());
965   } else {
966     Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
967   }
968 
969   QualType T = E->getBase()->getType()->getPointeeType();
970   assert(!T.isNull() &&
971          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
972 
973   LValue LV = LValue::MakeAddr(Address,
974                                T.getCVRQualifiers(),
975                                getContext().getObjCGCAttrKind(T),
976                                E->getBase()->getType().getAddressSpace());
977   if (getContext().getLangOptions().ObjC1 &&
978       getContext().getLangOptions().getGCMode() != LangOptions::NonGC) {
979     LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
980     setObjCGCLValueClass(getContext(), E, LV);
981   }
982   return LV;
983 }
984 
985 static
986 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
987                                        llvm::SmallVector<unsigned, 4> &Elts) {
988   llvm::SmallVector<llvm::Constant *, 4> CElts;
989 
990   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
991     CElts.push_back(llvm::ConstantInt::get(
992                                    llvm::Type::getInt32Ty(VMContext), Elts[i]));
993 
994   return llvm::ConstantVector::get(&CElts[0], CElts.size());
995 }
996 
997 LValue CodeGenFunction::
998 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
999   // Emit the base vector as an l-value.
1000   LValue Base;
1001 
1002   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1003   if (!E->isArrow()) {
1004     assert(E->getBase()->getType()->isVectorType());
1005     Base = EmitLValue(E->getBase());
1006   } else {
1007     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1008     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1009     Base = LValue::MakeAddr(Ptr, PT->getPointeeType().getCVRQualifiers(),
1010                             QualType::GCNone,
1011                             PT->getPointeeType().getAddressSpace());
1012   }
1013 
1014   // Encode the element access list into a vector of unsigned indices.
1015   llvm::SmallVector<unsigned, 4> Indices;
1016   E->getEncodedElementAccess(Indices);
1017 
1018   if (Base.isSimple()) {
1019     llvm::Constant *CV = GenerateConstantVector(VMContext, Indices);
1020     return LValue::MakeExtVectorElt(Base.getAddress(), CV,
1021                                     Base.getQualifiers());
1022   }
1023   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1024 
1025   llvm::Constant *BaseElts = Base.getExtVectorElts();
1026   llvm::SmallVector<llvm::Constant *, 4> CElts;
1027 
1028   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1029     if (isa<llvm::ConstantAggregateZero>(BaseElts))
1030       CElts.push_back(llvm::ConstantInt::get(
1031                                          llvm::Type::getInt32Ty(VMContext), 0));
1032     else
1033       CElts.push_back(BaseElts->getOperand(Indices[i]));
1034   }
1035   llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
1036   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
1037                                   Base.getQualifiers());
1038 }
1039 
1040 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1041   bool isUnion = false;
1042   bool isNonGC = false;
1043   Expr *BaseExpr = E->getBase();
1044   llvm::Value *BaseValue = NULL;
1045   unsigned CVRQualifiers=0;
1046 
1047   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1048   if (E->isArrow()) {
1049     BaseValue = EmitScalarExpr(BaseExpr);
1050     const PointerType *PTy =
1051       BaseExpr->getType()->getAs<PointerType>();
1052     if (PTy->getPointeeType()->isUnionType())
1053       isUnion = true;
1054     CVRQualifiers = PTy->getPointeeType().getCVRQualifiers();
1055   } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) ||
1056              isa<ObjCImplicitSetterGetterRefExpr>(
1057                BaseExpr->IgnoreParens())) {
1058     RValue RV = EmitObjCPropertyGet(BaseExpr);
1059     BaseValue = RV.getAggregateAddr();
1060     if (BaseExpr->getType()->isUnionType())
1061       isUnion = true;
1062     CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
1063   } else {
1064     LValue BaseLV = EmitLValue(BaseExpr);
1065     if (BaseLV.isNonGC())
1066       isNonGC = true;
1067     // FIXME: this isn't right for bitfields.
1068     BaseValue = BaseLV.getAddress();
1069     QualType BaseTy = BaseExpr->getType();
1070     if (BaseTy->isUnionType())
1071       isUnion = true;
1072     CVRQualifiers = BaseTy.getCVRQualifiers();
1073   }
1074 
1075   FieldDecl *Field = dyn_cast<FieldDecl>(E->getMemberDecl());
1076   // FIXME: Handle non-field member expressions
1077   assert(Field && "No code generation for non-field member references");
1078   LValue MemExpLV = EmitLValueForField(BaseValue, Field, isUnion,
1079                                        CVRQualifiers);
1080   LValue::SetObjCNonGC(MemExpLV, isNonGC);
1081   setObjCGCLValueClass(getContext(), E, MemExpLV);
1082   return MemExpLV;
1083 }
1084 
1085 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue,
1086                                               FieldDecl* Field,
1087                                               unsigned CVRQualifiers) {
1088   CodeGenTypes::BitFieldInfo Info = CGM.getTypes().getBitFieldInfo(Field);
1089 
1090   // FIXME: CodeGenTypes should expose a method to get the appropriate type for
1091   // FieldTy (the appropriate type is ABI-dependent).
1092   const llvm::Type *FieldTy =
1093     CGM.getTypes().ConvertTypeForMem(Field->getType());
1094   const llvm::PointerType *BaseTy =
1095   cast<llvm::PointerType>(BaseValue->getType());
1096   unsigned AS = BaseTy->getAddressSpace();
1097   BaseValue = Builder.CreateBitCast(BaseValue,
1098                                     llvm::PointerType::get(FieldTy, AS),
1099                                     "tmp");
1100 
1101   llvm::Value *Idx =
1102     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Info.FieldNo);
1103   llvm::Value *V = Builder.CreateGEP(BaseValue, Idx, "tmp");
1104 
1105   return LValue::MakeBitfield(V, Info.Start, Info.Size,
1106                               Field->getType()->isSignedIntegerType(),
1107                             Field->getType().getCVRQualifiers()|CVRQualifiers);
1108 }
1109 
1110 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
1111                                            FieldDecl* Field,
1112                                            bool isUnion,
1113                                            unsigned CVRQualifiers) {
1114   if (Field->isBitField())
1115     return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers);
1116 
1117   unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1118   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1119 
1120   // Match union field type.
1121   if (isUnion) {
1122     const llvm::Type *FieldTy =
1123       CGM.getTypes().ConvertTypeForMem(Field->getType());
1124     const llvm::PointerType * BaseTy =
1125       cast<llvm::PointerType>(BaseValue->getType());
1126     unsigned AS = BaseTy->getAddressSpace();
1127     V = Builder.CreateBitCast(V,
1128                               llvm::PointerType::get(FieldTy, AS),
1129                               "tmp");
1130   }
1131   if (Field->getType()->isReferenceType())
1132     V = Builder.CreateLoad(V, "tmp");
1133 
1134   QualType::GCAttrTypes attr = QualType::GCNone;
1135   if (CGM.getLangOptions().ObjC1 &&
1136       CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1137     QualType Ty = Field->getType();
1138     attr = Ty.getObjCGCAttr();
1139     if (attr != QualType::GCNone) {
1140       // __weak attribute on a field is ignored.
1141       if (attr == QualType::Weak)
1142         attr = QualType::GCNone;
1143     } else if (Ty->isObjCObjectPointerType())
1144       attr = QualType::Strong;
1145   }
1146   LValue LV =
1147     LValue::MakeAddr(V,
1148                      Field->getType().getCVRQualifiers()|CVRQualifiers,
1149                      attr,
1150                      Field->getType().getAddressSpace());
1151   return LV;
1152 }
1153 
1154 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E){
1155   const llvm::Type *LTy = ConvertType(E->getType());
1156   llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
1157 
1158   const Expr* InitExpr = E->getInitializer();
1159   LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers(),
1160                                    QualType::GCNone,
1161                                    E->getType().getAddressSpace());
1162 
1163   if (E->getType()->isComplexType()) {
1164     EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
1165   } else if (hasAggregateLLVMType(E->getType())) {
1166     EmitAnyExpr(InitExpr, DeclPtr, false);
1167   } else {
1168     EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
1169   }
1170 
1171   return Result;
1172 }
1173 
1174 LValue
1175 CodeGenFunction::EmitConditionalOperatorLValue(const ConditionalOperator* E) {
1176   if (E->isLvalue(getContext()) == Expr::LV_Valid) {
1177     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1178     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1179     llvm::BasicBlock *ContBlock = createBasicBlock("cond.end");
1180 
1181     llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1182     Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1183 
1184     EmitBlock(LHSBlock);
1185 
1186     LValue LHS = EmitLValue(E->getLHS());
1187     if (!LHS.isSimple())
1188       return EmitUnsupportedLValue(E, "conditional operator");
1189 
1190     llvm::Value *Temp = CreateTempAlloca(LHS.getAddress()->getType(),
1191                                          "condtmp");
1192 
1193     Builder.CreateStore(LHS.getAddress(), Temp);
1194     EmitBranch(ContBlock);
1195 
1196     EmitBlock(RHSBlock);
1197     LValue RHS = EmitLValue(E->getRHS());
1198     if (!RHS.isSimple())
1199       return EmitUnsupportedLValue(E, "conditional operator");
1200 
1201     Builder.CreateStore(RHS.getAddress(), Temp);
1202     EmitBranch(ContBlock);
1203 
1204     EmitBlock(ContBlock);
1205 
1206     Temp = Builder.CreateLoad(Temp, "lv");
1207     return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1208                             getContext().getObjCGCAttrKind(E->getType()),
1209                             E->getType().getAddressSpace());
1210   }
1211 
1212   // ?: here should be an aggregate.
1213   assert((hasAggregateLLVMType(E->getType()) &&
1214           !E->getType()->isAnyComplexType()) &&
1215          "Unexpected conditional operator!");
1216 
1217   llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1218   EmitAggExpr(E, Temp, false);
1219 
1220   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1221                           getContext().getObjCGCAttrKind(E->getType()),
1222                           E->getType().getAddressSpace());
1223 }
1224 
1225 /// EmitCastLValue - Casts are never lvalues.  If a cast is needed by the code
1226 /// generator in an lvalue context, then it must mean that we need the address
1227 /// of an aggregate in order to access one of its fields.  This can happen for
1228 /// all the reasons that casts are permitted with aggregate result, including
1229 /// noop aggregate casts, and cast from scalar to union.
1230 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1231   switch (E->getCastKind()) {
1232   default:
1233     // If this is an lvalue cast, treat it as a no-op.
1234     // FIXME: We shouldn't need to check for this explicitly!
1235     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
1236       if (ICE->isLvalueCast())
1237         return EmitLValue(E->getSubExpr());
1238 
1239     assert(0 && "Unhandled cast!");
1240 
1241   case CastExpr::CK_NoOp:
1242   case CastExpr::CK_ConstructorConversion:
1243   case CastExpr::CK_UserDefinedConversion:
1244     return EmitLValue(E->getSubExpr());
1245 
1246   case CastExpr::CK_DerivedToBase: {
1247     const RecordType *DerivedClassTy =
1248       E->getSubExpr()->getType()->getAs<RecordType>();
1249     CXXRecordDecl *DerivedClassDecl =
1250       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1251 
1252     const RecordType *BaseClassTy = E->getType()->getAs<RecordType>();
1253     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl());
1254 
1255     LValue LV = EmitLValue(E->getSubExpr());
1256 
1257     // Perform the derived-to-base conversion
1258     llvm::Value *Base =
1259       GetAddressCXXOfBaseClass(LV.getAddress(), DerivedClassDecl,
1260                                BaseClassDecl, /*NullCheckValue=*/false);
1261 
1262     return LValue::MakeAddr(Base, E->getType().getCVRQualifiers(),
1263                             getContext().getObjCGCAttrKind(E->getType()),
1264                             E->getType().getAddressSpace());
1265   }
1266 
1267   case CastExpr::CK_ToUnion: {
1268     llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1269     EmitAnyExpr(E->getSubExpr(), Temp, false);
1270 
1271     return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1272                             getContext().getObjCGCAttrKind(E->getType()),
1273                             E->getType().getAddressSpace());
1274     }
1275   }
1276 }
1277 
1278 //===--------------------------------------------------------------------===//
1279 //                             Expression Emission
1280 //===--------------------------------------------------------------------===//
1281 
1282 
1283 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
1284   // Builtins never have block type.
1285   if (E->getCallee()->getType()->isBlockPointerType())
1286     return EmitBlockCallExpr(E);
1287 
1288   if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1289     return EmitCXXMemberCallExpr(CE);
1290 
1291   const Decl *TargetDecl = 0;
1292   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1293     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1294       TargetDecl = DRE->getDecl();
1295       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1296         if (unsigned builtinID = FD->getBuiltinID())
1297           return EmitBuiltinExpr(FD, builtinID, E);
1298     }
1299   }
1300 
1301   if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1302     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1303       return EmitCXXOperatorMemberCallExpr(CE, MD);
1304 
1305   if (isa<CXXPseudoDestructorExpr>(E->getCallee())) {
1306     // C++ [expr.pseudo]p1:
1307     //   The result shall only be used as the operand for the function call
1308     //   operator (), and the result of such a call has type void. The only
1309     //   effect is the evaluation of the postfix-expression before the dot or
1310     //   arrow.
1311     EmitScalarExpr(E->getCallee());
1312     return RValue::get(0);
1313   }
1314 
1315   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
1316   return EmitCall(Callee, E->getCallee()->getType(),
1317                   E->arg_begin(), E->arg_end(), TargetDecl);
1318 }
1319 
1320 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
1321   // Comma expressions just emit their LHS then their RHS as an l-value.
1322   if (E->getOpcode() == BinaryOperator::Comma) {
1323     EmitAnyExpr(E->getLHS());
1324     return EmitLValue(E->getRHS());
1325   }
1326 
1327   // Can only get l-value for binary operator expressions which are a
1328   // simple assignment of aggregate type.
1329   if (E->getOpcode() != BinaryOperator::Assign)
1330     return EmitUnsupportedLValue(E, "binary l-value expression");
1331 
1332   llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1333   EmitAggExpr(E, Temp, false);
1334   // FIXME: Are these qualifiers correct?
1335   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1336                           getContext().getObjCGCAttrKind(E->getType()),
1337                           E->getType().getAddressSpace());
1338 }
1339 
1340 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
1341   RValue RV = EmitCallExpr(E);
1342 
1343   if (RV.isScalar()) {
1344     assert(E->getCallReturnType()->isReferenceType() &&
1345            "Can't have a scalar return unless the return type is a "
1346            "reference type!");
1347 
1348     return LValue::MakeAddr(RV.getScalarVal(), E->getType().getCVRQualifiers(),
1349                             getContext().getObjCGCAttrKind(E->getType()),
1350                             E->getType().getAddressSpace());
1351   }
1352 
1353   return LValue::MakeAddr(RV.getAggregateAddr(),
1354                           E->getType().getCVRQualifiers(),
1355                           getContext().getObjCGCAttrKind(E->getType()),
1356                           E->getType().getAddressSpace());
1357 }
1358 
1359 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
1360   // FIXME: This shouldn't require another copy.
1361   llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1362   EmitAggExpr(E, Temp, false);
1363   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1364                           QualType::GCNone, E->getType().getAddressSpace());
1365 }
1366 
1367 LValue
1368 CodeGenFunction::EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E) {
1369   EmitLocalBlockVarDecl(*E->getVarDecl());
1370   return EmitDeclRefLValue(E);
1371 }
1372 
1373 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
1374   llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()), "tmp");
1375   EmitCXXConstructExpr(Temp, E);
1376   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1377                           QualType::GCNone, E->getType().getAddressSpace());
1378 }
1379 
1380 LValue
1381 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
1382   LValue LV = EmitLValue(E->getSubExpr());
1383 
1384   PushCXXTemporary(E->getTemporary(), LV.getAddress());
1385 
1386   return LV;
1387 }
1388 
1389 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
1390   // Can only get l-value for message expression returning aggregate type
1391   RValue RV = EmitObjCMessageExpr(E);
1392   // FIXME: can this be volatile?
1393   return LValue::MakeAddr(RV.getAggregateAddr(),
1394                           E->getType().getCVRQualifiers(),
1395                           getContext().getObjCGCAttrKind(E->getType()),
1396                           E->getType().getAddressSpace());
1397 }
1398 
1399 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1400                                              const ObjCIvarDecl *Ivar) {
1401   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
1402 }
1403 
1404 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
1405                                           llvm::Value *BaseValue,
1406                                           const ObjCIvarDecl *Ivar,
1407                                           unsigned CVRQualifiers) {
1408   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
1409                                                    Ivar, CVRQualifiers);
1410 }
1411 
1412 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
1413   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
1414   llvm::Value *BaseValue = 0;
1415   const Expr *BaseExpr = E->getBase();
1416   unsigned CVRQualifiers = 0;
1417   QualType ObjectTy;
1418   if (E->isArrow()) {
1419     BaseValue = EmitScalarExpr(BaseExpr);
1420     ObjectTy = BaseExpr->getType()->getPointeeType();
1421     CVRQualifiers = ObjectTy.getCVRQualifiers();
1422   } else {
1423     LValue BaseLV = EmitLValue(BaseExpr);
1424     // FIXME: this isn't right for bitfields.
1425     BaseValue = BaseLV.getAddress();
1426     ObjectTy = BaseExpr->getType();
1427     CVRQualifiers = ObjectTy.getCVRQualifiers();
1428   }
1429 
1430   LValue LV =
1431     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), CVRQualifiers);
1432   setObjCGCLValueClass(getContext(), E, LV);
1433   return LV;
1434 }
1435 
1436 LValue
1437 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1438   // This is a special l-value that just issues sends when we load or store
1439   // through it.
1440   return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
1441 }
1442 
1443 LValue
1444 CodeGenFunction::EmitObjCKVCRefLValue(
1445                                 const ObjCImplicitSetterGetterRefExpr *E) {
1446   // This is a special l-value that just issues sends when we load or store
1447   // through it.
1448   return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers());
1449 }
1450 
1451 LValue
1452 CodeGenFunction::EmitObjCSuperExprLValue(const ObjCSuperExpr *E) {
1453   return EmitUnsupportedLValue(E, "use of super");
1454 }
1455 
1456 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
1457 
1458   // Can only get l-value for message expression returning aggregate type
1459   RValue RV = EmitAnyExprToTemp(E);
1460   // FIXME: can this be volatile?
1461   return LValue::MakeAddr(RV.getAggregateAddr(),
1462                           E->getType().getCVRQualifiers(),
1463                           getContext().getObjCGCAttrKind(E->getType()),
1464                           E->getType().getAddressSpace());
1465 }
1466 
1467 
1468 RValue CodeGenFunction::EmitCall(llvm::Value *Callee, QualType CalleeType,
1469                                  CallExpr::const_arg_iterator ArgBeg,
1470                                  CallExpr::const_arg_iterator ArgEnd,
1471                                  const Decl *TargetDecl) {
1472   // Get the actual function type. The callee type will always be a pointer to
1473   // function type or a block pointer type.
1474   assert(CalleeType->isFunctionPointerType() &&
1475          "Call must have function pointer type!");
1476 
1477   QualType FnType = CalleeType->getAs<PointerType>()->getPointeeType();
1478   QualType ResultType = FnType->getAsFunctionType()->getResultType();
1479 
1480   CallArgList Args;
1481   EmitCallArgs(Args, FnType->getAsFunctionProtoType(), ArgBeg, ArgEnd);
1482 
1483   // FIXME: We should not need to do this, it should be part of the function
1484   // type.
1485   unsigned CallingConvention = 0;
1486   if (const llvm::Function *F =
1487       dyn_cast<llvm::Function>(Callee->stripPointerCasts()))
1488     CallingConvention = F->getCallingConv();
1489   return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1490                                                  CallingConvention),
1491                   Callee, Args, TargetDecl);
1492 }
1493