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