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