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