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 "CGCXXABI.h"
18 #include "CGRecordLayout.h"
19 #include "CGObjCRuntime.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "llvm/Intrinsics.h"
23 #include "clang/Frontend/CodeGenOptions.h"
24 #include "llvm/Target/TargetData.h"
25 using namespace clang;
26 using namespace CodeGen;
27 
28 //===--------------------------------------------------------------------===//
29 //                        Miscellaneous Helper Methods
30 //===--------------------------------------------------------------------===//
31 
32 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
33 /// block.
34 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
35                                                     const llvm::Twine &Name) {
36   if (!Builder.isNamePreserving())
37     return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
38   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
39 }
40 
41 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
42                                      llvm::Value *Init) {
43   llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
44   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
45   Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
46 }
47 
48 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
49                                                 const llvm::Twine &Name) {
50   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
51   // FIXME: Should we prefer the preferred type alignment here?
52   CharUnits Align = getContext().getTypeAlignInChars(Ty);
53   Alloc->setAlignment(Align.getQuantity());
54   return Alloc;
55 }
56 
57 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
58                                                  const llvm::Twine &Name) {
59   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
60   // FIXME: Should we prefer the preferred type alignment here?
61   CharUnits Align = getContext().getTypeAlignInChars(Ty);
62   Alloc->setAlignment(Align.getQuantity());
63   return Alloc;
64 }
65 
66 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
67 /// expression and compare the result against zero, returning an Int1Ty value.
68 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
69   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
70     llvm::Value *MemPtr = EmitScalarExpr(E);
71     return CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
72   }
73 
74   QualType BoolTy = getContext().BoolTy;
75   if (!E->getType()->isAnyComplexType())
76     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
77 
78   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
79 }
80 
81 /// EmitAnyExpr - Emit code to compute the specified expression which
82 /// can have any type.  The result is returned as an RValue struct.
83 /// If this is an aggregate expression, AggSlot indicates where the
84 /// result should be returned.
85 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot,
86                                     bool IgnoreResult) {
87   if (!hasAggregateLLVMType(E->getType()))
88     return RValue::get(EmitScalarExpr(E, IgnoreResult));
89   else if (E->getType()->isAnyComplexType())
90     return RValue::getComplex(EmitComplexExpr(E, IgnoreResult, IgnoreResult));
91 
92   EmitAggExpr(E, AggSlot, IgnoreResult);
93   return AggSlot.asRValue();
94 }
95 
96 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
97 /// always be accessible even if no aggregate location is provided.
98 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
99   AggValueSlot AggSlot = AggValueSlot::ignored();
100 
101   if (hasAggregateLLVMType(E->getType()) &&
102       !E->getType()->isAnyComplexType())
103     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
104   return EmitAnyExpr(E, AggSlot);
105 }
106 
107 /// EmitAnyExprToMem - Evaluate an expression into a given memory
108 /// location.
109 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
110                                        llvm::Value *Location,
111                                        bool IsLocationVolatile,
112                                        bool IsInit) {
113   if (E->getType()->isComplexType())
114     EmitComplexExprIntoAddr(E, Location, IsLocationVolatile);
115   else if (hasAggregateLLVMType(E->getType()))
116     EmitAggExpr(E, AggValueSlot::forAddr(Location, IsLocationVolatile, IsInit));
117   else {
118     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
119     LValue LV = MakeAddrLValue(Location, E->getType());
120     EmitStoreThroughLValue(RV, LV, E->getType());
121   }
122 }
123 
124 namespace {
125 /// \brief An adjustment to be made to the temporary created when emitting a
126 /// reference binding, which accesses a particular subobject of that temporary.
127   struct SubobjectAdjustment {
128     enum { DerivedToBaseAdjustment, FieldAdjustment } Kind;
129 
130     union {
131       struct {
132         const CastExpr *BasePath;
133         const CXXRecordDecl *DerivedClass;
134       } DerivedToBase;
135 
136       FieldDecl *Field;
137     };
138 
139     SubobjectAdjustment(const CastExpr *BasePath,
140                         const CXXRecordDecl *DerivedClass)
141       : Kind(DerivedToBaseAdjustment) {
142       DerivedToBase.BasePath = BasePath;
143       DerivedToBase.DerivedClass = DerivedClass;
144     }
145 
146     SubobjectAdjustment(FieldDecl *Field)
147       : Kind(FieldAdjustment) {
148       this->Field = Field;
149     }
150   };
151 }
152 
153 static llvm::Value *
154 CreateReferenceTemporary(CodeGenFunction& CGF, QualType Type,
155                          const NamedDecl *InitializedDecl) {
156   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
157     if (VD->hasGlobalStorage()) {
158       llvm::SmallString<256> Name;
159       CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Name);
160 
161       const llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
162 
163       // Create the reference temporary.
164       llvm::GlobalValue *RefTemp =
165         new llvm::GlobalVariable(CGF.CGM.getModule(),
166                                  RefTempTy, /*isConstant=*/false,
167                                  llvm::GlobalValue::InternalLinkage,
168                                  llvm::Constant::getNullValue(RefTempTy),
169                                  Name.str());
170       return RefTemp;
171     }
172   }
173 
174   return CGF.CreateMemTemp(Type, "ref.tmp");
175 }
176 
177 static llvm::Value *
178 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
179                             llvm::Value *&ReferenceTemporary,
180                             const CXXDestructorDecl *&ReferenceTemporaryDtor,
181                             const NamedDecl *InitializedDecl) {
182   if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
183     E = DAE->getExpr();
184 
185   if (const CXXExprWithTemporaries *TE = dyn_cast<CXXExprWithTemporaries>(E)) {
186     CodeGenFunction::RunCleanupsScope Scope(CGF);
187 
188     return EmitExprForReferenceBinding(CGF, TE->getSubExpr(),
189                                        ReferenceTemporary,
190                                        ReferenceTemporaryDtor,
191                                        InitializedDecl);
192   }
193 
194   RValue RV;
195   if (E->isLValue()) {
196     // Emit the expression as an lvalue.
197     LValue LV = CGF.EmitLValue(E);
198     if (LV.isPropertyRef() || LV.isKVCRef()) {
199       QualType QT = E->getType();
200       RValue RV =
201         LV.isPropertyRef() ? CGF.EmitLoadOfPropertyRefLValue(LV, QT)
202                            : CGF.EmitLoadOfKVCRefLValue(LV, QT);
203       assert(RV.isScalar() && "EmitExprForReferenceBinding");
204       return RV.getScalarVal();
205     }
206 
207     if (LV.isSimple())
208       return LV.getAddress();
209 
210     // We have to load the lvalue.
211     RV = CGF.EmitLoadOfLValue(LV, E->getType());
212   } else {
213     QualType ResultTy = E->getType();
214 
215     llvm::SmallVector<SubobjectAdjustment, 2> Adjustments;
216     while (true) {
217       if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
218         E = PE->getSubExpr();
219         continue;
220       }
221 
222       if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
223         if ((CE->getCastKind() == CK_DerivedToBase ||
224              CE->getCastKind() == CK_UncheckedDerivedToBase) &&
225             E->getType()->isRecordType()) {
226           E = CE->getSubExpr();
227           CXXRecordDecl *Derived
228             = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
229           Adjustments.push_back(SubobjectAdjustment(CE, Derived));
230           continue;
231         }
232 
233         if (CE->getCastKind() == CK_NoOp) {
234           E = CE->getSubExpr();
235           continue;
236         }
237       } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
238         if (!ME->isArrow() && ME->getBase()->isRValue()) {
239           assert(ME->getBase()->getType()->isRecordType());
240           if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
241             E = ME->getBase();
242             Adjustments.push_back(SubobjectAdjustment(Field));
243             continue;
244           }
245         }
246       }
247 
248       // Nothing changed.
249       break;
250     }
251 
252     // Create a reference temporary if necessary.
253     AggValueSlot AggSlot = AggValueSlot::ignored();
254     if (CGF.hasAggregateLLVMType(E->getType()) &&
255         !E->getType()->isAnyComplexType()) {
256       ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
257                                                     InitializedDecl);
258       AggSlot = AggValueSlot::forAddr(ReferenceTemporary, false,
259                                       InitializedDecl != 0);
260     }
261 
262     RV = CGF.EmitAnyExpr(E, AggSlot);
263 
264     if (InitializedDecl) {
265       // Get the destructor for the reference temporary.
266       if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
267         CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
268         if (!ClassDecl->hasTrivialDestructor())
269           ReferenceTemporaryDtor = ClassDecl->getDestructor();
270       }
271     }
272 
273     // Check if need to perform derived-to-base casts and/or field accesses, to
274     // get from the temporary object we created (and, potentially, for which we
275     // extended the lifetime) to the subobject we're binding the reference to.
276     if (!Adjustments.empty()) {
277       llvm::Value *Object = RV.getAggregateAddr();
278       for (unsigned I = Adjustments.size(); I != 0; --I) {
279         SubobjectAdjustment &Adjustment = Adjustments[I-1];
280         switch (Adjustment.Kind) {
281         case SubobjectAdjustment::DerivedToBaseAdjustment:
282           Object =
283               CGF.GetAddressOfBaseClass(Object,
284                                         Adjustment.DerivedToBase.DerivedClass,
285                               Adjustment.DerivedToBase.BasePath->path_begin(),
286                               Adjustment.DerivedToBase.BasePath->path_end(),
287                                         /*NullCheckValue=*/false);
288           break;
289 
290         case SubobjectAdjustment::FieldAdjustment: {
291           LValue LV =
292             CGF.EmitLValueForField(Object, Adjustment.Field, 0);
293           if (LV.isSimple()) {
294             Object = LV.getAddress();
295             break;
296           }
297 
298           // For non-simple lvalues, we actually have to create a copy of
299           // the object we're binding to.
300           QualType T = Adjustment.Field->getType().getNonReferenceType()
301                                                   .getUnqualifiedType();
302           Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
303           LValue TempLV = CGF.MakeAddrLValue(Object,
304                                              Adjustment.Field->getType());
305           CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV, T), TempLV, T);
306           break;
307         }
308 
309         }
310       }
311 
312       const llvm::Type *ResultPtrTy = CGF.ConvertType(ResultTy)->getPointerTo();
313       return CGF.Builder.CreateBitCast(Object, ResultPtrTy, "temp");
314     }
315   }
316 
317   if (RV.isAggregate())
318     return RV.getAggregateAddr();
319 
320   // Create a temporary variable that we can bind the reference to.
321   ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
322                                                 InitializedDecl);
323 
324 
325   unsigned Alignment =
326     CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
327   if (RV.isScalar())
328     CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
329                           /*Volatile=*/false, Alignment, E->getType());
330   else
331     CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
332                            /*Volatile=*/false);
333   return ReferenceTemporary;
334 }
335 
336 RValue
337 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
338                                             const NamedDecl *InitializedDecl) {
339   llvm::Value *ReferenceTemporary = 0;
340   const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
341   llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
342                                                    ReferenceTemporaryDtor,
343                                                    InitializedDecl);
344   if (!ReferenceTemporaryDtor)
345     return RValue::get(Value);
346 
347   // Make sure to call the destructor for the reference temporary.
348   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
349     if (VD->hasGlobalStorage()) {
350       llvm::Constant *DtorFn =
351         CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
352       CGF.EmitCXXGlobalDtorRegistration(DtorFn,
353                                       cast<llvm::Constant>(ReferenceTemporary));
354 
355       return RValue::get(Value);
356     }
357   }
358 
359   PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
360 
361   return RValue::get(Value);
362 }
363 
364 
365 /// getAccessedFieldNo - Given an encoded value and a result number, return the
366 /// input field number being accessed.
367 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
368                                              const llvm::Constant *Elts) {
369   if (isa<llvm::ConstantAggregateZero>(Elts))
370     return 0;
371 
372   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
373 }
374 
375 void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
376   if (!CatchUndefined)
377     return;
378 
379   Address = Builder.CreateBitCast(Address, PtrToInt8Ty);
380 
381   const llvm::Type *IntPtrT = IntPtrTy;
382   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, &IntPtrT, 1);
383   const llvm::IntegerType *Int1Ty = llvm::Type::getInt1Ty(VMContext);
384 
385   // In time, people may want to control this and use a 1 here.
386   llvm::Value *Arg = llvm::ConstantInt::get(Int1Ty, 0);
387   llvm::Value *C = Builder.CreateCall2(F, Address, Arg);
388   llvm::BasicBlock *Cont = createBasicBlock();
389   llvm::BasicBlock *Check = createBasicBlock();
390   llvm::Value *NegativeOne = llvm::ConstantInt::get(IntPtrTy, -1ULL);
391   Builder.CreateCondBr(Builder.CreateICmpEQ(C, NegativeOne), Cont, Check);
392 
393   EmitBlock(Check);
394   Builder.CreateCondBr(Builder.CreateICmpUGE(C,
395                                         llvm::ConstantInt::get(IntPtrTy, Size)),
396                        Cont, getTrapBB());
397   EmitBlock(Cont);
398 }
399 
400 
401 CodeGenFunction::ComplexPairTy CodeGenFunction::
402 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
403                          bool isInc, bool isPre) {
404   ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
405                                             LV.isVolatileQualified());
406 
407   llvm::Value *NextVal;
408   if (isa<llvm::IntegerType>(InVal.first->getType())) {
409     uint64_t AmountVal = isInc ? 1 : -1;
410     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
411 
412     // Add the inc/dec to the real part.
413     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
414   } else {
415     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
416     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
417     if (!isInc)
418       FVal.changeSign();
419     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
420 
421     // Add the inc/dec to the real part.
422     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
423   }
424 
425   ComplexPairTy IncVal(NextVal, InVal.second);
426 
427   // Store the updated result through the lvalue.
428   StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
429 
430   // If this is a postinc, return the value read from memory, otherwise use the
431   // updated value.
432   return isPre ? IncVal : InVal;
433 }
434 
435 
436 //===----------------------------------------------------------------------===//
437 //                         LValue Expression Emission
438 //===----------------------------------------------------------------------===//
439 
440 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
441   if (Ty->isVoidType())
442     return RValue::get(0);
443 
444   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
445     const llvm::Type *EltTy = ConvertType(CTy->getElementType());
446     llvm::Value *U = llvm::UndefValue::get(EltTy);
447     return RValue::getComplex(std::make_pair(U, U));
448   }
449 
450   // If this is a use of an undefined aggregate type, the aggregate must have an
451   // identifiable address.  Just because the contents of the value are undefined
452   // doesn't mean that the address can't be taken and compared.
453   if (hasAggregateLLVMType(Ty)) {
454     llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
455     return RValue::getAggregate(DestPtr);
456   }
457 
458   return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
459 }
460 
461 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
462                                               const char *Name) {
463   ErrorUnsupported(E, Name);
464   return GetUndefRValue(E->getType());
465 }
466 
467 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
468                                               const char *Name) {
469   ErrorUnsupported(E, Name);
470   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
471   return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
472 }
473 
474 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) {
475   LValue LV = EmitLValue(E);
476   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
477     EmitCheck(LV.getAddress(), getContext().getTypeSize(E->getType()) / 8);
478   return LV;
479 }
480 
481 /// EmitLValue - Emit code to compute a designator that specifies the location
482 /// of the expression.
483 ///
484 /// This can return one of two things: a simple address or a bitfield reference.
485 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
486 /// an LLVM pointer type.
487 ///
488 /// If this returns a bitfield reference, nothing about the pointee type of the
489 /// LLVM value is known: For example, it may not be a pointer to an integer.
490 ///
491 /// If this returns a normal address, and if the lvalue's C type is fixed size,
492 /// this method guarantees that the returned pointer type will point to an LLVM
493 /// type of the same size of the lvalue's type.  If the lvalue has a variable
494 /// length type, this is not possible.
495 ///
496 LValue CodeGenFunction::EmitLValue(const Expr *E) {
497   llvm::DenseMap<const Expr *, LValue>::iterator I =
498                                       CGF.ConditionalSaveLValueExprs.find(E);
499   if (I != CGF.ConditionalSaveLValueExprs.end())
500     return I->second;
501 
502   switch (E->getStmtClass()) {
503   default: return EmitUnsupportedLValue(E, "l-value expression");
504 
505   case Expr::ObjCSelectorExprClass:
506   return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
507   case Expr::ObjCIsaExprClass:
508     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
509   case Expr::BinaryOperatorClass:
510     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
511   case Expr::CompoundAssignOperatorClass:
512     return EmitCompoundAssignOperatorLValue(cast<CompoundAssignOperator>(E));
513   case Expr::CallExprClass:
514   case Expr::CXXMemberCallExprClass:
515   case Expr::CXXOperatorCallExprClass:
516     return EmitCallExprLValue(cast<CallExpr>(E));
517   case Expr::VAArgExprClass:
518     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
519   case Expr::DeclRefExprClass:
520     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
521   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
522   case Expr::PredefinedExprClass:
523     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
524   case Expr::StringLiteralClass:
525     return EmitStringLiteralLValue(cast<StringLiteral>(E));
526   case Expr::ObjCEncodeExprClass:
527     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
528 
529   case Expr::BlockDeclRefExprClass:
530     return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
531 
532   case Expr::CXXTemporaryObjectExprClass:
533   case Expr::CXXConstructExprClass:
534     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
535   case Expr::CXXBindTemporaryExprClass:
536     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
537   case Expr::CXXExprWithTemporariesClass:
538     return EmitCXXExprWithTemporariesLValue(cast<CXXExprWithTemporaries>(E));
539   case Expr::CXXScalarValueInitExprClass:
540     return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
541   case Expr::CXXDefaultArgExprClass:
542     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
543   case Expr::CXXTypeidExprClass:
544     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
545 
546   case Expr::ObjCMessageExprClass:
547     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
548   case Expr::ObjCIvarRefExprClass:
549     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
550   case Expr::ObjCPropertyRefExprClass:
551     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
552   case Expr::ObjCImplicitSetterGetterRefExprClass:
553     return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E));
554   case Expr::StmtExprClass:
555     return EmitStmtExprLValue(cast<StmtExpr>(E));
556   case Expr::UnaryOperatorClass:
557     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
558   case Expr::ArraySubscriptExprClass:
559     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
560   case Expr::ExtVectorElementExprClass:
561     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
562   case Expr::MemberExprClass:
563     return EmitMemberExpr(cast<MemberExpr>(E));
564   case Expr::CompoundLiteralExprClass:
565     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
566   case Expr::ConditionalOperatorClass:
567     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
568   case Expr::ChooseExprClass:
569     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
570   case Expr::ImplicitCastExprClass:
571   case Expr::CStyleCastExprClass:
572   case Expr::CXXFunctionalCastExprClass:
573   case Expr::CXXStaticCastExprClass:
574   case Expr::CXXDynamicCastExprClass:
575   case Expr::CXXReinterpretCastExprClass:
576   case Expr::CXXConstCastExprClass:
577     return EmitCastLValue(cast<CastExpr>(E));
578   }
579 }
580 
581 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
582                                               unsigned Alignment, QualType Ty,
583                                               llvm::MDNode *TBAAInfo) {
584   llvm::LoadInst *Load = Builder.CreateLoad(Addr, "tmp");
585   if (Volatile)
586     Load->setVolatile(true);
587   if (Alignment)
588     Load->setAlignment(Alignment);
589   if (TBAAInfo)
590     CGM.DecorateInstruction(Load, TBAAInfo);
591 
592   return EmitFromMemory(Load, Ty);
593 }
594 
595 static bool isBooleanUnderlyingType(QualType Ty) {
596   if (const EnumType *ET = dyn_cast<EnumType>(Ty))
597     return ET->getDecl()->getIntegerType()->isBooleanType();
598   return false;
599 }
600 
601 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
602   // Bool has a different representation in memory than in registers.
603   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
604     // This should really always be an i1, but sometimes it's already
605     // an i8, and it's awkward to track those cases down.
606     if (Value->getType()->isIntegerTy(1))
607       return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
608     assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
609   }
610 
611   return Value;
612 }
613 
614 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
615   // Bool has a different representation in memory than in registers.
616   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
617     assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
618     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
619   }
620 
621   return Value;
622 }
623 
624 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
625                                         bool Volatile, unsigned Alignment,
626                                         QualType Ty,
627                                         llvm::MDNode *TBAAInfo) {
628   Value = EmitToMemory(Value, Ty);
629   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
630   if (Alignment)
631     Store->setAlignment(Alignment);
632   if (TBAAInfo)
633     CGM.DecorateInstruction(Store, TBAAInfo);
634 }
635 
636 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
637 /// method emits the address of the lvalue, then loads the result as an rvalue,
638 /// returning the rvalue.
639 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
640   if (LV.isObjCWeak()) {
641     // load of a __weak object.
642     llvm::Value *AddrWeakObj = LV.getAddress();
643     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
644                                                              AddrWeakObj));
645   }
646 
647   if (LV.isSimple()) {
648     llvm::Value *Ptr = LV.getAddress();
649 
650     // Functions are l-values that don't require loading.
651     if (ExprType->isFunctionType())
652       return RValue::get(Ptr);
653 
654     // Everything needs a load.
655     return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
656                                         LV.getAlignment(), ExprType,
657                                         LV.getTBAAInfo()));
658 
659   }
660 
661   if (LV.isVectorElt()) {
662     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
663                                           LV.isVolatileQualified(), "tmp");
664     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
665                                                     "vecext"));
666   }
667 
668   // If this is a reference to a subset of the elements of a vector, either
669   // shuffle the input or extract/insert them as appropriate.
670   if (LV.isExtVectorElt())
671     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
672 
673   if (LV.isBitField())
674     return EmitLoadOfBitfieldLValue(LV, ExprType);
675 
676   if (LV.isPropertyRef())
677     return EmitLoadOfPropertyRefLValue(LV, ExprType);
678 
679   assert(LV.isKVCRef() && "Unknown LValue type!");
680   return EmitLoadOfKVCRefLValue(LV, ExprType);
681 }
682 
683 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
684                                                  QualType ExprType) {
685   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
686 
687   // Get the output type.
688   const llvm::Type *ResLTy = ConvertType(ExprType);
689   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
690 
691   // Compute the result as an OR of all of the individual component accesses.
692   llvm::Value *Res = 0;
693   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
694     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
695 
696     // Get the field pointer.
697     llvm::Value *Ptr = LV.getBitFieldBaseAddr();
698 
699     // Only offset by the field index if used, so that incoming values are not
700     // required to be structures.
701     if (AI.FieldIndex)
702       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
703 
704     // Offset by the byte offset, if used.
705     if (AI.FieldByteOffset) {
706       const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
707       Ptr = Builder.CreateBitCast(Ptr, i8PTy);
708       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs");
709     }
710 
711     // Cast to the access type.
712     const llvm::Type *PTy = llvm::Type::getIntNPtrTy(VMContext, AI.AccessWidth,
713                                                     ExprType.getAddressSpace());
714     Ptr = Builder.CreateBitCast(Ptr, PTy);
715 
716     // Perform the load.
717     llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
718     if (AI.AccessAlignment)
719       Load->setAlignment(AI.AccessAlignment);
720 
721     // Shift out unused low bits and mask out unused high bits.
722     llvm::Value *Val = Load;
723     if (AI.FieldBitStart)
724       Val = Builder.CreateLShr(Load, AI.FieldBitStart);
725     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
726                                                             AI.TargetBitWidth),
727                             "bf.clear");
728 
729     // Extend or truncate to the target size.
730     if (AI.AccessWidth < ResSizeInBits)
731       Val = Builder.CreateZExt(Val, ResLTy);
732     else if (AI.AccessWidth > ResSizeInBits)
733       Val = Builder.CreateTrunc(Val, ResLTy);
734 
735     // Shift into place, and OR into the result.
736     if (AI.TargetBitOffset)
737       Val = Builder.CreateShl(Val, AI.TargetBitOffset);
738     Res = Res ? Builder.CreateOr(Res, Val) : Val;
739   }
740 
741   // If the bit-field is signed, perform the sign-extension.
742   //
743   // FIXME: This can easily be folded into the load of the high bits, which
744   // could also eliminate the mask of high bits in some situations.
745   if (Info.isSigned()) {
746     unsigned ExtraBits = ResSizeInBits - Info.getSize();
747     if (ExtraBits)
748       Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
749                                ExtraBits, "bf.val.sext");
750   }
751 
752   return RValue::get(Res);
753 }
754 
755 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
756                                                     QualType ExprType) {
757   return EmitObjCPropertyGet(LV.getPropertyRefExpr());
758 }
759 
760 RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV,
761                                                QualType ExprType) {
762   return EmitObjCPropertyGet(LV.getKVCRefExpr());
763 }
764 
765 // If this is a reference to a subset of the elements of a vector, create an
766 // appropriate shufflevector.
767 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
768                                                          QualType ExprType) {
769   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
770                                         LV.isVolatileQualified(), "tmp");
771 
772   const llvm::Constant *Elts = LV.getExtVectorElts();
773 
774   // If the result of the expression is a non-vector type, we must be extracting
775   // a single element.  Just codegen as an extractelement.
776   const VectorType *ExprVT = ExprType->getAs<VectorType>();
777   if (!ExprVT) {
778     unsigned InIdx = getAccessedFieldNo(0, Elts);
779     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
780     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
781   }
782 
783   // Always use shuffle vector to try to retain the original program structure
784   unsigned NumResultElts = ExprVT->getNumElements();
785 
786   llvm::SmallVector<llvm::Constant*, 4> Mask;
787   for (unsigned i = 0; i != NumResultElts; ++i) {
788     unsigned InIdx = getAccessedFieldNo(i, Elts);
789     Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx));
790   }
791 
792   llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
793   Vec = Builder.CreateShuffleVector(Vec,
794                                     llvm::UndefValue::get(Vec->getType()),
795                                     MaskV, "tmp");
796   return RValue::get(Vec);
797 }
798 
799 
800 
801 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
802 /// lvalue, where both are guaranteed to the have the same type, and that type
803 /// is 'Ty'.
804 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
805                                              QualType Ty) {
806   if (!Dst.isSimple()) {
807     if (Dst.isVectorElt()) {
808       // Read/modify/write the vector, inserting the new element.
809       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
810                                             Dst.isVolatileQualified(), "tmp");
811       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
812                                         Dst.getVectorIdx(), "vecins");
813       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
814       return;
815     }
816 
817     // If this is an update of extended vector elements, insert them as
818     // appropriate.
819     if (Dst.isExtVectorElt())
820       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
821 
822     if (Dst.isBitField())
823       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
824 
825     if (Dst.isPropertyRef())
826       return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
827 
828     assert(Dst.isKVCRef() && "Unknown LValue type");
829     return EmitStoreThroughKVCRefLValue(Src, Dst, Ty);
830   }
831 
832   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
833     // load of a __weak object.
834     llvm::Value *LvalueDst = Dst.getAddress();
835     llvm::Value *src = Src.getScalarVal();
836      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
837     return;
838   }
839 
840   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
841     // load of a __strong object.
842     llvm::Value *LvalueDst = Dst.getAddress();
843     llvm::Value *src = Src.getScalarVal();
844     if (Dst.isObjCIvar()) {
845       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
846       const llvm::Type *ResultType = ConvertType(getContext().LongTy);
847       llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
848       llvm::Value *dst = RHS;
849       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
850       llvm::Value *LHS =
851         Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
852       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
853       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
854                                               BytesBetween);
855     } else if (Dst.isGlobalObjCRef()) {
856       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
857                                                 Dst.isThreadLocalRef());
858     }
859     else
860       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
861     return;
862   }
863 
864   assert(Src.isScalar() && "Can't emit an agg store with this method");
865   EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
866                     Dst.isVolatileQualified(), Dst.getAlignment(), Ty,
867                     Dst.getTBAAInfo());
868 }
869 
870 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
871                                                      QualType Ty,
872                                                      llvm::Value **Result) {
873   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
874 
875   // Get the output type.
876   const llvm::Type *ResLTy = ConvertTypeForMem(Ty);
877   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
878 
879   // Get the source value, truncated to the width of the bit-field.
880   llvm::Value *SrcVal = Src.getScalarVal();
881 
882   if (Ty->isBooleanType())
883     SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
884 
885   SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
886                                                                 Info.getSize()),
887                              "bf.value");
888 
889   // Return the new value of the bit-field, if requested.
890   if (Result) {
891     // Cast back to the proper type for result.
892     const llvm::Type *SrcTy = Src.getScalarVal()->getType();
893     llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
894                                                    "bf.reload.val");
895 
896     // Sign extend if necessary.
897     if (Info.isSigned()) {
898       unsigned ExtraBits = ResSizeInBits - Info.getSize();
899       if (ExtraBits)
900         ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
901                                        ExtraBits, "bf.reload.sext");
902     }
903 
904     *Result = ReloadVal;
905   }
906 
907   // Iterate over the components, writing each piece to memory.
908   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
909     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
910 
911     // Get the field pointer.
912     llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
913 
914     // Only offset by the field index if used, so that incoming values are not
915     // required to be structures.
916     if (AI.FieldIndex)
917       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
918 
919     // Offset by the byte offset, if used.
920     if (AI.FieldByteOffset) {
921       const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
922       Ptr = Builder.CreateBitCast(Ptr, i8PTy);
923       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs");
924     }
925 
926     // Cast to the access type.
927     const llvm::Type *PTy = llvm::Type::getIntNPtrTy(VMContext, AI.AccessWidth,
928                                                      Ty.getAddressSpace());
929     Ptr = Builder.CreateBitCast(Ptr, PTy);
930 
931     // Extract the piece of the bit-field value to write in this access, limited
932     // to the values that are part of this access.
933     llvm::Value *Val = SrcVal;
934     if (AI.TargetBitOffset)
935       Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
936     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
937                                                             AI.TargetBitWidth));
938 
939     // Extend or truncate to the access size.
940     const llvm::Type *AccessLTy =
941       llvm::Type::getIntNTy(VMContext, AI.AccessWidth);
942     if (ResSizeInBits < AI.AccessWidth)
943       Val = Builder.CreateZExt(Val, AccessLTy);
944     else if (ResSizeInBits > AI.AccessWidth)
945       Val = Builder.CreateTrunc(Val, AccessLTy);
946 
947     // Shift into the position in memory.
948     if (AI.FieldBitStart)
949       Val = Builder.CreateShl(Val, AI.FieldBitStart);
950 
951     // If necessary, load and OR in bits that are outside of the bit-field.
952     if (AI.TargetBitWidth != AI.AccessWidth) {
953       llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
954       if (AI.AccessAlignment)
955         Load->setAlignment(AI.AccessAlignment);
956 
957       // Compute the mask for zeroing the bits that are part of the bit-field.
958       llvm::APInt InvMask =
959         ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
960                                  AI.FieldBitStart + AI.TargetBitWidth);
961 
962       // Apply the mask and OR in to the value to write.
963       Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
964     }
965 
966     // Write the value.
967     llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
968                                                  Dst.isVolatileQualified());
969     if (AI.AccessAlignment)
970       Store->setAlignment(AI.AccessAlignment);
971   }
972 }
973 
974 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
975                                                         LValue Dst,
976                                                         QualType Ty) {
977   EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
978 }
979 
980 void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src,
981                                                    LValue Dst,
982                                                    QualType Ty) {
983   EmitObjCPropertySet(Dst.getKVCRefExpr(), Src);
984 }
985 
986 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
987                                                                LValue Dst,
988                                                                QualType Ty) {
989   // This access turns into a read/modify/write of the vector.  Load the input
990   // value now.
991   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
992                                         Dst.isVolatileQualified(), "tmp");
993   const llvm::Constant *Elts = Dst.getExtVectorElts();
994 
995   llvm::Value *SrcVal = Src.getScalarVal();
996 
997   if (const VectorType *VTy = Ty->getAs<VectorType>()) {
998     unsigned NumSrcElts = VTy->getNumElements();
999     unsigned NumDstElts =
1000        cast<llvm::VectorType>(Vec->getType())->getNumElements();
1001     if (NumDstElts == NumSrcElts) {
1002       // Use shuffle vector is the src and destination are the same number of
1003       // elements and restore the vector mask since it is on the side it will be
1004       // stored.
1005       llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1006       for (unsigned i = 0; i != NumSrcElts; ++i) {
1007         unsigned InIdx = getAccessedFieldNo(i, Elts);
1008         Mask[InIdx] = llvm::ConstantInt::get(Int32Ty, i);
1009       }
1010 
1011       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
1012       Vec = Builder.CreateShuffleVector(SrcVal,
1013                                         llvm::UndefValue::get(Vec->getType()),
1014                                         MaskV, "tmp");
1015     } else if (NumDstElts > NumSrcElts) {
1016       // Extended the source vector to the same length and then shuffle it
1017       // into the destination.
1018       // FIXME: since we're shuffling with undef, can we just use the indices
1019       //        into that?  This could be simpler.
1020       llvm::SmallVector<llvm::Constant*, 4> ExtMask;
1021       unsigned i;
1022       for (i = 0; i != NumSrcElts; ++i)
1023         ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1024       for (; i != NumDstElts; ++i)
1025         ExtMask.push_back(llvm::UndefValue::get(Int32Ty));
1026       llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0],
1027                                                         ExtMask.size());
1028       llvm::Value *ExtSrcVal =
1029         Builder.CreateShuffleVector(SrcVal,
1030                                     llvm::UndefValue::get(SrcVal->getType()),
1031                                     ExtMaskV, "tmp");
1032       // build identity
1033       llvm::SmallVector<llvm::Constant*, 4> Mask;
1034       for (unsigned i = 0; i != NumDstElts; ++i)
1035         Mask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1036 
1037       // modify when what gets shuffled in
1038       for (unsigned i = 0; i != NumSrcElts; ++i) {
1039         unsigned Idx = getAccessedFieldNo(i, Elts);
1040         Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts);
1041       }
1042       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
1043       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
1044     } else {
1045       // We should never shorten the vector
1046       assert(0 && "unexpected shorten vector length");
1047     }
1048   } else {
1049     // If the Src is a scalar (not a vector) it must be updating one element.
1050     unsigned InIdx = getAccessedFieldNo(0, Elts);
1051     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1052     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
1053   }
1054 
1055   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
1056 }
1057 
1058 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
1059 // generating write-barries API. It is currently a global, ivar,
1060 // or neither.
1061 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1062                                  LValue &LV) {
1063   if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC)
1064     return;
1065 
1066   if (isa<ObjCIvarRefExpr>(E)) {
1067     LV.setObjCIvar(true);
1068     ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1069     LV.setBaseIvarExp(Exp->getBase());
1070     LV.setObjCArray(E->getType()->isArrayType());
1071     return;
1072   }
1073 
1074   if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1075     if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1076       if (VD->hasGlobalStorage()) {
1077         LV.setGlobalObjCRef(true);
1078         LV.setThreadLocalRef(VD->isThreadSpecified());
1079       }
1080     }
1081     LV.setObjCArray(E->getType()->isArrayType());
1082     return;
1083   }
1084 
1085   if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1086     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1087     return;
1088   }
1089 
1090   if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1091     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1092     if (LV.isObjCIvar()) {
1093       // If cast is to a structure pointer, follow gcc's behavior and make it
1094       // a non-ivar write-barrier.
1095       QualType ExpTy = E->getType();
1096       if (ExpTy->isPointerType())
1097         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1098       if (ExpTy->isRecordType())
1099         LV.setObjCIvar(false);
1100     }
1101     return;
1102   }
1103   if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1104     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1105     return;
1106   }
1107 
1108   if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1109     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1110     return;
1111   }
1112 
1113   if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1114     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1115     if (LV.isObjCIvar() && !LV.isObjCArray())
1116       // Using array syntax to assigning to what an ivar points to is not
1117       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1118       LV.setObjCIvar(false);
1119     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1120       // Using array syntax to assigning to what global points to is not
1121       // same as assigning to the global itself. {id *G;} G[i] = 0;
1122       LV.setGlobalObjCRef(false);
1123     return;
1124   }
1125 
1126   if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1127     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1128     // We don't know if member is an 'ivar', but this flag is looked at
1129     // only in the context of LV.isObjCIvar().
1130     LV.setObjCArray(E->getType()->isArrayType());
1131     return;
1132   }
1133 }
1134 
1135 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1136                                       const Expr *E, const VarDecl *VD) {
1137   assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
1138          "Var decl must have external storage or be a file var decl!");
1139 
1140   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1141   if (VD->getType()->isReferenceType())
1142     V = CGF.Builder.CreateLoad(V, "tmp");
1143   unsigned Alignment = CGF.getContext().getDeclAlign(VD).getQuantity();
1144   LValue LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1145   setObjCGCLValueClass(CGF.getContext(), E, LV);
1146   return LV;
1147 }
1148 
1149 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1150                                       const Expr *E, const FunctionDecl *FD) {
1151   llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1152   if (!FD->hasPrototype()) {
1153     if (const FunctionProtoType *Proto =
1154             FD->getType()->getAs<FunctionProtoType>()) {
1155       // Ugly case: for a K&R-style definition, the type of the definition
1156       // isn't the same as the type of a use.  Correct for this with a
1157       // bitcast.
1158       QualType NoProtoType =
1159           CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1160       NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1161       V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType), "tmp");
1162     }
1163   }
1164   unsigned Alignment = CGF.getContext().getDeclAlign(FD).getQuantity();
1165   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1166 }
1167 
1168 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1169   const NamedDecl *ND = E->getDecl();
1170   unsigned Alignment = CGF.getContext().getDeclAlign(ND).getQuantity();
1171 
1172   if (ND->hasAttr<WeakRefAttr>()) {
1173     const ValueDecl *VD = cast<ValueDecl>(ND);
1174     llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1175     return MakeAddrLValue(Aliasee, E->getType(), Alignment);
1176   }
1177 
1178   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1179 
1180     // Check if this is a global variable.
1181     if (VD->hasExternalStorage() || VD->isFileVarDecl())
1182       return EmitGlobalVarDeclLValue(*this, E, VD);
1183 
1184     bool NonGCable = VD->hasLocalStorage() &&
1185                      !VD->getType()->isReferenceType() &&
1186                      !VD->hasAttr<BlocksAttr>();
1187 
1188     llvm::Value *V = LocalDeclMap[VD];
1189     if (!V && VD->isStaticLocal())
1190       V = CGM.getStaticLocalDeclAddress(VD);
1191     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1192 
1193     if (VD->hasAttr<BlocksAttr>()) {
1194       V = Builder.CreateStructGEP(V, 1, "forwarding");
1195       V = Builder.CreateLoad(V);
1196       V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
1197                                   VD->getNameAsString());
1198     }
1199     if (VD->getType()->isReferenceType())
1200       V = Builder.CreateLoad(V, "tmp");
1201 
1202     LValue LV = MakeAddrLValue(V, E->getType(), Alignment);
1203     if (NonGCable) {
1204       LV.getQuals().removeObjCGCAttr();
1205       LV.setNonGC(true);
1206     }
1207     setObjCGCLValueClass(getContext(), E, LV);
1208     return LV;
1209   }
1210 
1211   // If we're emitting an instance method as an independent lvalue,
1212   // we're actually emitting a member pointer.
1213   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1214     if (MD->isInstance()) {
1215       llvm::Value *V = CGM.getCXXABI().EmitMemberPointer(MD);
1216       return MakeAddrLValue(V, MD->getType(), Alignment);
1217     }
1218   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1219     return EmitFunctionDeclLValue(*this, E, FD);
1220 
1221   // If we're emitting a field as an independent lvalue, we're
1222   // actually emitting a member pointer.
1223   if (const FieldDecl *FD = dyn_cast<FieldDecl>(ND)) {
1224     llvm::Value *V = CGM.getCXXABI().EmitMemberPointer(FD);
1225     return MakeAddrLValue(V, FD->getType(), Alignment);
1226   }
1227 
1228   assert(false && "Unhandled DeclRefExpr");
1229 
1230   // an invalid LValue, but the assert will
1231   // ensure that this point is never reached.
1232   return LValue();
1233 }
1234 
1235 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
1236   unsigned Alignment =
1237     CGF.getContext().getDeclAlign(E->getDecl()).getQuantity();
1238   return MakeAddrLValue(GetAddrOfBlockDecl(E), E->getType(), Alignment);
1239 }
1240 
1241 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1242   // __extension__ doesn't affect lvalue-ness.
1243   if (E->getOpcode() == UO_Extension)
1244     return EmitLValue(E->getSubExpr());
1245 
1246   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1247   switch (E->getOpcode()) {
1248   default: assert(0 && "Unknown unary operator lvalue!");
1249   case UO_Deref: {
1250     QualType T = E->getSubExpr()->getType()->getPointeeType();
1251     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1252 
1253     LValue LV = MakeAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1254     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1255 
1256     // We should not generate __weak write barrier on indirect reference
1257     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1258     // But, we continue to generate __strong write barrier on indirect write
1259     // into a pointer to object.
1260     if (getContext().getLangOptions().ObjC1 &&
1261         getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
1262         LV.isObjCWeak())
1263       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1264     return LV;
1265   }
1266   case UO_Real:
1267   case UO_Imag: {
1268     LValue LV = EmitLValue(E->getSubExpr());
1269     unsigned Idx = E->getOpcode() == UO_Imag;
1270     return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
1271                                                     Idx, "idx"),
1272                           ExprTy);
1273   }
1274   case UO_PreInc:
1275   case UO_PreDec: {
1276     LValue LV = EmitLValue(E->getSubExpr());
1277     bool isInc = E->getOpcode() == UO_PreInc;
1278 
1279     if (E->getType()->isAnyComplexType())
1280       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1281     else
1282       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1283     return LV;
1284   }
1285   }
1286 }
1287 
1288 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1289   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1290                         E->getType());
1291 }
1292 
1293 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1294   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1295                         E->getType());
1296 }
1297 
1298 
1299 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1300   switch (E->getIdentType()) {
1301   default:
1302     return EmitUnsupportedLValue(E, "predefined expression");
1303 
1304   case PredefinedExpr::Func:
1305   case PredefinedExpr::Function:
1306   case PredefinedExpr::PrettyFunction: {
1307     unsigned Type = E->getIdentType();
1308     std::string GlobalVarName;
1309 
1310     switch (Type) {
1311     default: assert(0 && "Invalid type");
1312     case PredefinedExpr::Func:
1313       GlobalVarName = "__func__.";
1314       break;
1315     case PredefinedExpr::Function:
1316       GlobalVarName = "__FUNCTION__.";
1317       break;
1318     case PredefinedExpr::PrettyFunction:
1319       GlobalVarName = "__PRETTY_FUNCTION__.";
1320       break;
1321     }
1322 
1323     llvm::StringRef FnName = CurFn->getName();
1324     if (FnName.startswith("\01"))
1325       FnName = FnName.substr(1);
1326     GlobalVarName += FnName;
1327 
1328     const Decl *CurDecl = CurCodeDecl;
1329     if (CurDecl == 0)
1330       CurDecl = getContext().getTranslationUnitDecl();
1331 
1332     std::string FunctionName =
1333       PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurDecl);
1334 
1335     llvm::Constant *C =
1336       CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
1337     return MakeAddrLValue(C, E->getType());
1338   }
1339   }
1340 }
1341 
1342 llvm::BasicBlock *CodeGenFunction::getTrapBB() {
1343   const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1344 
1345   // If we are not optimzing, don't collapse all calls to trap in the function
1346   // to the same call, that way, in the debugger they can see which operation
1347   // did in fact fail.  If we are optimizing, we collapse all calls to trap down
1348   // to just one per function to save on codesize.
1349   if (GCO.OptimizationLevel && TrapBB)
1350     return TrapBB;
1351 
1352   llvm::BasicBlock *Cont = 0;
1353   if (HaveInsertPoint()) {
1354     Cont = createBasicBlock("cont");
1355     EmitBranch(Cont);
1356   }
1357   TrapBB = createBasicBlock("trap");
1358   EmitBlock(TrapBB);
1359 
1360   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap, 0, 0);
1361   llvm::CallInst *TrapCall = Builder.CreateCall(F);
1362   TrapCall->setDoesNotReturn();
1363   TrapCall->setDoesNotThrow();
1364   Builder.CreateUnreachable();
1365 
1366   if (Cont)
1367     EmitBlock(Cont);
1368   return TrapBB;
1369 }
1370 
1371 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1372 /// array to pointer, return the array subexpression.
1373 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1374   // If this isn't just an array->pointer decay, bail out.
1375   const CastExpr *CE = dyn_cast<CastExpr>(E);
1376   if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
1377     return 0;
1378 
1379   // If this is a decay from variable width array, bail out.
1380   const Expr *SubExpr = CE->getSubExpr();
1381   if (SubExpr->getType()->isVariableArrayType())
1382     return 0;
1383 
1384   return SubExpr;
1385 }
1386 
1387 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1388   // The index must always be an integer, which is not an aggregate.  Emit it.
1389   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
1390   QualType IdxTy  = E->getIdx()->getType();
1391   bool IdxSigned = IdxTy->isSignedIntegerType();
1392 
1393   // If the base is a vector type, then we are forming a vector element lvalue
1394   // with this subscript.
1395   if (E->getBase()->getType()->isVectorType()) {
1396     // Emit the vector as an lvalue to get its address.
1397     LValue LHS = EmitLValue(E->getBase());
1398     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
1399     Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vidx");
1400     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
1401                                  E->getBase()->getType().getCVRQualifiers());
1402   }
1403 
1404   // Extend or truncate the index type to 32 or 64-bits.
1405   if (!Idx->getType()->isIntegerTy(LLVMPointerWidth))
1406     Idx = Builder.CreateIntCast(Idx, IntPtrTy,
1407                                 IdxSigned, "idxprom");
1408 
1409   // FIXME: As llvm implements the object size checking, this can come out.
1410   if (CatchUndefined) {
1411     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){
1412       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1413         if (ICE->getCastKind() == CK_ArrayToPointerDecay) {
1414           if (const ConstantArrayType *CAT
1415               = getContext().getAsConstantArrayType(DRE->getType())) {
1416             llvm::APInt Size = CAT->getSize();
1417             llvm::BasicBlock *Cont = createBasicBlock("cont");
1418             Builder.CreateCondBr(Builder.CreateICmpULE(Idx,
1419                                   llvm::ConstantInt::get(Idx->getType(), Size)),
1420                                  Cont, getTrapBB());
1421             EmitBlock(Cont);
1422           }
1423         }
1424       }
1425     }
1426   }
1427 
1428   // We know that the pointer points to a type of the correct size, unless the
1429   // size is a VLA or Objective-C interface.
1430   llvm::Value *Address = 0;
1431   if (const VariableArrayType *VAT =
1432         getContext().getAsVariableArrayType(E->getType())) {
1433     llvm::Value *VLASize = GetVLASize(VAT);
1434 
1435     Idx = Builder.CreateMul(Idx, VLASize);
1436 
1437     const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
1438 
1439     // The base must be a pointer, which is not an aggregate.  Emit it.
1440     llvm::Value *Base = EmitScalarExpr(E->getBase());
1441 
1442     Address = Builder.CreateInBoundsGEP(Builder.CreateBitCast(Base, i8PTy),
1443                                         Idx, "arrayidx");
1444     Address = Builder.CreateBitCast(Address, Base->getType());
1445   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1446     // Indexing over an interface, as in "NSString *P; P[4];"
1447     llvm::Value *InterfaceSize =
1448       llvm::ConstantInt::get(Idx->getType(),
1449           getContext().getTypeSizeInChars(OIT).getQuantity());
1450 
1451     Idx = Builder.CreateMul(Idx, InterfaceSize);
1452 
1453     const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
1454 
1455     // The base must be a pointer, which is not an aggregate.  Emit it.
1456     llvm::Value *Base = EmitScalarExpr(E->getBase());
1457     Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy),
1458                                 Idx, "arrayidx");
1459     Address = Builder.CreateBitCast(Address, Base->getType());
1460   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1461     // If this is A[i] where A is an array, the frontend will have decayed the
1462     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
1463     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1464     // "gep x, i" here.  Emit one "gep A, 0, i".
1465     assert(Array->getType()->isArrayType() &&
1466            "Array to pointer decay must have array source type!");
1467     llvm::Value *ArrayPtr = EmitLValue(Array).getAddress();
1468     llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1469     llvm::Value *Args[] = { Zero, Idx };
1470 
1471     Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, Args+2, "arrayidx");
1472   } else {
1473     // The base must be a pointer, which is not an aggregate.  Emit it.
1474     llvm::Value *Base = EmitScalarExpr(E->getBase());
1475     Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1476   }
1477 
1478   QualType T = E->getBase()->getType()->getPointeeType();
1479   assert(!T.isNull() &&
1480          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
1481 
1482   LValue LV = MakeAddrLValue(Address, T);
1483   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
1484 
1485   if (getContext().getLangOptions().ObjC1 &&
1486       getContext().getLangOptions().getGCMode() != LangOptions::NonGC) {
1487     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1488     setObjCGCLValueClass(getContext(), E, LV);
1489   }
1490   return LV;
1491 }
1492 
1493 static
1494 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
1495                                        llvm::SmallVector<unsigned, 4> &Elts) {
1496   llvm::SmallVector<llvm::Constant*, 4> CElts;
1497 
1498   const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
1499   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
1500     CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i]));
1501 
1502   return llvm::ConstantVector::get(&CElts[0], CElts.size());
1503 }
1504 
1505 LValue CodeGenFunction::
1506 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
1507   // Emit the base vector as an l-value.
1508   LValue Base;
1509 
1510   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1511   if (E->isArrow()) {
1512     // If it is a pointer to a vector, emit the address and form an lvalue with
1513     // it.
1514     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1515     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1516     Base = MakeAddrLValue(Ptr, PT->getPointeeType());
1517     Base.getQuals().removeObjCGCAttr();
1518   } else if (E->getBase()->isGLValue()) {
1519     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
1520     // emit the base as an lvalue.
1521     assert(E->getBase()->getType()->isVectorType());
1522     Base = EmitLValue(E->getBase());
1523   } else {
1524     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
1525     assert(E->getBase()->getType()->getAs<VectorType>() &&
1526            "Result must be a vector");
1527     llvm::Value *Vec = EmitScalarExpr(E->getBase());
1528 
1529     // Store the vector to memory (because LValue wants an address).
1530     llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
1531     Builder.CreateStore(Vec, VecMem);
1532     Base = MakeAddrLValue(VecMem, E->getBase()->getType());
1533   }
1534 
1535   // Encode the element access list into a vector of unsigned indices.
1536   llvm::SmallVector<unsigned, 4> Indices;
1537   E->getEncodedElementAccess(Indices);
1538 
1539   if (Base.isSimple()) {
1540     llvm::Constant *CV = GenerateConstantVector(VMContext, Indices);
1541     return LValue::MakeExtVectorElt(Base.getAddress(), CV,
1542                                     Base.getVRQualifiers());
1543   }
1544   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1545 
1546   llvm::Constant *BaseElts = Base.getExtVectorElts();
1547   llvm::SmallVector<llvm::Constant *, 4> CElts;
1548 
1549   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1550     if (isa<llvm::ConstantAggregateZero>(BaseElts))
1551       CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0));
1552     else
1553       CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i])));
1554   }
1555   llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
1556   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
1557                                   Base.getVRQualifiers());
1558 }
1559 
1560 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1561   bool isNonGC = false;
1562   Expr *BaseExpr = E->getBase();
1563   llvm::Value *BaseValue = NULL;
1564   Qualifiers BaseQuals;
1565 
1566   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1567   if (E->isArrow()) {
1568     BaseValue = EmitScalarExpr(BaseExpr);
1569     const PointerType *PTy =
1570       BaseExpr->getType()->getAs<PointerType>();
1571     BaseQuals = PTy->getPointeeType().getQualifiers();
1572   } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) ||
1573              isa<ObjCImplicitSetterGetterRefExpr>(
1574                BaseExpr->IgnoreParens())) {
1575     RValue RV = EmitObjCPropertyGet(BaseExpr);
1576     BaseValue = RV.getAggregateAddr();
1577     BaseQuals = BaseExpr->getType().getQualifiers();
1578   } else {
1579     LValue BaseLV = EmitLValue(BaseExpr);
1580     if (BaseLV.isNonGC())
1581       isNonGC = true;
1582     // FIXME: this isn't right for bitfields.
1583     BaseValue = BaseLV.getAddress();
1584     QualType BaseTy = BaseExpr->getType();
1585     BaseQuals = BaseTy.getQualifiers();
1586   }
1587 
1588   NamedDecl *ND = E->getMemberDecl();
1589   if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
1590     LValue LV = EmitLValueForField(BaseValue, Field,
1591                                    BaseQuals.getCVRQualifiers());
1592     LV.setNonGC(isNonGC);
1593     setObjCGCLValueClass(getContext(), E, LV);
1594     return LV;
1595   }
1596 
1597   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
1598     return EmitGlobalVarDeclLValue(*this, E, VD);
1599 
1600   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1601     return EmitFunctionDeclLValue(*this, E, FD);
1602 
1603   assert(false && "Unhandled member declaration!");
1604   return LValue();
1605 }
1606 
1607 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue,
1608                                               const FieldDecl *Field,
1609                                               unsigned CVRQualifiers) {
1610   const CGRecordLayout &RL =
1611     CGM.getTypes().getCGRecordLayout(Field->getParent());
1612   const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
1613   return LValue::MakeBitfield(BaseValue, Info,
1614                              Field->getType().getCVRQualifiers()|CVRQualifiers);
1615 }
1616 
1617 /// EmitLValueForAnonRecordField - Given that the field is a member of
1618 /// an anonymous struct or union buried inside a record, and given
1619 /// that the base value is a pointer to the enclosing record, derive
1620 /// an lvalue for the ultimate field.
1621 LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
1622                                                      const FieldDecl *Field,
1623                                                      unsigned CVRQualifiers) {
1624   llvm::SmallVector<const FieldDecl *, 8> Path;
1625   Path.push_back(Field);
1626 
1627   while (Field->getParent()->isAnonymousStructOrUnion()) {
1628     const ValueDecl *VD = Field->getParent()->getAnonymousStructOrUnionObject();
1629     if (!isa<FieldDecl>(VD)) break;
1630     Field = cast<FieldDecl>(VD);
1631     Path.push_back(Field);
1632   }
1633 
1634   llvm::SmallVectorImpl<const FieldDecl*>::reverse_iterator
1635     I = Path.rbegin(), E = Path.rend();
1636   while (true) {
1637     LValue LV = EmitLValueForField(BaseValue, *I, CVRQualifiers);
1638     if (++I == E) return LV;
1639 
1640     assert(LV.isSimple());
1641     BaseValue = LV.getAddress();
1642     CVRQualifiers |= LV.getVRQualifiers();
1643   }
1644 }
1645 
1646 LValue CodeGenFunction::EmitLValueForField(llvm::Value *BaseValue,
1647                                            const FieldDecl *Field,
1648                                            unsigned CVRQualifiers) {
1649   if (Field->isBitField())
1650     return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers);
1651 
1652   const CGRecordLayout &RL =
1653     CGM.getTypes().getCGRecordLayout(Field->getParent());
1654   unsigned idx = RL.getLLVMFieldNo(Field);
1655   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1656 
1657   // Match union field type.
1658   if (Field->getParent()->isUnion()) {
1659     const llvm::Type *FieldTy =
1660       CGM.getTypes().ConvertTypeForMem(Field->getType());
1661     const llvm::PointerType *BaseTy =
1662       cast<llvm::PointerType>(BaseValue->getType());
1663     unsigned AS = BaseTy->getAddressSpace();
1664     V = Builder.CreateBitCast(V,
1665                               llvm::PointerType::get(FieldTy, AS),
1666                               "tmp");
1667   }
1668   if (Field->getType()->isReferenceType())
1669     V = Builder.CreateLoad(V, "tmp");
1670 
1671   unsigned Alignment = getContext().getDeclAlign(Field).getQuantity();
1672   LValue LV = MakeAddrLValue(V, Field->getType(), Alignment);
1673   LV.getQuals().addCVRQualifiers(CVRQualifiers);
1674 
1675   // __weak attribute on a field is ignored.
1676   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
1677     LV.getQuals().removeObjCGCAttr();
1678 
1679   return LV;
1680 }
1681 
1682 LValue
1683 CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value *BaseValue,
1684                                                   const FieldDecl *Field,
1685                                                   unsigned CVRQualifiers) {
1686   QualType FieldType = Field->getType();
1687 
1688   if (!FieldType->isReferenceType())
1689     return EmitLValueForField(BaseValue, Field, CVRQualifiers);
1690 
1691   const CGRecordLayout &RL =
1692     CGM.getTypes().getCGRecordLayout(Field->getParent());
1693   unsigned idx = RL.getLLVMFieldNo(Field);
1694   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1695 
1696   assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1697 
1698   unsigned Alignment = getContext().getDeclAlign(Field).getQuantity();
1699   return MakeAddrLValue(V, FieldType, Alignment);
1700 }
1701 
1702 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
1703   llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
1704   const Expr *InitExpr = E->getInitializer();
1705   LValue Result = MakeAddrLValue(DeclPtr, E->getType());
1706 
1707   EmitAnyExprToMem(InitExpr, DeclPtr, /*Volatile*/ false, /*Init*/ true);
1708 
1709   return Result;
1710 }
1711 
1712 LValue
1713 CodeGenFunction::EmitConditionalOperatorLValue(const ConditionalOperator *E) {
1714   if (E->isGLValue()) {
1715     if (int Cond = ConstantFoldsToSimpleInteger(E->getCond())) {
1716       Expr *Live = Cond == 1 ? E->getLHS() : E->getRHS();
1717       if (Live)
1718         return EmitLValue(Live);
1719     }
1720 
1721     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1722     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1723     llvm::BasicBlock *ContBlock = createBasicBlock("cond.end");
1724 
1725     if (E->getLHS())
1726       EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1727     else {
1728       Expr *save = E->getSAVE();
1729       assert(save && "VisitConditionalOperator - save is null");
1730       // Intentianlly not doing direct assignment to ConditionalSaveExprs[save]
1731       LValue SaveVal = EmitLValue(save);
1732       ConditionalSaveLValueExprs[save] = SaveVal;
1733       EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1734     }
1735 
1736     // Any temporaries created here are conditional.
1737     BeginConditionalBranch();
1738     EmitBlock(LHSBlock);
1739     LValue LHS = EmitLValue(E->getTrueExpr());
1740 
1741     EndConditionalBranch();
1742 
1743     if (!LHS.isSimple())
1744       return EmitUnsupportedLValue(E, "conditional operator");
1745 
1746     // FIXME: We shouldn't need an alloca for this.
1747     llvm::Value *Temp = CreateTempAlloca(LHS.getAddress()->getType(),"condtmp");
1748     Builder.CreateStore(LHS.getAddress(), Temp);
1749     EmitBranch(ContBlock);
1750 
1751     // Any temporaries created here are conditional.
1752     BeginConditionalBranch();
1753     EmitBlock(RHSBlock);
1754     LValue RHS = EmitLValue(E->getRHS());
1755     EndConditionalBranch();
1756     if (!RHS.isSimple())
1757       return EmitUnsupportedLValue(E, "conditional operator");
1758 
1759     Builder.CreateStore(RHS.getAddress(), Temp);
1760     EmitBranch(ContBlock);
1761 
1762     EmitBlock(ContBlock);
1763 
1764     Temp = Builder.CreateLoad(Temp, "lv");
1765     return MakeAddrLValue(Temp, E->getType());
1766   }
1767 
1768   // ?: here should be an aggregate.
1769   assert((hasAggregateLLVMType(E->getType()) &&
1770           !E->getType()->isAnyComplexType()) &&
1771          "Unexpected conditional operator!");
1772 
1773   return EmitAggExprToLValue(E);
1774 }
1775 
1776 /// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast.
1777 /// If the cast is a dynamic_cast, we can have the usual lvalue result,
1778 /// otherwise if a cast is needed by the code generator in an lvalue context,
1779 /// then it must mean that we need the address of an aggregate in order to
1780 /// access one of its fields.  This can happen for all the reasons that casts
1781 /// are permitted with aggregate result, including noop aggregate casts, and
1782 /// cast from scalar to union.
1783 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1784   switch (E->getCastKind()) {
1785   case CK_ToVoid:
1786     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
1787 
1788   case CK_Dependent:
1789     llvm_unreachable("dependent cast kind in IR gen!");
1790 
1791   case CK_NoOp:
1792     if (E->getSubExpr()->Classify(getContext()).getKind()
1793                                           != Expr::Classification::CL_PRValue) {
1794       LValue LV = EmitLValue(E->getSubExpr());
1795       if (LV.isPropertyRef() || LV.isKVCRef()) {
1796         QualType QT = E->getSubExpr()->getType();
1797         RValue RV =
1798           LV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(LV, QT)
1799                              : EmitLoadOfKVCRefLValue(LV, QT);
1800         assert(!RV.isScalar() && "EmitCastLValue-scalar cast of property ref");
1801         llvm::Value *V = RV.getAggregateAddr();
1802         return MakeAddrLValue(V, QT);
1803       }
1804       return LV;
1805     }
1806     // Fall through to synthesize a temporary.
1807 
1808   case CK_BitCast:
1809   case CK_ArrayToPointerDecay:
1810   case CK_FunctionToPointerDecay:
1811   case CK_NullToMemberPointer:
1812   case CK_NullToPointer:
1813   case CK_IntegralToPointer:
1814   case CK_PointerToIntegral:
1815   case CK_PointerToBoolean:
1816   case CK_VectorSplat:
1817   case CK_IntegralCast:
1818   case CK_IntegralToBoolean:
1819   case CK_IntegralToFloating:
1820   case CK_FloatingToIntegral:
1821   case CK_FloatingToBoolean:
1822   case CK_FloatingCast:
1823   case CK_FloatingRealToComplex:
1824   case CK_FloatingComplexToReal:
1825   case CK_FloatingComplexToBoolean:
1826   case CK_FloatingComplexCast:
1827   case CK_FloatingComplexToIntegralComplex:
1828   case CK_IntegralRealToComplex:
1829   case CK_IntegralComplexToReal:
1830   case CK_IntegralComplexToBoolean:
1831   case CK_IntegralComplexCast:
1832   case CK_IntegralComplexToFloatingComplex:
1833   case CK_DerivedToBaseMemberPointer:
1834   case CK_BaseToDerivedMemberPointer:
1835   case CK_MemberPointerToBoolean:
1836   case CK_AnyPointerToBlockPointerCast: {
1837     // These casts only produce lvalues when we're binding a reference to a
1838     // temporary realized from a (converted) pure rvalue. Emit the expression
1839     // as a value, copy it into a temporary, and return an lvalue referring to
1840     // that temporary.
1841     llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
1842     EmitAnyExprToMem(E, V, false, false);
1843     return MakeAddrLValue(V, E->getType());
1844   }
1845 
1846   case CK_Dynamic: {
1847     LValue LV = EmitLValue(E->getSubExpr());
1848     llvm::Value *V = LV.getAddress();
1849     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
1850     return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
1851   }
1852 
1853   case CK_ConstructorConversion:
1854   case CK_UserDefinedConversion:
1855   case CK_AnyPointerToObjCPointerCast:
1856     return EmitLValue(E->getSubExpr());
1857 
1858   case CK_UncheckedDerivedToBase:
1859   case CK_DerivedToBase: {
1860     const RecordType *DerivedClassTy =
1861       E->getSubExpr()->getType()->getAs<RecordType>();
1862     CXXRecordDecl *DerivedClassDecl =
1863       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1864 
1865     LValue LV = EmitLValue(E->getSubExpr());
1866     llvm::Value *This;
1867     if (LV.isPropertyRef() || LV.isKVCRef()) {
1868       QualType QT = E->getSubExpr()->getType();
1869       RValue RV =
1870         LV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(LV, QT)
1871                            : EmitLoadOfKVCRefLValue(LV, QT);
1872       assert (!RV.isScalar() && "EmitCastLValue");
1873       This = RV.getAggregateAddr();
1874     }
1875     else
1876       This = LV.getAddress();
1877 
1878     // Perform the derived-to-base conversion
1879     llvm::Value *Base =
1880       GetAddressOfBaseClass(This, DerivedClassDecl,
1881                             E->path_begin(), E->path_end(),
1882                             /*NullCheckValue=*/false);
1883 
1884     return MakeAddrLValue(Base, E->getType());
1885   }
1886   case CK_ToUnion:
1887     return EmitAggExprToLValue(E);
1888   case CK_BaseToDerived: {
1889     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
1890     CXXRecordDecl *DerivedClassDecl =
1891       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1892 
1893     LValue LV = EmitLValue(E->getSubExpr());
1894 
1895     // Perform the base-to-derived conversion
1896     llvm::Value *Derived =
1897       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
1898                                E->path_begin(), E->path_end(),
1899                                /*NullCheckValue=*/false);
1900 
1901     return MakeAddrLValue(Derived, E->getType());
1902   }
1903   case CK_LValueBitCast: {
1904     // This must be a reinterpret_cast (or c-style equivalent).
1905     const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
1906 
1907     LValue LV = EmitLValue(E->getSubExpr());
1908     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1909                                            ConvertType(CE->getTypeAsWritten()));
1910     return MakeAddrLValue(V, E->getType());
1911   }
1912   case CK_ObjCObjectLValueCast: {
1913     LValue LV = EmitLValue(E->getSubExpr());
1914     QualType ToType = getContext().getLValueReferenceType(E->getType());
1915     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1916                                            ConvertType(ToType));
1917     return MakeAddrLValue(V, E->getType());
1918   }
1919   }
1920 
1921   llvm_unreachable("Unhandled lvalue cast kind?");
1922 }
1923 
1924 LValue CodeGenFunction::EmitNullInitializationLValue(
1925                                               const CXXScalarValueInitExpr *E) {
1926   QualType Ty = E->getType();
1927   LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
1928   EmitNullInitialization(LV.getAddress(), Ty);
1929   return LV;
1930 }
1931 
1932 //===--------------------------------------------------------------------===//
1933 //                             Expression Emission
1934 //===--------------------------------------------------------------------===//
1935 
1936 
1937 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
1938                                      ReturnValueSlot ReturnValue) {
1939   // Builtins never have block type.
1940   if (E->getCallee()->getType()->isBlockPointerType())
1941     return EmitBlockCallExpr(E, ReturnValue);
1942 
1943   if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1944     return EmitCXXMemberCallExpr(CE, ReturnValue);
1945 
1946   const Decl *TargetDecl = 0;
1947   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1948     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1949       TargetDecl = DRE->getDecl();
1950       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1951         if (unsigned builtinID = FD->getBuiltinID())
1952           return EmitBuiltinExpr(FD, builtinID, E);
1953     }
1954   }
1955 
1956   if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1957     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1958       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
1959 
1960   if (isa<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
1961     // C++ [expr.pseudo]p1:
1962     //   The result shall only be used as the operand for the function call
1963     //   operator (), and the result of such a call has type void. The only
1964     //   effect is the evaluation of the postfix-expression before the dot or
1965     //   arrow.
1966     EmitScalarExpr(E->getCallee());
1967     return RValue::get(0);
1968   }
1969 
1970   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
1971   return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
1972                   E->arg_begin(), E->arg_end(), TargetDecl);
1973 }
1974 
1975 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
1976   // Comma expressions just emit their LHS then their RHS as an l-value.
1977   if (E->getOpcode() == BO_Comma) {
1978     EmitAnyExpr(E->getLHS());
1979     EnsureInsertPoint();
1980     return EmitLValue(E->getRHS());
1981   }
1982 
1983   if (E->getOpcode() == BO_PtrMemD ||
1984       E->getOpcode() == BO_PtrMemI)
1985     return EmitPointerToDataMemberBinaryExpr(E);
1986 
1987   assert(E->isAssignmentOp() && "unexpected binary l-value");
1988 
1989   if (!hasAggregateLLVMType(E->getType())) {
1990     if (E->isCompoundAssignmentOp())
1991       return EmitCompoundAssignOperatorLValue(cast<CompoundAssignOperator>(E));
1992 
1993     assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
1994 
1995     // Emit the LHS as an l-value.
1996     LValue LV = EmitLValue(E->getLHS());
1997     // Store the value through the l-value.
1998     EmitStoreThroughLValue(EmitAnyExpr(E->getRHS()), LV, E->getType());
1999     return LV;
2000   }
2001 
2002   if (E->getType()->isAnyComplexType())
2003     return EmitComplexAssignmentLValue(E);
2004 
2005   // The compound assignment operators are not used for aggregates.
2006   assert(E->getOpcode() == BO_Assign && "aggregate compound assignment?");
2007 
2008   return EmitAggExprToLValue(E);
2009 }
2010 
2011 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
2012   RValue RV = EmitCallExpr(E);
2013 
2014   if (!RV.isScalar())
2015     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2016 
2017   assert(E->getCallReturnType()->isReferenceType() &&
2018          "Can't have a scalar return unless the return type is a "
2019          "reference type!");
2020 
2021   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2022 }
2023 
2024 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2025   // FIXME: This shouldn't require another copy.
2026   return EmitAggExprToLValue(E);
2027 }
2028 
2029 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
2030   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2031          && "binding l-value to type which needs a temporary");
2032   AggValueSlot Slot = CreateAggTemp(E->getType(), "tmp");
2033   EmitCXXConstructExpr(E, Slot);
2034   return MakeAddrLValue(Slot.getAddr(), E->getType());
2035 }
2036 
2037 LValue
2038 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
2039   return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
2040 }
2041 
2042 LValue
2043 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
2044   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2045   Slot.setLifetimeExternallyManaged();
2046   EmitAggExpr(E->getSubExpr(), Slot);
2047   EmitCXXTemporary(E->getTemporary(), Slot.getAddr());
2048   return MakeAddrLValue(Slot.getAddr(), E->getType());
2049 }
2050 
2051 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
2052   RValue RV = EmitObjCMessageExpr(E);
2053 
2054   if (!RV.isScalar())
2055     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2056 
2057   assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2058          "Can't have a scalar return unless the return type is a "
2059          "reference type!");
2060 
2061   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2062 }
2063 
2064 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2065   llvm::Value *V =
2066     CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
2067   return MakeAddrLValue(V, E->getType());
2068 }
2069 
2070 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2071                                              const ObjCIvarDecl *Ivar) {
2072   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
2073 }
2074 
2075 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2076                                           llvm::Value *BaseValue,
2077                                           const ObjCIvarDecl *Ivar,
2078                                           unsigned CVRQualifiers) {
2079   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
2080                                                    Ivar, CVRQualifiers);
2081 }
2082 
2083 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
2084   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2085   llvm::Value *BaseValue = 0;
2086   const Expr *BaseExpr = E->getBase();
2087   Qualifiers BaseQuals;
2088   QualType ObjectTy;
2089   if (E->isArrow()) {
2090     BaseValue = EmitScalarExpr(BaseExpr);
2091     ObjectTy = BaseExpr->getType()->getPointeeType();
2092     BaseQuals = ObjectTy.getQualifiers();
2093   } else {
2094     LValue BaseLV = EmitLValue(BaseExpr);
2095     // FIXME: this isn't right for bitfields.
2096     BaseValue = BaseLV.getAddress();
2097     ObjectTy = BaseExpr->getType();
2098     BaseQuals = ObjectTy.getQualifiers();
2099   }
2100 
2101   LValue LV =
2102     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2103                       BaseQuals.getCVRQualifiers());
2104   setObjCGCLValueClass(getContext(), E, LV);
2105   return LV;
2106 }
2107 
2108 LValue
2109 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
2110   // This is a special l-value that just issues sends when we load or store
2111   // through it.
2112   return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
2113 }
2114 
2115 LValue CodeGenFunction::EmitObjCKVCRefLValue(
2116                                 const ObjCImplicitSetterGetterRefExpr *E) {
2117   // This is a special l-value that just issues sends when we load or store
2118   // through it.
2119   return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers());
2120 }
2121 
2122 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
2123   // Can only get l-value for message expression returning aggregate type
2124   RValue RV = EmitAnyExprToTemp(E);
2125   return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2126 }
2127 
2128 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
2129                                  ReturnValueSlot ReturnValue,
2130                                  CallExpr::const_arg_iterator ArgBeg,
2131                                  CallExpr::const_arg_iterator ArgEnd,
2132                                  const Decl *TargetDecl) {
2133   // Get the actual function type. The callee type will always be a pointer to
2134   // function type or a block pointer type.
2135   assert(CalleeType->isFunctionPointerType() &&
2136          "Call must have function pointer type!");
2137 
2138   CalleeType = getContext().getCanonicalType(CalleeType);
2139 
2140   const FunctionType *FnType
2141     = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
2142   QualType ResultType = FnType->getResultType();
2143 
2144   CallArgList Args;
2145   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
2146 
2147   return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType),
2148                   Callee, ReturnValue, Args, TargetDecl);
2149 }
2150 
2151 LValue CodeGenFunction::
2152 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
2153   llvm::Value *BaseV;
2154   if (E->getOpcode() == BO_PtrMemI)
2155     BaseV = EmitScalarExpr(E->getLHS());
2156   else
2157     BaseV = EmitLValue(E->getLHS()).getAddress();
2158 
2159   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2160 
2161   const MemberPointerType *MPT
2162     = E->getRHS()->getType()->getAs<MemberPointerType>();
2163 
2164   llvm::Value *AddV =
2165     CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2166 
2167   return MakeAddrLValue(AddV, MPT->getPointeeType());
2168 }
2169 
2170