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