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 "CGCXXABI.h"
16 #include "CGCall.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "CGRecordLayout.h"
20 #include "CodeGenModule.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/ADT/Hashing.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/Support/ConvertUTF.h"
31 
32 using namespace clang;
33 using namespace CodeGen;
34 
35 //===--------------------------------------------------------------------===//
36 //                        Miscellaneous Helper Methods
37 //===--------------------------------------------------------------------===//
38 
39 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
40   unsigned addressSpace =
41     cast<llvm::PointerType>(value->getType())->getAddressSpace();
42 
43   llvm::PointerType *destType = Int8PtrTy;
44   if (addressSpace)
45     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
46 
47   if (value->getType() == destType) return value;
48   return Builder.CreateBitCast(value, destType);
49 }
50 
51 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
52 /// block.
53 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
54                                                     const Twine &Name) {
55   if (!Builder.isNamePreserving())
56     return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
57   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
58 }
59 
60 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
61                                      llvm::Value *Init) {
62   llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
63   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
64   Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
65 }
66 
67 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
68                                                 const Twine &Name) {
69   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
70   // FIXME: Should we prefer the preferred type alignment here?
71   CharUnits Align = getContext().getTypeAlignInChars(Ty);
72   Alloc->setAlignment(Align.getQuantity());
73   return Alloc;
74 }
75 
76 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
77                                                  const Twine &Name) {
78   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
79   // FIXME: Should we prefer the preferred type alignment here?
80   CharUnits Align = getContext().getTypeAlignInChars(Ty);
81   Alloc->setAlignment(Align.getQuantity());
82   return Alloc;
83 }
84 
85 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
86 /// expression and compare the result against zero, returning an Int1Ty value.
87 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
88   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
89     llvm::Value *MemPtr = EmitScalarExpr(E);
90     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
91   }
92 
93   QualType BoolTy = getContext().BoolTy;
94   if (!E->getType()->isAnyComplexType())
95     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
96 
97   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
98 }
99 
100 /// EmitIgnoredExpr - Emit code to compute the specified expression,
101 /// ignoring the result.
102 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
103   if (E->isRValue())
104     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
105 
106   // Just emit it as an l-value and drop the result.
107   EmitLValue(E);
108 }
109 
110 /// EmitAnyExpr - Emit code to compute the specified expression which
111 /// can have any type.  The result is returned as an RValue struct.
112 /// If this is an aggregate expression, AggSlot indicates where the
113 /// result should be returned.
114 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
115                                     AggValueSlot aggSlot,
116                                     bool ignoreResult) {
117   if (!hasAggregateLLVMType(E->getType()))
118     return RValue::get(EmitScalarExpr(E, ignoreResult));
119   else if (E->getType()->isAnyComplexType())
120     return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
121 
122   if (!ignoreResult && aggSlot.isIgnored())
123     aggSlot = CreateAggTemp(E->getType(), "agg-temp");
124   EmitAggExpr(E, aggSlot);
125   return aggSlot.asRValue();
126 }
127 
128 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
129 /// always be accessible even if no aggregate location is provided.
130 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
131   AggValueSlot AggSlot = AggValueSlot::ignored();
132 
133   if (hasAggregateLLVMType(E->getType()) &&
134       !E->getType()->isAnyComplexType())
135     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
136   return EmitAnyExpr(E, AggSlot);
137 }
138 
139 /// EmitAnyExprToMem - Evaluate an expression into a given memory
140 /// location.
141 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
142                                        llvm::Value *Location,
143                                        Qualifiers Quals,
144                                        bool IsInit) {
145   // FIXME: This function should take an LValue as an argument.
146   if (E->getType()->isAnyComplexType()) {
147     EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
148   } else if (hasAggregateLLVMType(E->getType())) {
149     CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
150     EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
151                                          AggValueSlot::IsDestructed_t(IsInit),
152                                          AggValueSlot::DoesNotNeedGCBarriers,
153                                          AggValueSlot::IsAliased_t(!IsInit)));
154   } else {
155     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
156     LValue LV = MakeAddrLValue(Location, E->getType());
157     EmitStoreThroughLValue(RV, LV);
158   }
159 }
160 
161 static llvm::Value *
162 CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
163                          const NamedDecl *InitializedDecl) {
164   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
165     if (VD->hasGlobalStorage()) {
166       SmallString<256> Name;
167       llvm::raw_svector_ostream Out(Name);
168       CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
169       Out.flush();
170 
171       llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
172 
173       // Create the reference temporary.
174       llvm::GlobalValue *RefTemp =
175         new llvm::GlobalVariable(CGF.CGM.getModule(),
176                                  RefTempTy, /*isConstant=*/false,
177                                  llvm::GlobalValue::InternalLinkage,
178                                  llvm::Constant::getNullValue(RefTempTy),
179                                  Name.str());
180       return RefTemp;
181     }
182   }
183 
184   return CGF.CreateMemTemp(Type, "ref.tmp");
185 }
186 
187 static llvm::Value *
188 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
189                             llvm::Value *&ReferenceTemporary,
190                             const CXXDestructorDecl *&ReferenceTemporaryDtor,
191                             QualType &ObjCARCReferenceLifetimeType,
192                             const NamedDecl *InitializedDecl) {
193   const MaterializeTemporaryExpr *M = NULL;
194   E = E->findMaterializedTemporary(M);
195   // Objective-C++ ARC:
196   //   If we are binding a reference to a temporary that has ownership, we
197   //   need to perform retain/release operations on the temporary.
198   if (M && CGF.getLangOpts().ObjCAutoRefCount &&
199       M->getType()->isObjCLifetimeType() &&
200       (M->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
201        M->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
202        M->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
203     ObjCARCReferenceLifetimeType = M->getType();
204 
205   if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) {
206     CGF.enterFullExpression(EWC);
207     CodeGenFunction::RunCleanupsScope Scope(CGF);
208 
209     return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
210                                        ReferenceTemporary,
211                                        ReferenceTemporaryDtor,
212                                        ObjCARCReferenceLifetimeType,
213                                        InitializedDecl);
214   }
215 
216   RValue RV;
217   if (E->isGLValue()) {
218     // Emit the expression as an lvalue.
219     LValue LV = CGF.EmitLValue(E);
220 
221     if (LV.isSimple())
222       return LV.getAddress();
223 
224     // We have to load the lvalue.
225     RV = CGF.EmitLoadOfLValue(LV);
226   } else {
227     if (!ObjCARCReferenceLifetimeType.isNull()) {
228       ReferenceTemporary = CreateReferenceTemporary(CGF,
229                                                   ObjCARCReferenceLifetimeType,
230                                                     InitializedDecl);
231 
232 
233       LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
234                                              ObjCARCReferenceLifetimeType);
235 
236       CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
237                          RefTempDst, false);
238 
239       bool ExtendsLifeOfTemporary = false;
240       if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
241         if (Var->extendsLifetimeOfTemporary())
242           ExtendsLifeOfTemporary = true;
243       } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
244         ExtendsLifeOfTemporary = true;
245       }
246 
247       if (!ExtendsLifeOfTemporary) {
248         // Since the lifetime of this temporary isn't going to be extended,
249         // we need to clean it up ourselves at the end of the full expression.
250         switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
251         case Qualifiers::OCL_None:
252         case Qualifiers::OCL_ExplicitNone:
253         case Qualifiers::OCL_Autoreleasing:
254           break;
255 
256         case Qualifiers::OCL_Strong: {
257           assert(!ObjCARCReferenceLifetimeType->isArrayType());
258           CleanupKind cleanupKind = CGF.getARCCleanupKind();
259           CGF.pushDestroy(cleanupKind,
260                           ReferenceTemporary,
261                           ObjCARCReferenceLifetimeType,
262                           CodeGenFunction::destroyARCStrongImprecise,
263                           cleanupKind & EHCleanup);
264           break;
265         }
266 
267         case Qualifiers::OCL_Weak:
268           assert(!ObjCARCReferenceLifetimeType->isArrayType());
269           CGF.pushDestroy(NormalAndEHCleanup,
270                           ReferenceTemporary,
271                           ObjCARCReferenceLifetimeType,
272                           CodeGenFunction::destroyARCWeak,
273                           /*useEHCleanupForArray*/ true);
274           break;
275         }
276 
277         ObjCARCReferenceLifetimeType = QualType();
278       }
279 
280       return ReferenceTemporary;
281     }
282 
283     SmallVector<SubobjectAdjustment, 2> Adjustments;
284     E = E->skipRValueSubobjectAdjustments(Adjustments);
285     if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
286       if (opaque->getType()->isRecordType())
287         return CGF.EmitOpaqueValueLValue(opaque).getAddress();
288 
289     // Create a reference temporary if necessary.
290     AggValueSlot AggSlot = AggValueSlot::ignored();
291     if (CGF.hasAggregateLLVMType(E->getType()) &&
292         !E->getType()->isAnyComplexType()) {
293       ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
294                                                     InitializedDecl);
295       CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
296       AggValueSlot::IsDestructed_t isDestructed
297         = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
298       AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
299                                       Qualifiers(), isDestructed,
300                                       AggValueSlot::DoesNotNeedGCBarriers,
301                                       AggValueSlot::IsNotAliased);
302     }
303 
304     if (InitializedDecl) {
305       // Get the destructor for the reference temporary.
306       if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
307         CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
308         if (!ClassDecl->hasTrivialDestructor())
309           ReferenceTemporaryDtor = ClassDecl->getDestructor();
310       }
311     }
312 
313     RV = CGF.EmitAnyExpr(E, AggSlot);
314 
315     // Check if need to perform derived-to-base casts and/or field accesses, to
316     // get from the temporary object we created (and, potentially, for which we
317     // extended the lifetime) to the subobject we're binding the reference to.
318     if (!Adjustments.empty()) {
319       llvm::Value *Object = RV.getAggregateAddr();
320       for (unsigned I = Adjustments.size(); I != 0; --I) {
321         SubobjectAdjustment &Adjustment = Adjustments[I-1];
322         switch (Adjustment.Kind) {
323         case SubobjectAdjustment::DerivedToBaseAdjustment:
324           Object =
325               CGF.GetAddressOfBaseClass(Object,
326                                         Adjustment.DerivedToBase.DerivedClass,
327                               Adjustment.DerivedToBase.BasePath->path_begin(),
328                               Adjustment.DerivedToBase.BasePath->path_end(),
329                                         /*NullCheckValue=*/false);
330           break;
331 
332         case SubobjectAdjustment::FieldAdjustment: {
333           LValue LV = CGF.MakeAddrLValue(Object, E->getType());
334           LV = CGF.EmitLValueForField(LV, Adjustment.Field);
335           if (LV.isSimple()) {
336             Object = LV.getAddress();
337             break;
338           }
339 
340           // For non-simple lvalues, we actually have to create a copy of
341           // the object we're binding to.
342           QualType T = Adjustment.Field->getType().getNonReferenceType()
343                                                   .getUnqualifiedType();
344           Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
345           LValue TempLV = CGF.MakeAddrLValue(Object,
346                                              Adjustment.Field->getType());
347           CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
348           break;
349         }
350 
351         case SubobjectAdjustment::MemberPointerAdjustment: {
352           llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS);
353           Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
354                         CGF, Object, Ptr, Adjustment.Ptr.MPT);
355           break;
356         }
357         }
358       }
359 
360       return Object;
361     }
362   }
363 
364   if (RV.isAggregate())
365     return RV.getAggregateAddr();
366 
367   // Create a temporary variable that we can bind the reference to.
368   ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
369                                                 InitializedDecl);
370 
371 
372   unsigned Alignment =
373     CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
374   if (RV.isScalar())
375     CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
376                           /*Volatile=*/false, Alignment, E->getType());
377   else
378     CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
379                            /*Volatile=*/false);
380   return ReferenceTemporary;
381 }
382 
383 RValue
384 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
385                                             const NamedDecl *InitializedDecl) {
386   llvm::Value *ReferenceTemporary = 0;
387   const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
388   QualType ObjCARCReferenceLifetimeType;
389   llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
390                                                    ReferenceTemporaryDtor,
391                                                    ObjCARCReferenceLifetimeType,
392                                                    InitializedDecl);
393   if (SanitizePerformTypeCheck && !E->getType()->isFunctionType()) {
394     // C++11 [dcl.ref]p5 (as amended by core issue 453):
395     //   If a glvalue to which a reference is directly bound designates neither
396     //   an existing object or function of an appropriate type nor a region of
397     //   storage of suitable size and alignment to contain an object of the
398     //   reference's type, the behavior is undefined.
399     QualType Ty = E->getType();
400     EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
401   }
402   if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
403     return RValue::get(Value);
404 
405   // Make sure to call the destructor for the reference temporary.
406   const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
407   if (VD && VD->hasGlobalStorage()) {
408     if (ReferenceTemporaryDtor) {
409       llvm::Constant *DtorFn =
410         CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
411       CGM.getCXXABI().registerGlobalDtor(*this, DtorFn,
412                                     cast<llvm::Constant>(ReferenceTemporary));
413     } else {
414       assert(!ObjCARCReferenceLifetimeType.isNull());
415       // Note: We intentionally do not register a global "destructor" to
416       // release the object.
417     }
418 
419     return RValue::get(Value);
420   }
421 
422   if (ReferenceTemporaryDtor)
423     PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
424   else {
425     switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
426     case Qualifiers::OCL_None:
427       llvm_unreachable(
428                       "Not a reference temporary that needs to be deallocated");
429     case Qualifiers::OCL_ExplicitNone:
430     case Qualifiers::OCL_Autoreleasing:
431       // Nothing to do.
432       break;
433 
434     case Qualifiers::OCL_Strong: {
435       bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
436       CleanupKind cleanupKind = getARCCleanupKind();
437       pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType,
438                   precise ? destroyARCStrongPrecise : destroyARCStrongImprecise,
439                   cleanupKind & EHCleanup);
440       break;
441     }
442 
443     case Qualifiers::OCL_Weak: {
444       // __weak objects always get EH cleanups; otherwise, exceptions
445       // could cause really nasty crashes instead of mere leaks.
446       pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
447                   ObjCARCReferenceLifetimeType, destroyARCWeak, true);
448       break;
449     }
450     }
451   }
452 
453   return RValue::get(Value);
454 }
455 
456 
457 /// getAccessedFieldNo - Given an encoded value and a result number, return the
458 /// input field number being accessed.
459 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
460                                              const llvm::Constant *Elts) {
461   return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
462       ->getZExtValue();
463 }
464 
465 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
466 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
467                                     llvm::Value *High) {
468   llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
469   llvm::Value *K47 = Builder.getInt64(47);
470   llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
471   llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
472   llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
473   llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
474   return Builder.CreateMul(B1, KMul);
475 }
476 
477 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
478                                     llvm::Value *Address,
479                                     QualType Ty, CharUnits Alignment) {
480   if (!SanitizePerformTypeCheck)
481     return;
482 
483   // Don't check pointers outside the default address space. The null check
484   // isn't correct, the object-size check isn't supported by LLVM, and we can't
485   // communicate the addresses to the runtime handler for the vptr check.
486   if (Address->getType()->getPointerAddressSpace())
487     return;
488 
489   llvm::Value *Cond = 0;
490 
491   if (SanOpts->Null) {
492     // The glvalue must not be an empty glvalue.
493     Cond = Builder.CreateICmpNE(
494         Address, llvm::Constant::getNullValue(Address->getType()));
495   }
496 
497   if (SanOpts->ObjectSize && !Ty->isIncompleteType()) {
498     uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
499 
500     // The glvalue must refer to a large enough storage region.
501     // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
502     //        to check this.
503     llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy);
504     llvm::Value *Min = Builder.getFalse();
505     llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
506     llvm::Value *LargeEnough =
507         Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min),
508                               llvm::ConstantInt::get(IntPtrTy, Size));
509     Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough;
510   }
511 
512   uint64_t AlignVal = 0;
513 
514   if (SanOpts->Alignment) {
515     AlignVal = Alignment.getQuantity();
516     if (!Ty->isIncompleteType() && !AlignVal)
517       AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
518 
519     // The glvalue must be suitably aligned.
520     if (AlignVal) {
521       llvm::Value *Align =
522           Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
523                             llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
524       llvm::Value *Aligned =
525         Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
526       Cond = Cond ? Builder.CreateAnd(Cond, Aligned) : Aligned;
527     }
528   }
529 
530   if (Cond) {
531     llvm::Constant *StaticData[] = {
532       EmitCheckSourceLocation(Loc),
533       EmitCheckTypeDescriptor(Ty),
534       llvm::ConstantInt::get(SizeTy, AlignVal),
535       llvm::ConstantInt::get(Int8Ty, TCK)
536     };
537     EmitCheck(Cond, "type_mismatch", StaticData, Address, CRK_Recoverable);
538   }
539 
540   // If possible, check that the vptr indicates that there is a subobject of
541   // type Ty at offset zero within this object.
542   //
543   // C++11 [basic.life]p5,6:
544   //   [For storage which does not refer to an object within its lifetime]
545   //   The program has undefined behavior if:
546   //    -- the [pointer or glvalue] is used to access a non-static data member
547   //       or call a non-static member function
548   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
549   if (SanOpts->Vptr &&
550       (TCK == TCK_MemberAccess || TCK == TCK_MemberCall) &&
551       RD && RD->hasDefinition() && RD->isDynamicClass()) {
552     // Compute a hash of the mangled name of the type.
553     //
554     // FIXME: This is not guaranteed to be deterministic! Move to a
555     //        fingerprinting mechanism once LLVM provides one. For the time
556     //        being the implementation happens to be deterministic.
557     SmallString<64> MangledName;
558     llvm::raw_svector_ostream Out(MangledName);
559     CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
560                                                      Out);
561     llvm::hash_code TypeHash = hash_value(Out.str());
562 
563     // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
564     llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
565     llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
566     llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
567     llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
568     llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
569 
570     llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
571     Hash = Builder.CreateTrunc(Hash, IntPtrTy);
572 
573     // Look the hash up in our cache.
574     const int CacheSize = 128;
575     llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
576     llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
577                                                    "__ubsan_vptr_type_cache");
578     llvm::Value *Slot = Builder.CreateAnd(Hash,
579                                           llvm::ConstantInt::get(IntPtrTy,
580                                                                  CacheSize-1));
581     llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
582     llvm::Value *CacheVal =
583       Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
584 
585     // If the hash isn't in the cache, call a runtime handler to perform the
586     // hard work of checking whether the vptr is for an object of the right
587     // type. This will either fill in the cache and return, or produce a
588     // diagnostic.
589     llvm::Constant *StaticData[] = {
590       EmitCheckSourceLocation(Loc),
591       EmitCheckTypeDescriptor(Ty),
592       CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
593       llvm::ConstantInt::get(Int8Ty, TCK)
594     };
595     llvm::Value *DynamicData[] = { Address, Hash };
596     EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash),
597               "dynamic_type_cache_miss", StaticData, DynamicData,
598               CRK_AlwaysRecoverable);
599   }
600 }
601 
602 
603 CodeGenFunction::ComplexPairTy CodeGenFunction::
604 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
605                          bool isInc, bool isPre) {
606   ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
607                                             LV.isVolatileQualified());
608 
609   llvm::Value *NextVal;
610   if (isa<llvm::IntegerType>(InVal.first->getType())) {
611     uint64_t AmountVal = isInc ? 1 : -1;
612     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
613 
614     // Add the inc/dec to the real part.
615     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
616   } else {
617     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
618     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
619     if (!isInc)
620       FVal.changeSign();
621     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
622 
623     // Add the inc/dec to the real part.
624     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
625   }
626 
627   ComplexPairTy IncVal(NextVal, InVal.second);
628 
629   // Store the updated result through the lvalue.
630   StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
631 
632   // If this is a postinc, return the value read from memory, otherwise use the
633   // updated value.
634   return isPre ? IncVal : InVal;
635 }
636 
637 
638 //===----------------------------------------------------------------------===//
639 //                         LValue Expression Emission
640 //===----------------------------------------------------------------------===//
641 
642 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
643   if (Ty->isVoidType())
644     return RValue::get(0);
645 
646   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
647     llvm::Type *EltTy = ConvertType(CTy->getElementType());
648     llvm::Value *U = llvm::UndefValue::get(EltTy);
649     return RValue::getComplex(std::make_pair(U, U));
650   }
651 
652   // If this is a use of an undefined aggregate type, the aggregate must have an
653   // identifiable address.  Just because the contents of the value are undefined
654   // doesn't mean that the address can't be taken and compared.
655   if (hasAggregateLLVMType(Ty)) {
656     llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
657     return RValue::getAggregate(DestPtr);
658   }
659 
660   return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
661 }
662 
663 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
664                                               const char *Name) {
665   ErrorUnsupported(E, Name);
666   return GetUndefRValue(E->getType());
667 }
668 
669 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
670                                               const char *Name) {
671   ErrorUnsupported(E, Name);
672   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
673   return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
674 }
675 
676 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
677   LValue LV = EmitLValue(E);
678   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
679     EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
680                   E->getType(), LV.getAlignment());
681   return LV;
682 }
683 
684 /// EmitLValue - Emit code to compute a designator that specifies the location
685 /// of the expression.
686 ///
687 /// This can return one of two things: a simple address or a bitfield reference.
688 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
689 /// an LLVM pointer type.
690 ///
691 /// If this returns a bitfield reference, nothing about the pointee type of the
692 /// LLVM value is known: For example, it may not be a pointer to an integer.
693 ///
694 /// If this returns a normal address, and if the lvalue's C type is fixed size,
695 /// this method guarantees that the returned pointer type will point to an LLVM
696 /// type of the same size of the lvalue's type.  If the lvalue has a variable
697 /// length type, this is not possible.
698 ///
699 LValue CodeGenFunction::EmitLValue(const Expr *E) {
700   switch (E->getStmtClass()) {
701   default: return EmitUnsupportedLValue(E, "l-value expression");
702 
703   case Expr::ObjCPropertyRefExprClass:
704     llvm_unreachable("cannot emit a property reference directly");
705 
706   case Expr::ObjCSelectorExprClass:
707     return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
708   case Expr::ObjCIsaExprClass:
709     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
710   case Expr::BinaryOperatorClass:
711     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
712   case Expr::CompoundAssignOperatorClass:
713     if (!E->getType()->isAnyComplexType())
714       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
715     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
716   case Expr::CallExprClass:
717   case Expr::CXXMemberCallExprClass:
718   case Expr::CXXOperatorCallExprClass:
719   case Expr::UserDefinedLiteralClass:
720     return EmitCallExprLValue(cast<CallExpr>(E));
721   case Expr::VAArgExprClass:
722     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
723   case Expr::DeclRefExprClass:
724     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
725   case Expr::ParenExprClass:
726     return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
727   case Expr::GenericSelectionExprClass:
728     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
729   case Expr::PredefinedExprClass:
730     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
731   case Expr::StringLiteralClass:
732     return EmitStringLiteralLValue(cast<StringLiteral>(E));
733   case Expr::ObjCEncodeExprClass:
734     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
735   case Expr::PseudoObjectExprClass:
736     return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
737   case Expr::InitListExprClass:
738     return EmitInitListLValue(cast<InitListExpr>(E));
739   case Expr::CXXTemporaryObjectExprClass:
740   case Expr::CXXConstructExprClass:
741     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
742   case Expr::CXXBindTemporaryExprClass:
743     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
744   case Expr::CXXUuidofExprClass:
745     return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
746   case Expr::LambdaExprClass:
747     return EmitLambdaLValue(cast<LambdaExpr>(E));
748 
749   case Expr::ExprWithCleanupsClass: {
750     const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E);
751     enterFullExpression(cleanups);
752     RunCleanupsScope Scope(*this);
753     return EmitLValue(cleanups->getSubExpr());
754   }
755 
756   case Expr::CXXScalarValueInitExprClass:
757     return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
758   case Expr::CXXDefaultArgExprClass:
759     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
760   case Expr::CXXTypeidExprClass:
761     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
762 
763   case Expr::ObjCMessageExprClass:
764     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
765   case Expr::ObjCIvarRefExprClass:
766     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
767   case Expr::StmtExprClass:
768     return EmitStmtExprLValue(cast<StmtExpr>(E));
769   case Expr::UnaryOperatorClass:
770     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
771   case Expr::ArraySubscriptExprClass:
772     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
773   case Expr::ExtVectorElementExprClass:
774     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
775   case Expr::MemberExprClass:
776     return EmitMemberExpr(cast<MemberExpr>(E));
777   case Expr::CompoundLiteralExprClass:
778     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
779   case Expr::ConditionalOperatorClass:
780     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
781   case Expr::BinaryConditionalOperatorClass:
782     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
783   case Expr::ChooseExprClass:
784     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
785   case Expr::OpaqueValueExprClass:
786     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
787   case Expr::SubstNonTypeTemplateParmExprClass:
788     return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
789   case Expr::ImplicitCastExprClass:
790   case Expr::CStyleCastExprClass:
791   case Expr::CXXFunctionalCastExprClass:
792   case Expr::CXXStaticCastExprClass:
793   case Expr::CXXDynamicCastExprClass:
794   case Expr::CXXReinterpretCastExprClass:
795   case Expr::CXXConstCastExprClass:
796   case Expr::ObjCBridgedCastExprClass:
797     return EmitCastLValue(cast<CastExpr>(E));
798 
799   case Expr::MaterializeTemporaryExprClass:
800     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
801   }
802 }
803 
804 /// Given an object of the given canonical type, can we safely copy a
805 /// value out of it based on its initializer?
806 static bool isConstantEmittableObjectType(QualType type) {
807   assert(type.isCanonical());
808   assert(!type->isReferenceType());
809 
810   // Must be const-qualified but non-volatile.
811   Qualifiers qs = type.getLocalQualifiers();
812   if (!qs.hasConst() || qs.hasVolatile()) return false;
813 
814   // Otherwise, all object types satisfy this except C++ classes with
815   // mutable subobjects or non-trivial copy/destroy behavior.
816   if (const RecordType *RT = dyn_cast<RecordType>(type))
817     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
818       if (RD->hasMutableFields() || !RD->isTrivial())
819         return false;
820 
821   return true;
822 }
823 
824 /// Can we constant-emit a load of a reference to a variable of the
825 /// given type?  This is different from predicates like
826 /// Decl::isUsableInConstantExpressions because we do want it to apply
827 /// in situations that don't necessarily satisfy the language's rules
828 /// for this (e.g. C++'s ODR-use rules).  For example, we want to able
829 /// to do this with const float variables even if those variables
830 /// aren't marked 'constexpr'.
831 enum ConstantEmissionKind {
832   CEK_None,
833   CEK_AsReferenceOnly,
834   CEK_AsValueOrReference,
835   CEK_AsValueOnly
836 };
837 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
838   type = type.getCanonicalType();
839   if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) {
840     if (isConstantEmittableObjectType(ref->getPointeeType()))
841       return CEK_AsValueOrReference;
842     return CEK_AsReferenceOnly;
843   }
844   if (isConstantEmittableObjectType(type))
845     return CEK_AsValueOnly;
846   return CEK_None;
847 }
848 
849 /// Try to emit a reference to the given value without producing it as
850 /// an l-value.  This is actually more than an optimization: we can't
851 /// produce an l-value for variables that we never actually captured
852 /// in a block or lambda, which means const int variables or constexpr
853 /// literals or similar.
854 CodeGenFunction::ConstantEmission
855 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
856   ValueDecl *value = refExpr->getDecl();
857 
858   // The value needs to be an enum constant or a constant variable.
859   ConstantEmissionKind CEK;
860   if (isa<ParmVarDecl>(value)) {
861     CEK = CEK_None;
862   } else if (VarDecl *var = dyn_cast<VarDecl>(value)) {
863     CEK = checkVarTypeForConstantEmission(var->getType());
864   } else if (isa<EnumConstantDecl>(value)) {
865     CEK = CEK_AsValueOnly;
866   } else {
867     CEK = CEK_None;
868   }
869   if (CEK == CEK_None) return ConstantEmission();
870 
871   Expr::EvalResult result;
872   bool resultIsReference;
873   QualType resultType;
874 
875   // It's best to evaluate all the way as an r-value if that's permitted.
876   if (CEK != CEK_AsReferenceOnly &&
877       refExpr->EvaluateAsRValue(result, getContext())) {
878     resultIsReference = false;
879     resultType = refExpr->getType();
880 
881   // Otherwise, try to evaluate as an l-value.
882   } else if (CEK != CEK_AsValueOnly &&
883              refExpr->EvaluateAsLValue(result, getContext())) {
884     resultIsReference = true;
885     resultType = value->getType();
886 
887   // Failure.
888   } else {
889     return ConstantEmission();
890   }
891 
892   // In any case, if the initializer has side-effects, abandon ship.
893   if (result.HasSideEffects)
894     return ConstantEmission();
895 
896   // Emit as a constant.
897   llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
898 
899   // Make sure we emit a debug reference to the global variable.
900   // This should probably fire even for
901   if (isa<VarDecl>(value)) {
902     if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
903       EmitDeclRefExprDbgValue(refExpr, C);
904   } else {
905     assert(isa<EnumConstantDecl>(value));
906     EmitDeclRefExprDbgValue(refExpr, C);
907   }
908 
909   // If we emitted a reference constant, we need to dereference that.
910   if (resultIsReference)
911     return ConstantEmission::forReference(C);
912 
913   return ConstantEmission::forValue(C);
914 }
915 
916 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
917   return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
918                           lvalue.getAlignment().getQuantity(),
919                           lvalue.getType(), lvalue.getTBAAInfo());
920 }
921 
922 static bool hasBooleanRepresentation(QualType Ty) {
923   if (Ty->isBooleanType())
924     return true;
925 
926   if (const EnumType *ET = Ty->getAs<EnumType>())
927     return ET->getDecl()->getIntegerType()->isBooleanType();
928 
929   if (const AtomicType *AT = Ty->getAs<AtomicType>())
930     return hasBooleanRepresentation(AT->getValueType());
931 
932   return false;
933 }
934 
935 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
936                             llvm::APInt &Min, llvm::APInt &End,
937                             bool StrictEnums) {
938   const EnumType *ET = Ty->getAs<EnumType>();
939   bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
940                                 ET && !ET->getDecl()->isFixed();
941   bool IsBool = hasBooleanRepresentation(Ty);
942   if (!IsBool && !IsRegularCPlusPlusEnum)
943     return false;
944 
945   if (IsBool) {
946     Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
947     End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
948   } else {
949     const EnumDecl *ED = ET->getDecl();
950     llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
951     unsigned Bitwidth = LTy->getScalarSizeInBits();
952     unsigned NumNegativeBits = ED->getNumNegativeBits();
953     unsigned NumPositiveBits = ED->getNumPositiveBits();
954 
955     if (NumNegativeBits) {
956       unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
957       assert(NumBits <= Bitwidth);
958       End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
959       Min = -End;
960     } else {
961       assert(NumPositiveBits <= Bitwidth);
962       End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
963       Min = llvm::APInt(Bitwidth, 0);
964     }
965   }
966   return true;
967 }
968 
969 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
970   llvm::APInt Min, End;
971   if (!getRangeForType(*this, Ty, Min, End,
972                        CGM.getCodeGenOpts().StrictEnums))
973     return 0;
974 
975   llvm::MDBuilder MDHelper(getLLVMContext());
976   return MDHelper.createRange(Min, End);
977 }
978 
979 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
980                                               unsigned Alignment, QualType Ty,
981                                               llvm::MDNode *TBAAInfo) {
982 
983   // For better performance, handle vector loads differently.
984   if (Ty->isVectorType()) {
985     llvm::Value *V;
986     const llvm::Type *EltTy =
987     cast<llvm::PointerType>(Addr->getType())->getElementType();
988 
989     const llvm::VectorType *VTy = cast<llvm::VectorType>(EltTy);
990 
991     // Handle vectors of size 3, like size 4 for better performance.
992     if (VTy->getNumElements() == 3) {
993 
994       // Bitcast to vec4 type.
995       llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
996                                                          4);
997       llvm::PointerType *ptVec4Ty =
998       llvm::PointerType::get(vec4Ty,
999                              (cast<llvm::PointerType>(
1000                                       Addr->getType()))->getAddressSpace());
1001       llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
1002                                                 "castToVec4");
1003       // Now load value.
1004       llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1005 
1006       // Shuffle vector to get vec3.
1007       llvm::Constant *Mask[] = {
1008         llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
1009         llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
1010         llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
1011       };
1012 
1013       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1014       V = Builder.CreateShuffleVector(LoadVal,
1015                                       llvm::UndefValue::get(vec4Ty),
1016                                       MaskV, "extractVec");
1017       return EmitFromMemory(V, Ty);
1018     }
1019   }
1020 
1021   llvm::LoadInst *Load = Builder.CreateLoad(Addr);
1022   if (Volatile)
1023     Load->setVolatile(true);
1024   if (Alignment)
1025     Load->setAlignment(Alignment);
1026   if (TBAAInfo)
1027     CGM.DecorateInstruction(Load, TBAAInfo);
1028   // If this is an atomic type, all normal reads must be atomic
1029   if (Ty->isAtomicType())
1030     Load->setAtomic(llvm::SequentiallyConsistent);
1031 
1032   if ((SanOpts->Bool && hasBooleanRepresentation(Ty)) ||
1033       (SanOpts->Enum && Ty->getAs<EnumType>())) {
1034     llvm::APInt Min, End;
1035     if (getRangeForType(*this, Ty, Min, End, true)) {
1036       --End;
1037       llvm::Value *Check;
1038       if (!Min)
1039         Check = Builder.CreateICmpULE(
1040           Load, llvm::ConstantInt::get(getLLVMContext(), End));
1041       else {
1042         llvm::Value *Upper = Builder.CreateICmpSLE(
1043           Load, llvm::ConstantInt::get(getLLVMContext(), End));
1044         llvm::Value *Lower = Builder.CreateICmpSGE(
1045           Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1046         Check = Builder.CreateAnd(Upper, Lower);
1047       }
1048       // FIXME: Provide a SourceLocation.
1049       EmitCheck(Check, "load_invalid_value", EmitCheckTypeDescriptor(Ty),
1050                 EmitCheckValue(Load), CRK_Recoverable);
1051     }
1052   } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1053     if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1054       Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1055 
1056   return EmitFromMemory(Load, Ty);
1057 }
1058 
1059 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1060   // Bool has a different representation in memory than in registers.
1061   if (hasBooleanRepresentation(Ty)) {
1062     // This should really always be an i1, but sometimes it's already
1063     // an i8, and it's awkward to track those cases down.
1064     if (Value->getType()->isIntegerTy(1))
1065       return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1066     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1067            "wrong value rep of bool");
1068   }
1069 
1070   return Value;
1071 }
1072 
1073 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1074   // Bool has a different representation in memory than in registers.
1075   if (hasBooleanRepresentation(Ty)) {
1076     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1077            "wrong value rep of bool");
1078     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1079   }
1080 
1081   return Value;
1082 }
1083 
1084 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1085                                         bool Volatile, unsigned Alignment,
1086                                         QualType Ty,
1087                                         llvm::MDNode *TBAAInfo,
1088                                         bool isInit) {
1089 
1090   // Handle vectors differently to get better performance.
1091   if (Ty->isVectorType()) {
1092     llvm::Type *SrcTy = Value->getType();
1093     llvm::VectorType *VecTy = cast<llvm::VectorType>(SrcTy);
1094     // Handle vec3 special.
1095     if (VecTy->getNumElements() == 3) {
1096       llvm::LLVMContext &VMContext = getLLVMContext();
1097 
1098       // Our source is a vec3, do a shuffle vector to make it a vec4.
1099       SmallVector<llvm::Constant*, 4> Mask;
1100       Mask.push_back(llvm::ConstantInt::get(
1101                                             llvm::Type::getInt32Ty(VMContext),
1102                                             0));
1103       Mask.push_back(llvm::ConstantInt::get(
1104                                             llvm::Type::getInt32Ty(VMContext),
1105                                             1));
1106       Mask.push_back(llvm::ConstantInt::get(
1107                                             llvm::Type::getInt32Ty(VMContext),
1108                                             2));
1109       Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
1110 
1111       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1112       Value = Builder.CreateShuffleVector(Value,
1113                                           llvm::UndefValue::get(VecTy),
1114                                           MaskV, "extractVec");
1115       SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1116     }
1117     llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
1118     if (DstPtr->getElementType() != SrcTy) {
1119       llvm::Type *MemTy =
1120       llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1121       Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1122     }
1123   }
1124 
1125   Value = EmitToMemory(Value, Ty);
1126 
1127   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1128   if (Alignment)
1129     Store->setAlignment(Alignment);
1130   if (TBAAInfo)
1131     CGM.DecorateInstruction(Store, TBAAInfo);
1132   if (!isInit && Ty->isAtomicType())
1133     Store->setAtomic(llvm::SequentiallyConsistent);
1134 }
1135 
1136 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1137     bool isInit) {
1138   EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1139                     lvalue.getAlignment().getQuantity(), lvalue.getType(),
1140                     lvalue.getTBAAInfo(), isInit);
1141 }
1142 
1143 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1144 /// method emits the address of the lvalue, then loads the result as an rvalue,
1145 /// returning the rvalue.
1146 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
1147   if (LV.isObjCWeak()) {
1148     // load of a __weak object.
1149     llvm::Value *AddrWeakObj = LV.getAddress();
1150     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1151                                                              AddrWeakObj));
1152   }
1153   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1154     llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1155     Object = EmitObjCConsumeObject(LV.getType(), Object);
1156     return RValue::get(Object);
1157   }
1158 
1159   if (LV.isSimple()) {
1160     assert(!LV.getType()->isFunctionType());
1161 
1162     // Everything needs a load.
1163     return RValue::get(EmitLoadOfScalar(LV));
1164   }
1165 
1166   if (LV.isVectorElt()) {
1167     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1168                                               LV.isVolatileQualified());
1169     Load->setAlignment(LV.getAlignment().getQuantity());
1170     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1171                                                     "vecext"));
1172   }
1173 
1174   // If this is a reference to a subset of the elements of a vector, either
1175   // shuffle the input or extract/insert them as appropriate.
1176   if (LV.isExtVectorElt())
1177     return EmitLoadOfExtVectorElementLValue(LV);
1178 
1179   assert(LV.isBitField() && "Unknown LValue type!");
1180   return EmitLoadOfBitfieldLValue(LV);
1181 }
1182 
1183 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
1184   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1185 
1186   // Get the output type.
1187   llvm::Type *ResLTy = ConvertType(LV.getType());
1188 
1189   llvm::Value *Ptr = LV.getBitFieldAddr();
1190   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),
1191                                         "bf.load");
1192   cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1193 
1194   if (Info.IsSigned) {
1195     assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1196     unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1197     if (HighBits)
1198       Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1199     if (Info.Offset + HighBits)
1200       Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1201   } else {
1202     if (Info.Offset)
1203       Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1204     if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1205       Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1206                                                               Info.Size),
1207                               "bf.clear");
1208   }
1209   Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1210 
1211   return RValue::get(Val);
1212 }
1213 
1214 // If this is a reference to a subset of the elements of a vector, create an
1215 // appropriate shufflevector.
1216 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1217   llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1218                                             LV.isVolatileQualified());
1219   Load->setAlignment(LV.getAlignment().getQuantity());
1220   llvm::Value *Vec = Load;
1221 
1222   const llvm::Constant *Elts = LV.getExtVectorElts();
1223 
1224   // If the result of the expression is a non-vector type, we must be extracting
1225   // a single element.  Just codegen as an extractelement.
1226   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1227   if (!ExprVT) {
1228     unsigned InIdx = getAccessedFieldNo(0, Elts);
1229     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1230     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1231   }
1232 
1233   // Always use shuffle vector to try to retain the original program structure
1234   unsigned NumResultElts = ExprVT->getNumElements();
1235 
1236   SmallVector<llvm::Constant*, 4> Mask;
1237   for (unsigned i = 0; i != NumResultElts; ++i)
1238     Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1239 
1240   llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1241   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1242                                     MaskV);
1243   return RValue::get(Vec);
1244 }
1245 
1246 
1247 
1248 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1249 /// lvalue, where both are guaranteed to the have the same type, and that type
1250 /// is 'Ty'.
1251 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
1252   if (!Dst.isSimple()) {
1253     if (Dst.isVectorElt()) {
1254       // Read/modify/write the vector, inserting the new element.
1255       llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1256                                                 Dst.isVolatileQualified());
1257       Load->setAlignment(Dst.getAlignment().getQuantity());
1258       llvm::Value *Vec = Load;
1259       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1260                                         Dst.getVectorIdx(), "vecins");
1261       llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1262                                                    Dst.isVolatileQualified());
1263       Store->setAlignment(Dst.getAlignment().getQuantity());
1264       return;
1265     }
1266 
1267     // If this is an update of extended vector elements, insert them as
1268     // appropriate.
1269     if (Dst.isExtVectorElt())
1270       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1271 
1272     assert(Dst.isBitField() && "Unknown LValue type");
1273     return EmitStoreThroughBitfieldLValue(Src, Dst);
1274   }
1275 
1276   // There's special magic for assigning into an ARC-qualified l-value.
1277   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1278     switch (Lifetime) {
1279     case Qualifiers::OCL_None:
1280       llvm_unreachable("present but none");
1281 
1282     case Qualifiers::OCL_ExplicitNone:
1283       // nothing special
1284       break;
1285 
1286     case Qualifiers::OCL_Strong:
1287       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1288       return;
1289 
1290     case Qualifiers::OCL_Weak:
1291       EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1292       return;
1293 
1294     case Qualifiers::OCL_Autoreleasing:
1295       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1296                                                      Src.getScalarVal()));
1297       // fall into the normal path
1298       break;
1299     }
1300   }
1301 
1302   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1303     // load of a __weak object.
1304     llvm::Value *LvalueDst = Dst.getAddress();
1305     llvm::Value *src = Src.getScalarVal();
1306      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1307     return;
1308   }
1309 
1310   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1311     // load of a __strong object.
1312     llvm::Value *LvalueDst = Dst.getAddress();
1313     llvm::Value *src = Src.getScalarVal();
1314     if (Dst.isObjCIvar()) {
1315       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1316       llvm::Type *ResultType = ConvertType(getContext().LongTy);
1317       llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
1318       llvm::Value *dst = RHS;
1319       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1320       llvm::Value *LHS =
1321         Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1322       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1323       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1324                                               BytesBetween);
1325     } else if (Dst.isGlobalObjCRef()) {
1326       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1327                                                 Dst.isThreadLocalRef());
1328     }
1329     else
1330       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1331     return;
1332   }
1333 
1334   assert(Src.isScalar() && "Can't emit an agg store with this method");
1335   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1336 }
1337 
1338 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1339                                                      llvm::Value **Result) {
1340   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1341   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1342   llvm::Value *Ptr = Dst.getBitFieldAddr();
1343 
1344   // Get the source value, truncated to the width of the bit-field.
1345   llvm::Value *SrcVal = Src.getScalarVal();
1346 
1347   // Cast the source to the storage type and shift it into place.
1348   SrcVal = Builder.CreateIntCast(SrcVal,
1349                                  Ptr->getType()->getPointerElementType(),
1350                                  /*IsSigned=*/false);
1351   llvm::Value *MaskedVal = SrcVal;
1352 
1353   // See if there are other bits in the bitfield's storage we'll need to load
1354   // and mask together with source before storing.
1355   if (Info.StorageSize != Info.Size) {
1356     assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1357     llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
1358                                           "bf.load");
1359     cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1360 
1361     // Mask the source value as needed.
1362     if (!hasBooleanRepresentation(Dst.getType()))
1363       SrcVal = Builder.CreateAnd(SrcVal,
1364                                  llvm::APInt::getLowBitsSet(Info.StorageSize,
1365                                                             Info.Size),
1366                                  "bf.value");
1367     MaskedVal = SrcVal;
1368     if (Info.Offset)
1369       SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1370 
1371     // Mask out the original value.
1372     Val = Builder.CreateAnd(Val,
1373                             ~llvm::APInt::getBitsSet(Info.StorageSize,
1374                                                      Info.Offset,
1375                                                      Info.Offset + Info.Size),
1376                             "bf.clear");
1377 
1378     // Or together the unchanged values and the source value.
1379     SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1380   } else {
1381     assert(Info.Offset == 0);
1382   }
1383 
1384   // Write the new value back out.
1385   llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr,
1386                                                Dst.isVolatileQualified());
1387   Store->setAlignment(Info.StorageAlignment);
1388 
1389   // Return the new value of the bit-field, if requested.
1390   if (Result) {
1391     llvm::Value *ResultVal = MaskedVal;
1392 
1393     // Sign extend the value if needed.
1394     if (Info.IsSigned) {
1395       assert(Info.Size <= Info.StorageSize);
1396       unsigned HighBits = Info.StorageSize - Info.Size;
1397       if (HighBits) {
1398         ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1399         ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1400       }
1401     }
1402 
1403     ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1404                                       "bf.result.cast");
1405     *Result = EmitFromMemory(ResultVal, Dst.getType());
1406   }
1407 }
1408 
1409 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1410                                                                LValue Dst) {
1411   // This access turns into a read/modify/write of the vector.  Load the input
1412   // value now.
1413   llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1414                                             Dst.isVolatileQualified());
1415   Load->setAlignment(Dst.getAlignment().getQuantity());
1416   llvm::Value *Vec = Load;
1417   const llvm::Constant *Elts = Dst.getExtVectorElts();
1418 
1419   llvm::Value *SrcVal = Src.getScalarVal();
1420 
1421   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1422     unsigned NumSrcElts = VTy->getNumElements();
1423     unsigned NumDstElts =
1424        cast<llvm::VectorType>(Vec->getType())->getNumElements();
1425     if (NumDstElts == NumSrcElts) {
1426       // Use shuffle vector is the src and destination are the same number of
1427       // elements and restore the vector mask since it is on the side it will be
1428       // stored.
1429       SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1430       for (unsigned i = 0; i != NumSrcElts; ++i)
1431         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1432 
1433       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1434       Vec = Builder.CreateShuffleVector(SrcVal,
1435                                         llvm::UndefValue::get(Vec->getType()),
1436                                         MaskV);
1437     } else if (NumDstElts > NumSrcElts) {
1438       // Extended the source vector to the same length and then shuffle it
1439       // into the destination.
1440       // FIXME: since we're shuffling with undef, can we just use the indices
1441       //        into that?  This could be simpler.
1442       SmallVector<llvm::Constant*, 4> ExtMask;
1443       for (unsigned i = 0; i != NumSrcElts; ++i)
1444         ExtMask.push_back(Builder.getInt32(i));
1445       ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1446       llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1447       llvm::Value *ExtSrcVal =
1448         Builder.CreateShuffleVector(SrcVal,
1449                                     llvm::UndefValue::get(SrcVal->getType()),
1450                                     ExtMaskV);
1451       // build identity
1452       SmallVector<llvm::Constant*, 4> Mask;
1453       for (unsigned i = 0; i != NumDstElts; ++i)
1454         Mask.push_back(Builder.getInt32(i));
1455 
1456       // modify when what gets shuffled in
1457       for (unsigned i = 0; i != NumSrcElts; ++i)
1458         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1459       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1460       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1461     } else {
1462       // We should never shorten the vector
1463       llvm_unreachable("unexpected shorten vector length");
1464     }
1465   } else {
1466     // If the Src is a scalar (not a vector) it must be updating one element.
1467     unsigned InIdx = getAccessedFieldNo(0, Elts);
1468     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1469     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1470   }
1471 
1472   llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1473                                                Dst.isVolatileQualified());
1474   Store->setAlignment(Dst.getAlignment().getQuantity());
1475 }
1476 
1477 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
1478 // generating write-barries API. It is currently a global, ivar,
1479 // or neither.
1480 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1481                                  LValue &LV,
1482                                  bool IsMemberAccess=false) {
1483   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1484     return;
1485 
1486   if (isa<ObjCIvarRefExpr>(E)) {
1487     QualType ExpTy = E->getType();
1488     if (IsMemberAccess && ExpTy->isPointerType()) {
1489       // If ivar is a structure pointer, assigning to field of
1490       // this struct follows gcc's behavior and makes it a non-ivar
1491       // writer-barrier conservatively.
1492       ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1493       if (ExpTy->isRecordType()) {
1494         LV.setObjCIvar(false);
1495         return;
1496       }
1497     }
1498     LV.setObjCIvar(true);
1499     ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1500     LV.setBaseIvarExp(Exp->getBase());
1501     LV.setObjCArray(E->getType()->isArrayType());
1502     return;
1503   }
1504 
1505   if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1506     if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1507       if (VD->hasGlobalStorage()) {
1508         LV.setGlobalObjCRef(true);
1509         LV.setThreadLocalRef(VD->isThreadSpecified());
1510       }
1511     }
1512     LV.setObjCArray(E->getType()->isArrayType());
1513     return;
1514   }
1515 
1516   if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1517     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1518     return;
1519   }
1520 
1521   if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1522     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1523     if (LV.isObjCIvar()) {
1524       // If cast is to a structure pointer, follow gcc's behavior and make it
1525       // a non-ivar write-barrier.
1526       QualType ExpTy = E->getType();
1527       if (ExpTy->isPointerType())
1528         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1529       if (ExpTy->isRecordType())
1530         LV.setObjCIvar(false);
1531     }
1532     return;
1533   }
1534 
1535   if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1536     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1537     return;
1538   }
1539 
1540   if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1541     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1542     return;
1543   }
1544 
1545   if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1546     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1547     return;
1548   }
1549 
1550   if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
1551     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1552     return;
1553   }
1554 
1555   if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1556     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1557     if (LV.isObjCIvar() && !LV.isObjCArray())
1558       // Using array syntax to assigning to what an ivar points to is not
1559       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1560       LV.setObjCIvar(false);
1561     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1562       // Using array syntax to assigning to what global points to is not
1563       // same as assigning to the global itself. {id *G;} G[i] = 0;
1564       LV.setGlobalObjCRef(false);
1565     return;
1566   }
1567 
1568   if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1569     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
1570     // We don't know if member is an 'ivar', but this flag is looked at
1571     // only in the context of LV.isObjCIvar().
1572     LV.setObjCArray(E->getType()->isArrayType());
1573     return;
1574   }
1575 }
1576 
1577 static llvm::Value *
1578 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
1579                                 llvm::Value *V, llvm::Type *IRType,
1580                                 StringRef Name = StringRef()) {
1581   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
1582   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
1583 }
1584 
1585 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1586                                       const Expr *E, const VarDecl *VD) {
1587   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1588   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1589   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
1590   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
1591   QualType T = E->getType();
1592   LValue LV;
1593   if (VD->getType()->isReferenceType()) {
1594     llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
1595     LI->setAlignment(Alignment.getQuantity());
1596     V = LI;
1597     LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1598   } else {
1599     LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1600   }
1601   setObjCGCLValueClass(CGF.getContext(), E, LV);
1602   return LV;
1603 }
1604 
1605 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1606                                      const Expr *E, const FunctionDecl *FD) {
1607   llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1608   if (!FD->hasPrototype()) {
1609     if (const FunctionProtoType *Proto =
1610             FD->getType()->getAs<FunctionProtoType>()) {
1611       // Ugly case: for a K&R-style definition, the type of the definition
1612       // isn't the same as the type of a use.  Correct for this with a
1613       // bitcast.
1614       QualType NoProtoType =
1615           CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1616       NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1617       V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
1618     }
1619   }
1620   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
1621   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1622 }
1623 
1624 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1625   const NamedDecl *ND = E->getDecl();
1626   CharUnits Alignment = getContext().getDeclAlign(ND);
1627   QualType T = E->getType();
1628 
1629   // A DeclRefExpr for a reference initialized by a constant expression can
1630   // appear without being odr-used. Directly emit the constant initializer.
1631   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1632     const Expr *Init = VD->getAnyInitializer(VD);
1633     if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1634         VD->isUsableInConstantExpressions(getContext()) &&
1635         VD->checkInitIsICE()) {
1636       llvm::Constant *Val =
1637         CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1638       assert(Val && "failed to emit reference constant expression");
1639       // FIXME: Eventually we will want to emit vector element references.
1640       return MakeAddrLValue(Val, T, Alignment);
1641     }
1642   }
1643 
1644   // FIXME: We should be able to assert this for FunctionDecls as well!
1645   // FIXME: We should be able to assert this for all DeclRefExprs, not just
1646   // those with a valid source location.
1647   assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1648           !E->getLocation().isValid()) &&
1649          "Should not use decl without marking it used!");
1650 
1651   if (ND->hasAttr<WeakRefAttr>()) {
1652     const ValueDecl *VD = cast<ValueDecl>(ND);
1653     llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1654     return MakeAddrLValue(Aliasee, T, Alignment);
1655   }
1656 
1657   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1658     // Check if this is a global variable.
1659     if (VD->hasLinkage() || VD->isStaticDataMember())
1660       return EmitGlobalVarDeclLValue(*this, E, VD);
1661 
1662     bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1663 
1664     bool NonGCable = VD->hasLocalStorage() &&
1665                      !VD->getType()->isReferenceType() &&
1666                      !isBlockVariable;
1667 
1668     llvm::Value *V = LocalDeclMap.lookup(VD);
1669     if (!V && VD->isStaticLocal())
1670       V = CGM.getStaticLocalDeclAddress(VD);
1671 
1672     // Use special handling for lambdas.
1673     if (!V) {
1674       if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1675         QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1676         LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1677                                                      LambdaTagType);
1678         return EmitLValueForField(LambdaLV, FD);
1679       }
1680 
1681       assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
1682       return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
1683                             T, Alignment);
1684     }
1685 
1686     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1687 
1688     if (isBlockVariable)
1689       V = BuildBlockByrefAddress(V, VD);
1690 
1691     LValue LV;
1692     if (VD->getType()->isReferenceType()) {
1693       llvm::LoadInst *LI = Builder.CreateLoad(V);
1694       LI->setAlignment(Alignment.getQuantity());
1695       V = LI;
1696       LV = MakeNaturalAlignAddrLValue(V, T);
1697     } else {
1698       LV = MakeAddrLValue(V, T, Alignment);
1699     }
1700 
1701     if (NonGCable) {
1702       LV.getQuals().removeObjCGCAttr();
1703       LV.setNonGC(true);
1704     }
1705     setObjCGCLValueClass(getContext(), E, LV);
1706     return LV;
1707   }
1708 
1709   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1710     return EmitFunctionDeclLValue(*this, E, fn);
1711 
1712   llvm_unreachable("Unhandled DeclRefExpr");
1713 }
1714 
1715 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1716   // __extension__ doesn't affect lvalue-ness.
1717   if (E->getOpcode() == UO_Extension)
1718     return EmitLValue(E->getSubExpr());
1719 
1720   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1721   switch (E->getOpcode()) {
1722   default: llvm_unreachable("Unknown unary operator lvalue!");
1723   case UO_Deref: {
1724     QualType T = E->getSubExpr()->getType()->getPointeeType();
1725     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1726 
1727     LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1728     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1729 
1730     // We should not generate __weak write barrier on indirect reference
1731     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1732     // But, we continue to generate __strong write barrier on indirect write
1733     // into a pointer to object.
1734     if (getLangOpts().ObjC1 &&
1735         getLangOpts().getGC() != LangOptions::NonGC &&
1736         LV.isObjCWeak())
1737       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1738     return LV;
1739   }
1740   case UO_Real:
1741   case UO_Imag: {
1742     LValue LV = EmitLValue(E->getSubExpr());
1743     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1744     llvm::Value *Addr = LV.getAddress();
1745 
1746     // __real is valid on scalars.  This is a faster way of testing that.
1747     // __imag can only produce an rvalue on scalars.
1748     if (E->getOpcode() == UO_Real &&
1749         !cast<llvm::PointerType>(Addr->getType())
1750            ->getElementType()->isStructTy()) {
1751       assert(E->getSubExpr()->getType()->isArithmeticType());
1752       return LV;
1753     }
1754 
1755     assert(E->getSubExpr()->getType()->isAnyComplexType());
1756 
1757     unsigned Idx = E->getOpcode() == UO_Imag;
1758     return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
1759                                                   Idx, "idx"),
1760                           ExprTy);
1761   }
1762   case UO_PreInc:
1763   case UO_PreDec: {
1764     LValue LV = EmitLValue(E->getSubExpr());
1765     bool isInc = E->getOpcode() == UO_PreInc;
1766 
1767     if (E->getType()->isAnyComplexType())
1768       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1769     else
1770       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1771     return LV;
1772   }
1773   }
1774 }
1775 
1776 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1777   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1778                         E->getType());
1779 }
1780 
1781 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1782   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1783                         E->getType());
1784 }
1785 
1786 static llvm::Constant*
1787 GetAddrOfConstantWideString(StringRef Str,
1788                             const char *GlobalName,
1789                             ASTContext &Context,
1790                             QualType Ty, SourceLocation Loc,
1791                             CodeGenModule &CGM) {
1792 
1793   StringLiteral *SL = StringLiteral::Create(Context,
1794                                             Str,
1795                                             StringLiteral::Wide,
1796                                             /*Pascal = */false,
1797                                             Ty, Loc);
1798   llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
1799   llvm::GlobalVariable *GV =
1800     new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1801                              !CGM.getLangOpts().WritableStrings,
1802                              llvm::GlobalValue::PrivateLinkage,
1803                              C, GlobalName);
1804   const unsigned WideAlignment =
1805     Context.getTypeAlignInChars(Ty).getQuantity();
1806   GV->setAlignment(WideAlignment);
1807   return GV;
1808 }
1809 
1810 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1811                                     SmallString<32>& Target) {
1812   Target.resize(CharByteWidth * (Source.size() + 1));
1813   char *ResultPtr = &Target[0];
1814   const UTF8 *ErrorPtr;
1815   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
1816   (void)success;
1817   assert(success);
1818   Target.resize(ResultPtr - &Target[0]);
1819 }
1820 
1821 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1822   switch (E->getIdentType()) {
1823   default:
1824     return EmitUnsupportedLValue(E, "predefined expression");
1825 
1826   case PredefinedExpr::Func:
1827   case PredefinedExpr::Function:
1828   case PredefinedExpr::LFunction:
1829   case PredefinedExpr::PrettyFunction: {
1830     unsigned IdentType = E->getIdentType();
1831     std::string GlobalVarName;
1832 
1833     switch (IdentType) {
1834     default: llvm_unreachable("Invalid type");
1835     case PredefinedExpr::Func:
1836       GlobalVarName = "__func__.";
1837       break;
1838     case PredefinedExpr::Function:
1839       GlobalVarName = "__FUNCTION__.";
1840       break;
1841     case PredefinedExpr::LFunction:
1842       GlobalVarName = "L__FUNCTION__.";
1843       break;
1844     case PredefinedExpr::PrettyFunction:
1845       GlobalVarName = "__PRETTY_FUNCTION__.";
1846       break;
1847     }
1848 
1849     StringRef FnName = CurFn->getName();
1850     if (FnName.startswith("\01"))
1851       FnName = FnName.substr(1);
1852     GlobalVarName += FnName;
1853 
1854     const Decl *CurDecl = CurCodeDecl;
1855     if (CurDecl == 0)
1856       CurDecl = getContext().getTranslationUnitDecl();
1857 
1858     std::string FunctionName =
1859         (isa<BlockDecl>(CurDecl)
1860          ? FnName.str()
1861          : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType,
1862                                        CurDecl));
1863 
1864     const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual();
1865     llvm::Constant *C;
1866     if (ElemType->isWideCharType()) {
1867       SmallString<32> RawChars;
1868       ConvertUTF8ToWideString(
1869           getContext().getTypeSizeInChars(ElemType).getQuantity(),
1870           FunctionName, RawChars);
1871       C = GetAddrOfConstantWideString(RawChars,
1872                                       GlobalVarName.c_str(),
1873                                       getContext(),
1874                                       E->getType(),
1875                                       E->getLocation(),
1876                                       CGM);
1877     } else {
1878       C = CGM.GetAddrOfConstantCString(FunctionName,
1879                                        GlobalVarName.c_str(),
1880                                        1);
1881     }
1882     return MakeAddrLValue(C, E->getType());
1883   }
1884   }
1885 }
1886 
1887 /// Emit a type description suitable for use by a runtime sanitizer library. The
1888 /// format of a type descriptor is
1889 ///
1890 /// \code
1891 ///   { i16 TypeKind, i16 TypeInfo }
1892 /// \endcode
1893 ///
1894 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
1895 /// integer, 1 for a floating point value, and -1 for anything else.
1896 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
1897   // FIXME: Only emit each type's descriptor once.
1898   uint16_t TypeKind = -1;
1899   uint16_t TypeInfo = 0;
1900 
1901   if (T->isIntegerType()) {
1902     TypeKind = 0;
1903     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
1904                (T->isSignedIntegerType() ? 1 : 0);
1905   } else if (T->isFloatingType()) {
1906     TypeKind = 1;
1907     TypeInfo = getContext().getTypeSize(T);
1908   }
1909 
1910   // Format the type name as if for a diagnostic, including quotes and
1911   // optionally an 'aka'.
1912   SmallString<32> Buffer;
1913   CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
1914                                     (intptr_t)T.getAsOpaquePtr(),
1915                                     0, 0, 0, 0, 0, 0, Buffer,
1916                                     ArrayRef<intptr_t>());
1917 
1918   llvm::Constant *Components[] = {
1919     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
1920     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
1921   };
1922   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
1923 
1924   llvm::GlobalVariable *GV =
1925     new llvm::GlobalVariable(CGM.getModule(), Descriptor->getType(),
1926                              /*isConstant=*/true,
1927                              llvm::GlobalVariable::PrivateLinkage,
1928                              Descriptor);
1929   GV->setUnnamedAddr(true);
1930   return GV;
1931 }
1932 
1933 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
1934   llvm::Type *TargetTy = IntPtrTy;
1935 
1936   // Integers which fit in intptr_t are zero-extended and passed directly.
1937   if (V->getType()->isIntegerTy() &&
1938       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
1939     return Builder.CreateZExt(V, TargetTy);
1940 
1941   // Pointers are passed directly, everything else is passed by address.
1942   if (!V->getType()->isPointerTy()) {
1943     llvm::Value *Ptr = Builder.CreateAlloca(V->getType());
1944     Builder.CreateStore(V, Ptr);
1945     V = Ptr;
1946   }
1947   return Builder.CreatePtrToInt(V, TargetTy);
1948 }
1949 
1950 /// \brief Emit a representation of a SourceLocation for passing to a handler
1951 /// in a sanitizer runtime library. The format for this data is:
1952 /// \code
1953 ///   struct SourceLocation {
1954 ///     const char *Filename;
1955 ///     int32_t Line, Column;
1956 ///   };
1957 /// \endcode
1958 /// For an invalid SourceLocation, the Filename pointer is null.
1959 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
1960   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
1961 
1962   llvm::Constant *Data[] = {
1963     // FIXME: Only emit each file name once.
1964     PLoc.isValid() ? cast<llvm::Constant>(
1965                        Builder.CreateGlobalStringPtr(PLoc.getFilename()))
1966                    : llvm::Constant::getNullValue(Int8PtrTy),
1967     Builder.getInt32(PLoc.getLine()),
1968     Builder.getInt32(PLoc.getColumn())
1969   };
1970 
1971   return llvm::ConstantStruct::getAnon(Data);
1972 }
1973 
1974 void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName,
1975                                 ArrayRef<llvm::Constant *> StaticArgs,
1976                                 ArrayRef<llvm::Value *> DynamicArgs,
1977                                 CheckRecoverableKind RecoverKind) {
1978   assert(SanOpts != &SanitizerOptions::Disabled);
1979 
1980   if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
1981     assert (RecoverKind != CRK_AlwaysRecoverable &&
1982             "Runtime call required for AlwaysRecoverable kind!");
1983     return EmitTrapCheck(Checked);
1984   }
1985 
1986   llvm::BasicBlock *Cont = createBasicBlock("cont");
1987 
1988   llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
1989 
1990   llvm::Instruction *Branch = Builder.CreateCondBr(Checked, Cont, Handler);
1991 
1992   // Give hint that we very much don't expect to execute the handler
1993   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
1994   llvm::MDBuilder MDHelper(getLLVMContext());
1995   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
1996   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
1997 
1998   EmitBlock(Handler);
1999 
2000   llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2001   llvm::GlobalValue *InfoPtr =
2002       new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2003                                llvm::GlobalVariable::PrivateLinkage, Info);
2004   InfoPtr->setUnnamedAddr(true);
2005 
2006   SmallVector<llvm::Value *, 4> Args;
2007   SmallVector<llvm::Type *, 4> ArgTypes;
2008   Args.reserve(DynamicArgs.size() + 1);
2009   ArgTypes.reserve(DynamicArgs.size() + 1);
2010 
2011   // Handler functions take an i8* pointing to the (handler-specific) static
2012   // information block, followed by a sequence of intptr_t arguments
2013   // representing operand values.
2014   Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2015   ArgTypes.push_back(Int8PtrTy);
2016   for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2017     Args.push_back(EmitCheckValue(DynamicArgs[i]));
2018     ArgTypes.push_back(IntPtrTy);
2019   }
2020 
2021   bool Recover = (RecoverKind == CRK_AlwaysRecoverable) ||
2022                  ((RecoverKind == CRK_Recoverable) &&
2023                    CGM.getCodeGenOpts().SanitizeRecover);
2024 
2025   llvm::FunctionType *FnType =
2026     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2027   llvm::AttrBuilder B;
2028   if (!Recover) {
2029     B.addAttribute(llvm::Attribute::NoReturn)
2030      .addAttribute(llvm::Attribute::NoUnwind);
2031   }
2032   B.addAttribute(llvm::Attribute::UWTable);
2033 
2034   // Checks that have two variants use a suffix to differentiate them
2035   bool NeedsAbortSuffix = (RecoverKind != CRK_Unrecoverable) &&
2036                            !CGM.getCodeGenOpts().SanitizeRecover;
2037   std::string FunctionName = ("__ubsan_handle_" + CheckName +
2038                               (NeedsAbortSuffix? "_abort" : "")).str();
2039   llvm::Value *Fn =
2040     CGM.CreateRuntimeFunction(FnType, FunctionName,
2041                               llvm::AttributeSet::get(getLLVMContext(),
2042                                               llvm::AttributeSet::FunctionIndex,
2043                                                       B));
2044   llvm::CallInst *HandlerCall = Builder.CreateCall(Fn, Args);
2045   if (Recover) {
2046     Builder.CreateBr(Cont);
2047   } else {
2048     HandlerCall->setDoesNotReturn();
2049     HandlerCall->setDoesNotThrow();
2050     Builder.CreateUnreachable();
2051   }
2052 
2053   EmitBlock(Cont);
2054 }
2055 
2056 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2057   llvm::BasicBlock *Cont = createBasicBlock("cont");
2058 
2059   // If we're optimizing, collapse all calls to trap down to just one per
2060   // function to save on code size.
2061   if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2062     TrapBB = createBasicBlock("trap");
2063     Builder.CreateCondBr(Checked, Cont, TrapBB);
2064     EmitBlock(TrapBB);
2065     llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2066     llvm::CallInst *TrapCall = Builder.CreateCall(F);
2067     TrapCall->setDoesNotReturn();
2068     TrapCall->setDoesNotThrow();
2069     Builder.CreateUnreachable();
2070   } else {
2071     Builder.CreateCondBr(Checked, Cont, TrapBB);
2072   }
2073 
2074   EmitBlock(Cont);
2075 }
2076 
2077 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2078 /// array to pointer, return the array subexpression.
2079 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2080   // If this isn't just an array->pointer decay, bail out.
2081   const CastExpr *CE = dyn_cast<CastExpr>(E);
2082   if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
2083     return 0;
2084 
2085   // If this is a decay from variable width array, bail out.
2086   const Expr *SubExpr = CE->getSubExpr();
2087   if (SubExpr->getType()->isVariableArrayType())
2088     return 0;
2089 
2090   return SubExpr;
2091 }
2092 
2093 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
2094   // The index must always be an integer, which is not an aggregate.  Emit it.
2095   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
2096   QualType IdxTy  = E->getIdx()->getType();
2097   bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2098 
2099   // If the base is a vector type, then we are forming a vector element lvalue
2100   // with this subscript.
2101   if (E->getBase()->getType()->isVectorType()) {
2102     // Emit the vector as an lvalue to get its address.
2103     LValue LHS = EmitLValue(E->getBase());
2104     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
2105     Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
2106     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
2107                                  E->getBase()->getType(), LHS.getAlignment());
2108   }
2109 
2110   // Extend or truncate the index type to 32 or 64-bits.
2111   if (Idx->getType() != IntPtrTy)
2112     Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2113 
2114   // We know that the pointer points to a type of the correct size, unless the
2115   // size is a VLA or Objective-C interface.
2116   llvm::Value *Address = 0;
2117   CharUnits ArrayAlignment;
2118   if (const VariableArrayType *vla =
2119         getContext().getAsVariableArrayType(E->getType())) {
2120     // The base must be a pointer, which is not an aggregate.  Emit
2121     // it.  It needs to be emitted first in case it's what captures
2122     // the VLA bounds.
2123     Address = EmitScalarExpr(E->getBase());
2124 
2125     // The element count here is the total number of non-VLA elements.
2126     llvm::Value *numElements = getVLASize(vla).first;
2127 
2128     // Effectively, the multiply by the VLA size is part of the GEP.
2129     // GEP indexes are signed, and scaling an index isn't permitted to
2130     // signed-overflow, so we use the same semantics for our explicit
2131     // multiply.  We suppress this if overflow is not undefined behavior.
2132     if (getLangOpts().isSignedOverflowDefined()) {
2133       Idx = Builder.CreateMul(Idx, numElements);
2134       Address = Builder.CreateGEP(Address, Idx, "arrayidx");
2135     } else {
2136       Idx = Builder.CreateNSWMul(Idx, numElements);
2137       Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
2138     }
2139   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2140     // Indexing over an interface, as in "NSString *P; P[4];"
2141     llvm::Value *InterfaceSize =
2142       llvm::ConstantInt::get(Idx->getType(),
2143           getContext().getTypeSizeInChars(OIT).getQuantity());
2144 
2145     Idx = Builder.CreateMul(Idx, InterfaceSize);
2146 
2147     // The base must be a pointer, which is not an aggregate.  Emit it.
2148     llvm::Value *Base = EmitScalarExpr(E->getBase());
2149     Address = EmitCastToVoidPtr(Base);
2150     Address = Builder.CreateGEP(Address, Idx, "arrayidx");
2151     Address = Builder.CreateBitCast(Address, Base->getType());
2152   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2153     // If this is A[i] where A is an array, the frontend will have decayed the
2154     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
2155     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2156     // "gep x, i" here.  Emit one "gep A, 0, i".
2157     assert(Array->getType()->isArrayType() &&
2158            "Array to pointer decay must have array source type!");
2159     LValue ArrayLV = EmitLValue(Array);
2160     llvm::Value *ArrayPtr = ArrayLV.getAddress();
2161     llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2162     llvm::Value *Args[] = { Zero, Idx };
2163 
2164     // Propagate the alignment from the array itself to the result.
2165     ArrayAlignment = ArrayLV.getAlignment();
2166 
2167     if (getLangOpts().isSignedOverflowDefined())
2168       Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
2169     else
2170       Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
2171   } else {
2172     // The base must be a pointer, which is not an aggregate.  Emit it.
2173     llvm::Value *Base = EmitScalarExpr(E->getBase());
2174     if (getLangOpts().isSignedOverflowDefined())
2175       Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2176     else
2177       Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
2178   }
2179 
2180   QualType T = E->getBase()->getType()->getPointeeType();
2181   assert(!T.isNull() &&
2182          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
2183 
2184 
2185   // Limit the alignment to that of the result type.
2186   LValue LV;
2187   if (!ArrayAlignment.isZero()) {
2188     CharUnits Align = getContext().getTypeAlignInChars(T);
2189     ArrayAlignment = std::min(Align, ArrayAlignment);
2190     LV = MakeAddrLValue(Address, T, ArrayAlignment);
2191   } else {
2192     LV = MakeNaturalAlignAddrLValue(Address, T);
2193   }
2194 
2195   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
2196 
2197   if (getLangOpts().ObjC1 &&
2198       getLangOpts().getGC() != LangOptions::NonGC) {
2199     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2200     setObjCGCLValueClass(getContext(), E, LV);
2201   }
2202   return LV;
2203 }
2204 
2205 static
2206 llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
2207                                        SmallVector<unsigned, 4> &Elts) {
2208   SmallVector<llvm::Constant*, 4> CElts;
2209   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
2210     CElts.push_back(Builder.getInt32(Elts[i]));
2211 
2212   return llvm::ConstantVector::get(CElts);
2213 }
2214 
2215 LValue CodeGenFunction::
2216 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
2217   // Emit the base vector as an l-value.
2218   LValue Base;
2219 
2220   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
2221   if (E->isArrow()) {
2222     // If it is a pointer to a vector, emit the address and form an lvalue with
2223     // it.
2224     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
2225     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
2226     Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2227     Base.getQuals().removeObjCGCAttr();
2228   } else if (E->getBase()->isGLValue()) {
2229     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2230     // emit the base as an lvalue.
2231     assert(E->getBase()->getType()->isVectorType());
2232     Base = EmitLValue(E->getBase());
2233   } else {
2234     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
2235     assert(E->getBase()->getType()->isVectorType() &&
2236            "Result must be a vector");
2237     llvm::Value *Vec = EmitScalarExpr(E->getBase());
2238 
2239     // Store the vector to memory (because LValue wants an address).
2240     llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
2241     Builder.CreateStore(Vec, VecMem);
2242     Base = MakeAddrLValue(VecMem, E->getBase()->getType());
2243   }
2244 
2245   QualType type =
2246     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
2247 
2248   // Encode the element access list into a vector of unsigned indices.
2249   SmallVector<unsigned, 4> Indices;
2250   E->getEncodedElementAccess(Indices);
2251 
2252   if (Base.isSimple()) {
2253     llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
2254     return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2255                                     Base.getAlignment());
2256   }
2257   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2258 
2259   llvm::Constant *BaseElts = Base.getExtVectorElts();
2260   SmallVector<llvm::Constant *, 4> CElts;
2261 
2262   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2263     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
2264   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
2265   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2266                                   Base.getAlignment());
2267 }
2268 
2269 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
2270   Expr *BaseExpr = E->getBase();
2271 
2272   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
2273   LValue BaseLV;
2274   if (E->isArrow()) {
2275     llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2276     QualType PtrTy = BaseExpr->getType()->getPointeeType();
2277     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
2278     BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2279   } else
2280     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
2281 
2282   NamedDecl *ND = E->getMemberDecl();
2283   if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
2284     LValue LV = EmitLValueForField(BaseLV, Field);
2285     setObjCGCLValueClass(getContext(), E, LV);
2286     return LV;
2287   }
2288 
2289   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
2290     return EmitGlobalVarDeclLValue(*this, E, VD);
2291 
2292   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
2293     return EmitFunctionDeclLValue(*this, E, FD);
2294 
2295   llvm_unreachable("Unhandled member declaration!");
2296 }
2297 
2298 LValue CodeGenFunction::EmitLValueForField(LValue base,
2299                                            const FieldDecl *field) {
2300   if (field->isBitField()) {
2301     const CGRecordLayout &RL =
2302       CGM.getTypes().getCGRecordLayout(field->getParent());
2303     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
2304     llvm::Value *Addr = base.getAddress();
2305     unsigned Idx = RL.getLLVMFieldNo(field);
2306     if (Idx != 0)
2307       // For structs, we GEP to the field that the record layout suggests.
2308       Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
2309     // Get the access type.
2310     llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
2311       getLLVMContext(), Info.StorageSize,
2312       CGM.getContext().getTargetAddressSpace(base.getType()));
2313     if (Addr->getType() != PtrTy)
2314       Addr = Builder.CreateBitCast(Addr, PtrTy);
2315 
2316     QualType fieldType =
2317       field->getType().withCVRQualifiers(base.getVRQualifiers());
2318     return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
2319   }
2320 
2321   const RecordDecl *rec = field->getParent();
2322   QualType type = field->getType();
2323   CharUnits alignment = getContext().getDeclAlign(field);
2324 
2325   // FIXME: It should be impossible to have an LValue without alignment for a
2326   // complete type.
2327   if (!base.getAlignment().isZero())
2328     alignment = std::min(alignment, base.getAlignment());
2329 
2330   bool mayAlias = rec->hasAttr<MayAliasAttr>();
2331 
2332   llvm::Value *addr = base.getAddress();
2333   unsigned cvr = base.getVRQualifiers();
2334   if (rec->isUnion()) {
2335     // For unions, there is no pointer adjustment.
2336     assert(!type->isReferenceType() && "union has reference member");
2337   } else {
2338     // For structs, we GEP to the field that the record layout suggests.
2339     unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
2340     addr = Builder.CreateStructGEP(addr, idx, field->getName());
2341 
2342     // If this is a reference field, load the reference right now.
2343     if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2344       llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2345       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
2346       load->setAlignment(alignment.getQuantity());
2347 
2348       if (CGM.shouldUseTBAA()) {
2349         llvm::MDNode *tbaa;
2350         if (mayAlias)
2351           tbaa = CGM.getTBAAInfo(getContext().CharTy);
2352         else
2353           tbaa = CGM.getTBAAInfo(type);
2354         CGM.DecorateInstruction(load, tbaa);
2355       }
2356 
2357       addr = load;
2358       mayAlias = false;
2359       type = refType->getPointeeType();
2360       if (type->isIncompleteType())
2361         alignment = CharUnits();
2362       else
2363         alignment = getContext().getTypeAlignInChars(type);
2364       cvr = 0; // qualifiers don't recursively apply to referencee
2365     }
2366   }
2367 
2368   // Make sure that the address is pointing to the right type.  This is critical
2369   // for both unions and structs.  A union needs a bitcast, a struct element
2370   // will need a bitcast if the LLVM type laid out doesn't match the desired
2371   // type.
2372   addr = EmitBitCastOfLValueToProperType(*this, addr,
2373                                          CGM.getTypes().ConvertTypeForMem(type),
2374                                          field->getName());
2375 
2376   if (field->hasAttr<AnnotateAttr>())
2377     addr = EmitFieldAnnotations(field, addr);
2378 
2379   LValue LV = MakeAddrLValue(addr, type, alignment);
2380   LV.getQuals().addCVRQualifiers(cvr);
2381 
2382   // __weak attribute on a field is ignored.
2383   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2384     LV.getQuals().removeObjCGCAttr();
2385 
2386   // Fields of may_alias structs act like 'char' for TBAA purposes.
2387   // FIXME: this should get propagated down through anonymous structs
2388   // and unions.
2389   if (mayAlias && LV.getTBAAInfo())
2390     LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2391 
2392   return LV;
2393 }
2394 
2395 LValue
2396 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2397                                                   const FieldDecl *Field) {
2398   QualType FieldType = Field->getType();
2399 
2400   if (!FieldType->isReferenceType())
2401     return EmitLValueForField(Base, Field);
2402 
2403   const CGRecordLayout &RL =
2404     CGM.getTypes().getCGRecordLayout(Field->getParent());
2405   unsigned idx = RL.getLLVMFieldNo(Field);
2406   llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
2407   assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2408 
2409   // Make sure that the address is pointing to the right type.  This is critical
2410   // for both unions and structs.  A union needs a bitcast, a struct element
2411   // will need a bitcast if the LLVM type laid out doesn't match the desired
2412   // type.
2413   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
2414   V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2415 
2416   CharUnits Alignment = getContext().getDeclAlign(Field);
2417 
2418   // FIXME: It should be impossible to have an LValue without alignment for a
2419   // complete type.
2420   if (!Base.getAlignment().isZero())
2421     Alignment = std::min(Alignment, Base.getAlignment());
2422 
2423   return MakeAddrLValue(V, FieldType, Alignment);
2424 }
2425 
2426 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
2427   if (E->isFileScope()) {
2428     llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2429     return MakeAddrLValue(GlobalPtr, E->getType());
2430   }
2431   if (E->getType()->isVariablyModifiedType())
2432     // make sure to emit the VLA size.
2433     EmitVariablyModifiedType(E->getType());
2434 
2435   llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
2436   const Expr *InitExpr = E->getInitializer();
2437   LValue Result = MakeAddrLValue(DeclPtr, E->getType());
2438 
2439   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2440                    /*Init*/ true);
2441 
2442   return Result;
2443 }
2444 
2445 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2446   if (!E->isGLValue())
2447     // Initializing an aggregate temporary in C++11: T{...}.
2448     return EmitAggExprToLValue(E);
2449 
2450   // An lvalue initializer list must be initializing a reference.
2451   assert(E->getNumInits() == 1 && "reference init with multiple values");
2452   return EmitLValue(E->getInit(0));
2453 }
2454 
2455 LValue CodeGenFunction::
2456 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2457   if (!expr->isGLValue()) {
2458     // ?: here should be an aggregate.
2459     assert((hasAggregateLLVMType(expr->getType()) &&
2460             !expr->getType()->isAnyComplexType()) &&
2461            "Unexpected conditional operator!");
2462     return EmitAggExprToLValue(expr);
2463   }
2464 
2465   OpaqueValueMapping binding(*this, expr);
2466 
2467   const Expr *condExpr = expr->getCond();
2468   bool CondExprBool;
2469   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2470     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
2471     if (!CondExprBool) std::swap(live, dead);
2472 
2473     if (!ContainsLabel(dead))
2474       return EmitLValue(live);
2475   }
2476 
2477   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2478   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2479   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
2480 
2481   ConditionalEvaluation eval(*this);
2482   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
2483 
2484   // Any temporaries created here are conditional.
2485   EmitBlock(lhsBlock);
2486   eval.begin(*this);
2487   LValue lhs = EmitLValue(expr->getTrueExpr());
2488   eval.end(*this);
2489 
2490   if (!lhs.isSimple())
2491     return EmitUnsupportedLValue(expr, "conditional operator");
2492 
2493   lhsBlock = Builder.GetInsertBlock();
2494   Builder.CreateBr(contBlock);
2495 
2496   // Any temporaries created here are conditional.
2497   EmitBlock(rhsBlock);
2498   eval.begin(*this);
2499   LValue rhs = EmitLValue(expr->getFalseExpr());
2500   eval.end(*this);
2501   if (!rhs.isSimple())
2502     return EmitUnsupportedLValue(expr, "conditional operator");
2503   rhsBlock = Builder.GetInsertBlock();
2504 
2505   EmitBlock(contBlock);
2506 
2507   llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
2508                                          "cond-lvalue");
2509   phi->addIncoming(lhs.getAddress(), lhsBlock);
2510   phi->addIncoming(rhs.getAddress(), rhsBlock);
2511   return MakeAddrLValue(phi, expr->getType());
2512 }
2513 
2514 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2515 /// type. If the cast is to a reference, we can have the usual lvalue result,
2516 /// otherwise if a cast is needed by the code generator in an lvalue context,
2517 /// then it must mean that we need the address of an aggregate in order to
2518 /// access one of its members.  This can happen for all the reasons that casts
2519 /// are permitted with aggregate result, including noop aggregate casts, and
2520 /// cast from scalar to union.
2521 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
2522   switch (E->getCastKind()) {
2523   case CK_ToVoid:
2524     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
2525 
2526   case CK_Dependent:
2527     llvm_unreachable("dependent cast kind in IR gen!");
2528 
2529   case CK_BuiltinFnToFnPtr:
2530     llvm_unreachable("builtin functions are handled elsewhere");
2531 
2532   // These two casts are currently treated as no-ops, although they could
2533   // potentially be real operations depending on the target's ABI.
2534   case CK_NonAtomicToAtomic:
2535   case CK_AtomicToNonAtomic:
2536 
2537   case CK_NoOp:
2538   case CK_LValueToRValue:
2539     if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2540         || E->getType()->isRecordType())
2541       return EmitLValue(E->getSubExpr());
2542     // Fall through to synthesize a temporary.
2543 
2544   case CK_BitCast:
2545   case CK_ArrayToPointerDecay:
2546   case CK_FunctionToPointerDecay:
2547   case CK_NullToMemberPointer:
2548   case CK_NullToPointer:
2549   case CK_IntegralToPointer:
2550   case CK_PointerToIntegral:
2551   case CK_PointerToBoolean:
2552   case CK_VectorSplat:
2553   case CK_IntegralCast:
2554   case CK_IntegralToBoolean:
2555   case CK_IntegralToFloating:
2556   case CK_FloatingToIntegral:
2557   case CK_FloatingToBoolean:
2558   case CK_FloatingCast:
2559   case CK_FloatingRealToComplex:
2560   case CK_FloatingComplexToReal:
2561   case CK_FloatingComplexToBoolean:
2562   case CK_FloatingComplexCast:
2563   case CK_FloatingComplexToIntegralComplex:
2564   case CK_IntegralRealToComplex:
2565   case CK_IntegralComplexToReal:
2566   case CK_IntegralComplexToBoolean:
2567   case CK_IntegralComplexCast:
2568   case CK_IntegralComplexToFloatingComplex:
2569   case CK_DerivedToBaseMemberPointer:
2570   case CK_BaseToDerivedMemberPointer:
2571   case CK_MemberPointerToBoolean:
2572   case CK_ReinterpretMemberPointer:
2573   case CK_AnyPointerToBlockPointerCast:
2574   case CK_ARCProduceObject:
2575   case CK_ARCConsumeObject:
2576   case CK_ARCReclaimReturnedObject:
2577   case CK_ARCExtendBlockObject:
2578   case CK_CopyAndAutoreleaseBlockObject: {
2579     // These casts only produce lvalues when we're binding a reference to a
2580     // temporary realized from a (converted) pure rvalue. Emit the expression
2581     // as a value, copy it into a temporary, and return an lvalue referring to
2582     // that temporary.
2583     llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
2584     EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
2585     return MakeAddrLValue(V, E->getType());
2586   }
2587 
2588   case CK_Dynamic: {
2589     LValue LV = EmitLValue(E->getSubExpr());
2590     llvm::Value *V = LV.getAddress();
2591     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
2592     return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
2593   }
2594 
2595   case CK_ConstructorConversion:
2596   case CK_UserDefinedConversion:
2597   case CK_CPointerToObjCPointerCast:
2598   case CK_BlockPointerToObjCPointerCast:
2599     return EmitLValue(E->getSubExpr());
2600 
2601   case CK_UncheckedDerivedToBase:
2602   case CK_DerivedToBase: {
2603     const RecordType *DerivedClassTy =
2604       E->getSubExpr()->getType()->getAs<RecordType>();
2605     CXXRecordDecl *DerivedClassDecl =
2606       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2607 
2608     LValue LV = EmitLValue(E->getSubExpr());
2609     llvm::Value *This = LV.getAddress();
2610 
2611     // Perform the derived-to-base conversion
2612     llvm::Value *Base =
2613       GetAddressOfBaseClass(This, DerivedClassDecl,
2614                             E->path_begin(), E->path_end(),
2615                             /*NullCheckValue=*/false);
2616 
2617     return MakeAddrLValue(Base, E->getType());
2618   }
2619   case CK_ToUnion:
2620     return EmitAggExprToLValue(E);
2621   case CK_BaseToDerived: {
2622     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2623     CXXRecordDecl *DerivedClassDecl =
2624       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2625 
2626     LValue LV = EmitLValue(E->getSubExpr());
2627 
2628     // Perform the base-to-derived conversion
2629     llvm::Value *Derived =
2630       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
2631                                E->path_begin(), E->path_end(),
2632                                /*NullCheckValue=*/false);
2633 
2634     return MakeAddrLValue(Derived, E->getType());
2635   }
2636   case CK_LValueBitCast: {
2637     // This must be a reinterpret_cast (or c-style equivalent).
2638     const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
2639 
2640     LValue LV = EmitLValue(E->getSubExpr());
2641     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2642                                            ConvertType(CE->getTypeAsWritten()));
2643     return MakeAddrLValue(V, E->getType());
2644   }
2645   case CK_ObjCObjectLValueCast: {
2646     LValue LV = EmitLValue(E->getSubExpr());
2647     QualType ToType = getContext().getLValueReferenceType(E->getType());
2648     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2649                                            ConvertType(ToType));
2650     return MakeAddrLValue(V, E->getType());
2651   }
2652   case CK_ZeroToOCLEvent:
2653     llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
2654   }
2655 
2656   llvm_unreachable("Unhandled lvalue cast kind?");
2657 }
2658 
2659 LValue CodeGenFunction::EmitNullInitializationLValue(
2660                                               const CXXScalarValueInitExpr *E) {
2661   QualType Ty = E->getType();
2662   LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
2663   EmitNullInitialization(LV.getAddress(), Ty);
2664   return LV;
2665 }
2666 
2667 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
2668   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
2669   return getOpaqueLValueMapping(e);
2670 }
2671 
2672 LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2673                                            const MaterializeTemporaryExpr *E) {
2674   RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
2675   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2676 }
2677 
2678 RValue CodeGenFunction::EmitRValueForField(LValue LV,
2679                                            const FieldDecl *FD) {
2680   QualType FT = FD->getType();
2681   LValue FieldLV = EmitLValueForField(LV, FD);
2682   if (FT->isAnyComplexType())
2683     return RValue::getComplex(
2684         LoadComplexFromAddr(FieldLV.getAddress(),
2685                             FieldLV.isVolatileQualified()));
2686   else if (CodeGenFunction::hasAggregateLLVMType(FT))
2687     return FieldLV.asAggregateRValue();
2688 
2689   return EmitLoadOfLValue(FieldLV);
2690 }
2691 
2692 //===--------------------------------------------------------------------===//
2693 //                             Expression Emission
2694 //===--------------------------------------------------------------------===//
2695 
2696 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2697                                      ReturnValueSlot ReturnValue) {
2698   if (CGDebugInfo *DI = getDebugInfo())
2699     DI->EmitLocation(Builder, E->getLocStart());
2700 
2701   // Builtins never have block type.
2702   if (E->getCallee()->getType()->isBlockPointerType())
2703     return EmitBlockCallExpr(E, ReturnValue);
2704 
2705   if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
2706     return EmitCXXMemberCallExpr(CE, ReturnValue);
2707 
2708   if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2709     return EmitCUDAKernelCallExpr(CE, ReturnValue);
2710 
2711   const Decl *TargetDecl = E->getCalleeDecl();
2712   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2713     if (unsigned builtinID = FD->getBuiltinID())
2714       return EmitBuiltinExpr(FD, builtinID, E);
2715   }
2716 
2717   if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
2718     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
2719       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
2720 
2721   if (const CXXPseudoDestructorExpr *PseudoDtor
2722           = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2723     QualType DestroyedType = PseudoDtor->getDestroyedType();
2724     if (getLangOpts().ObjCAutoRefCount &&
2725         DestroyedType->isObjCLifetimeType() &&
2726         (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2727          DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
2728       // Automatic Reference Counting:
2729       //   If the pseudo-expression names a retainable object with weak or
2730       //   strong lifetime, the object shall be released.
2731       Expr *BaseExpr = PseudoDtor->getBase();
2732       llvm::Value *BaseValue = NULL;
2733       Qualifiers BaseQuals;
2734 
2735       // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
2736       if (PseudoDtor->isArrow()) {
2737         BaseValue = EmitScalarExpr(BaseExpr);
2738         const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2739         BaseQuals = PTy->getPointeeType().getQualifiers();
2740       } else {
2741         LValue BaseLV = EmitLValue(BaseExpr);
2742         BaseValue = BaseLV.getAddress();
2743         QualType BaseTy = BaseExpr->getType();
2744         BaseQuals = BaseTy.getQualifiers();
2745       }
2746 
2747       switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2748       case Qualifiers::OCL_None:
2749       case Qualifiers::OCL_ExplicitNone:
2750       case Qualifiers::OCL_Autoreleasing:
2751         break;
2752 
2753       case Qualifiers::OCL_Strong:
2754         EmitARCRelease(Builder.CreateLoad(BaseValue,
2755                           PseudoDtor->getDestroyedType().isVolatileQualified()),
2756                        /*precise*/ true);
2757         break;
2758 
2759       case Qualifiers::OCL_Weak:
2760         EmitARCDestroyWeak(BaseValue);
2761         break;
2762       }
2763     } else {
2764       // C++ [expr.pseudo]p1:
2765       //   The result shall only be used as the operand for the function call
2766       //   operator (), and the result of such a call has type void. The only
2767       //   effect is the evaluation of the postfix-expression before the dot or
2768       //   arrow.
2769       EmitScalarExpr(E->getCallee());
2770     }
2771 
2772     return RValue::get(0);
2773   }
2774 
2775   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
2776   return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
2777                   E->arg_begin(), E->arg_end(), TargetDecl);
2778 }
2779 
2780 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
2781   // Comma expressions just emit their LHS then their RHS as an l-value.
2782   if (E->getOpcode() == BO_Comma) {
2783     EmitIgnoredExpr(E->getLHS());
2784     EnsureInsertPoint();
2785     return EmitLValue(E->getRHS());
2786   }
2787 
2788   if (E->getOpcode() == BO_PtrMemD ||
2789       E->getOpcode() == BO_PtrMemI)
2790     return EmitPointerToDataMemberBinaryExpr(E);
2791 
2792   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
2793 
2794   // Note that in all of these cases, __block variables need the RHS
2795   // evaluated first just in case the variable gets moved by the RHS.
2796 
2797   if (!hasAggregateLLVMType(E->getType())) {
2798     switch (E->getLHS()->getType().getObjCLifetime()) {
2799     case Qualifiers::OCL_Strong:
2800       return EmitARCStoreStrong(E, /*ignored*/ false).first;
2801 
2802     case Qualifiers::OCL_Autoreleasing:
2803       return EmitARCStoreAutoreleasing(E).first;
2804 
2805     // No reason to do any of these differently.
2806     case Qualifiers::OCL_None:
2807     case Qualifiers::OCL_ExplicitNone:
2808     case Qualifiers::OCL_Weak:
2809       break;
2810     }
2811 
2812     RValue RV = EmitAnyExpr(E->getRHS());
2813     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
2814     EmitStoreThroughLValue(RV, LV);
2815     return LV;
2816   }
2817 
2818   if (E->getType()->isAnyComplexType())
2819     return EmitComplexAssignmentLValue(E);
2820 
2821   return EmitAggExprToLValue(E);
2822 }
2823 
2824 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
2825   RValue RV = EmitCallExpr(E);
2826 
2827   if (!RV.isScalar())
2828     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2829 
2830   assert(E->getCallReturnType()->isReferenceType() &&
2831          "Can't have a scalar return unless the return type is a "
2832          "reference type!");
2833 
2834   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2835 }
2836 
2837 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2838   // FIXME: This shouldn't require another copy.
2839   return EmitAggExprToLValue(E);
2840 }
2841 
2842 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
2843   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2844          && "binding l-value to type which needs a temporary");
2845   AggValueSlot Slot = CreateAggTemp(E->getType());
2846   EmitCXXConstructExpr(E, Slot);
2847   return MakeAddrLValue(Slot.getAddr(), E->getType());
2848 }
2849 
2850 LValue
2851 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
2852   return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
2853 }
2854 
2855 llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
2856   return CGM.GetAddrOfUuidDescriptor(E);
2857 }
2858 
2859 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
2860   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
2861 }
2862 
2863 LValue
2864 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
2865   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2866   Slot.setExternallyDestructed();
2867   EmitAggExpr(E->getSubExpr(), Slot);
2868   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
2869   return MakeAddrLValue(Slot.getAddr(), E->getType());
2870 }
2871 
2872 LValue
2873 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
2874   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2875   EmitLambdaExpr(E, Slot);
2876   return MakeAddrLValue(Slot.getAddr(), E->getType());
2877 }
2878 
2879 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
2880   RValue RV = EmitObjCMessageExpr(E);
2881 
2882   if (!RV.isScalar())
2883     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2884 
2885   assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2886          "Can't have a scalar return unless the return type is a "
2887          "reference type!");
2888 
2889   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2890 }
2891 
2892 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2893   llvm::Value *V =
2894     CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
2895   return MakeAddrLValue(V, E->getType());
2896 }
2897 
2898 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2899                                              const ObjCIvarDecl *Ivar) {
2900   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
2901 }
2902 
2903 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2904                                           llvm::Value *BaseValue,
2905                                           const ObjCIvarDecl *Ivar,
2906                                           unsigned CVRQualifiers) {
2907   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
2908                                                    Ivar, CVRQualifiers);
2909 }
2910 
2911 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
2912   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2913   llvm::Value *BaseValue = 0;
2914   const Expr *BaseExpr = E->getBase();
2915   Qualifiers BaseQuals;
2916   QualType ObjectTy;
2917   if (E->isArrow()) {
2918     BaseValue = EmitScalarExpr(BaseExpr);
2919     ObjectTy = BaseExpr->getType()->getPointeeType();
2920     BaseQuals = ObjectTy.getQualifiers();
2921   } else {
2922     LValue BaseLV = EmitLValue(BaseExpr);
2923     // FIXME: this isn't right for bitfields.
2924     BaseValue = BaseLV.getAddress();
2925     ObjectTy = BaseExpr->getType();
2926     BaseQuals = ObjectTy.getQualifiers();
2927   }
2928 
2929   LValue LV =
2930     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2931                       BaseQuals.getCVRQualifiers());
2932   setObjCGCLValueClass(getContext(), E, LV);
2933   return LV;
2934 }
2935 
2936 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
2937   // Can only get l-value for message expression returning aggregate type
2938   RValue RV = EmitAnyExprToTemp(E);
2939   return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2940 }
2941 
2942 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
2943                                  ReturnValueSlot ReturnValue,
2944                                  CallExpr::const_arg_iterator ArgBeg,
2945                                  CallExpr::const_arg_iterator ArgEnd,
2946                                  const Decl *TargetDecl) {
2947   // Get the actual function type. The callee type will always be a pointer to
2948   // function type or a block pointer type.
2949   assert(CalleeType->isFunctionPointerType() &&
2950          "Call must have function pointer type!");
2951 
2952   CalleeType = getContext().getCanonicalType(CalleeType);
2953 
2954   const FunctionType *FnType
2955     = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
2956 
2957   CallArgList Args;
2958   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
2959 
2960   const CGFunctionInfo &FnInfo =
2961     CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
2962 
2963   // C99 6.5.2.2p6:
2964   //   If the expression that denotes the called function has a type
2965   //   that does not include a prototype, [the default argument
2966   //   promotions are performed]. If the number of arguments does not
2967   //   equal the number of parameters, the behavior is undefined. If
2968   //   the function is defined with a type that includes a prototype,
2969   //   and either the prototype ends with an ellipsis (, ...) or the
2970   //   types of the arguments after promotion are not compatible with
2971   //   the types of the parameters, the behavior is undefined. If the
2972   //   function is defined with a type that does not include a
2973   //   prototype, and the types of the arguments after promotion are
2974   //   not compatible with those of the parameters after promotion,
2975   //   the behavior is undefined [except in some trivial cases].
2976   // That is, in the general case, we should assume that a call
2977   // through an unprototyped function type works like a *non-variadic*
2978   // call.  The way we make this work is to cast to the exact type
2979   // of the promoted arguments.
2980   if (isa<FunctionNoProtoType>(FnType)) {
2981     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
2982     CalleeTy = CalleeTy->getPointerTo();
2983     Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
2984   }
2985 
2986   return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
2987 }
2988 
2989 LValue CodeGenFunction::
2990 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
2991   llvm::Value *BaseV;
2992   if (E->getOpcode() == BO_PtrMemI)
2993     BaseV = EmitScalarExpr(E->getLHS());
2994   else
2995     BaseV = EmitLValue(E->getLHS()).getAddress();
2996 
2997   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2998 
2999   const MemberPointerType *MPT
3000     = E->getRHS()->getType()->getAs<MemberPointerType>();
3001 
3002   llvm::Value *AddV =
3003     CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
3004 
3005   return MakeAddrLValue(AddV, MPT->getPointeeType());
3006 }
3007 
3008 static void
3009 EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
3010              llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
3011              uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
3012   llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
3013   llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
3014 
3015   switch (E->getOp()) {
3016   case AtomicExpr::AO__c11_atomic_init:
3017     llvm_unreachable("Already handled!");
3018 
3019   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3020   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3021   case AtomicExpr::AO__atomic_compare_exchange:
3022   case AtomicExpr::AO__atomic_compare_exchange_n: {
3023     // Note that cmpxchg only supports specifying one ordering and
3024     // doesn't support weak cmpxchg, at least at the moment.
3025     llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3026     LoadVal1->setAlignment(Align);
3027     llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
3028     LoadVal2->setAlignment(Align);
3029     llvm::AtomicCmpXchgInst *CXI =
3030         CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
3031     CXI->setVolatile(E->isVolatile());
3032     llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
3033     StoreVal1->setAlignment(Align);
3034     llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
3035     CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
3036     return;
3037   }
3038 
3039   case AtomicExpr::AO__c11_atomic_load:
3040   case AtomicExpr::AO__atomic_load_n:
3041   case AtomicExpr::AO__atomic_load: {
3042     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
3043     Load->setAtomic(Order);
3044     Load->setAlignment(Size);
3045     Load->setVolatile(E->isVolatile());
3046     llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
3047     StoreDest->setAlignment(Align);
3048     return;
3049   }
3050 
3051   case AtomicExpr::AO__c11_atomic_store:
3052   case AtomicExpr::AO__atomic_store:
3053   case AtomicExpr::AO__atomic_store_n: {
3054     assert(!Dest && "Store does not return a value");
3055     llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3056     LoadVal1->setAlignment(Align);
3057     llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
3058     Store->setAtomic(Order);
3059     Store->setAlignment(Size);
3060     Store->setVolatile(E->isVolatile());
3061     return;
3062   }
3063 
3064   case AtomicExpr::AO__c11_atomic_exchange:
3065   case AtomicExpr::AO__atomic_exchange_n:
3066   case AtomicExpr::AO__atomic_exchange:
3067     Op = llvm::AtomicRMWInst::Xchg;
3068     break;
3069 
3070   case AtomicExpr::AO__atomic_add_fetch:
3071     PostOp = llvm::Instruction::Add;
3072     // Fall through.
3073   case AtomicExpr::AO__c11_atomic_fetch_add:
3074   case AtomicExpr::AO__atomic_fetch_add:
3075     Op = llvm::AtomicRMWInst::Add;
3076     break;
3077 
3078   case AtomicExpr::AO__atomic_sub_fetch:
3079     PostOp = llvm::Instruction::Sub;
3080     // Fall through.
3081   case AtomicExpr::AO__c11_atomic_fetch_sub:
3082   case AtomicExpr::AO__atomic_fetch_sub:
3083     Op = llvm::AtomicRMWInst::Sub;
3084     break;
3085 
3086   case AtomicExpr::AO__atomic_and_fetch:
3087     PostOp = llvm::Instruction::And;
3088     // Fall through.
3089   case AtomicExpr::AO__c11_atomic_fetch_and:
3090   case AtomicExpr::AO__atomic_fetch_and:
3091     Op = llvm::AtomicRMWInst::And;
3092     break;
3093 
3094   case AtomicExpr::AO__atomic_or_fetch:
3095     PostOp = llvm::Instruction::Or;
3096     // Fall through.
3097   case AtomicExpr::AO__c11_atomic_fetch_or:
3098   case AtomicExpr::AO__atomic_fetch_or:
3099     Op = llvm::AtomicRMWInst::Or;
3100     break;
3101 
3102   case AtomicExpr::AO__atomic_xor_fetch:
3103     PostOp = llvm::Instruction::Xor;
3104     // Fall through.
3105   case AtomicExpr::AO__c11_atomic_fetch_xor:
3106   case AtomicExpr::AO__atomic_fetch_xor:
3107     Op = llvm::AtomicRMWInst::Xor;
3108     break;
3109 
3110   case AtomicExpr::AO__atomic_nand_fetch:
3111     PostOp = llvm::Instruction::And;
3112     // Fall through.
3113   case AtomicExpr::AO__atomic_fetch_nand:
3114     Op = llvm::AtomicRMWInst::Nand;
3115     break;
3116   }
3117 
3118   llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3119   LoadVal1->setAlignment(Align);
3120   llvm::AtomicRMWInst *RMWI =
3121       CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
3122   RMWI->setVolatile(E->isVolatile());
3123 
3124   // For __atomic_*_fetch operations, perform the operation again to
3125   // determine the value which was written.
3126   llvm::Value *Result = RMWI;
3127   if (PostOp)
3128     Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
3129   if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
3130     Result = CGF.Builder.CreateNot(Result);
3131   llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
3132   StoreDest->setAlignment(Align);
3133 }
3134 
3135 // This function emits any expression (scalar, complex, or aggregate)
3136 // into a temporary alloca.
3137 static llvm::Value *
3138 EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
3139   llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
3140   CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
3141                        /*Init*/ true);
3142   return DeclPtr;
3143 }
3144 
3145 static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
3146                                   llvm::Value *Dest) {
3147   if (Ty->isAnyComplexType())
3148     return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
3149   if (CGF.hasAggregateLLVMType(Ty))
3150     return RValue::getAggregate(Dest);
3151   return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
3152 }
3153 
3154 RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
3155   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
3156   QualType MemTy = AtomicTy;
3157   if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
3158     MemTy = AT->getValueType();
3159   CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
3160   uint64_t Size = sizeChars.getQuantity();
3161   CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
3162   unsigned Align = alignChars.getQuantity();
3163   unsigned MaxInlineWidthInBits =
3164     getContext().getTargetInfo().getMaxAtomicInlineWidth();
3165   bool UseLibcall = (Size != Align ||
3166                      getContext().toBits(sizeChars) > MaxInlineWidthInBits);
3167 
3168   llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
3169   Ptr = EmitScalarExpr(E->getPtr());
3170 
3171   if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
3172     assert(!Dest && "Init does not return a value");
3173     if (!hasAggregateLLVMType(E->getVal1()->getType())) {
3174       QualType PointeeType
3175         = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
3176       EmitScalarInit(EmitScalarExpr(E->getVal1()),
3177                      LValue::MakeAddr(Ptr, PointeeType, alignChars,
3178                                       getContext()));
3179     } else if (E->getType()->isAnyComplexType()) {
3180       EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
3181     } else {
3182       AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
3183                                         AtomicTy.getQualifiers(),
3184                                         AggValueSlot::IsNotDestructed,
3185                                         AggValueSlot::DoesNotNeedGCBarriers,
3186                                         AggValueSlot::IsNotAliased);
3187       EmitAggExpr(E->getVal1(), Slot);
3188     }
3189     return RValue::get(0);
3190   }
3191 
3192   Order = EmitScalarExpr(E->getOrder());
3193 
3194   switch (E->getOp()) {
3195   case AtomicExpr::AO__c11_atomic_init:
3196     llvm_unreachable("Already handled!");
3197 
3198   case AtomicExpr::AO__c11_atomic_load:
3199   case AtomicExpr::AO__atomic_load_n:
3200     break;
3201 
3202   case AtomicExpr::AO__atomic_load:
3203     Dest = EmitScalarExpr(E->getVal1());
3204     break;
3205 
3206   case AtomicExpr::AO__atomic_store:
3207     Val1 = EmitScalarExpr(E->getVal1());
3208     break;
3209 
3210   case AtomicExpr::AO__atomic_exchange:
3211     Val1 = EmitScalarExpr(E->getVal1());
3212     Dest = EmitScalarExpr(E->getVal2());
3213     break;
3214 
3215   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3216   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3217   case AtomicExpr::AO__atomic_compare_exchange_n:
3218   case AtomicExpr::AO__atomic_compare_exchange:
3219     Val1 = EmitScalarExpr(E->getVal1());
3220     if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
3221       Val2 = EmitScalarExpr(E->getVal2());
3222     else
3223       Val2 = EmitValToTemp(*this, E->getVal2());
3224     OrderFail = EmitScalarExpr(E->getOrderFail());
3225     // Evaluate and discard the 'weak' argument.
3226     if (E->getNumSubExprs() == 6)
3227       EmitScalarExpr(E->getWeak());
3228     break;
3229 
3230   case AtomicExpr::AO__c11_atomic_fetch_add:
3231   case AtomicExpr::AO__c11_atomic_fetch_sub:
3232     if (MemTy->isPointerType()) {
3233       // For pointer arithmetic, we're required to do a bit of math:
3234       // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
3235       // ... but only for the C11 builtins. The GNU builtins expect the
3236       // user to multiply by sizeof(T).
3237       QualType Val1Ty = E->getVal1()->getType();
3238       llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
3239       CharUnits PointeeIncAmt =
3240           getContext().getTypeSizeInChars(MemTy->getPointeeType());
3241       Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
3242       Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
3243       EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
3244       break;
3245     }
3246     // Fall through.
3247   case AtomicExpr::AO__atomic_fetch_add:
3248   case AtomicExpr::AO__atomic_fetch_sub:
3249   case AtomicExpr::AO__atomic_add_fetch:
3250   case AtomicExpr::AO__atomic_sub_fetch:
3251   case AtomicExpr::AO__c11_atomic_store:
3252   case AtomicExpr::AO__c11_atomic_exchange:
3253   case AtomicExpr::AO__atomic_store_n:
3254   case AtomicExpr::AO__atomic_exchange_n:
3255   case AtomicExpr::AO__c11_atomic_fetch_and:
3256   case AtomicExpr::AO__c11_atomic_fetch_or:
3257   case AtomicExpr::AO__c11_atomic_fetch_xor:
3258   case AtomicExpr::AO__atomic_fetch_and:
3259   case AtomicExpr::AO__atomic_fetch_or:
3260   case AtomicExpr::AO__atomic_fetch_xor:
3261   case AtomicExpr::AO__atomic_fetch_nand:
3262   case AtomicExpr::AO__atomic_and_fetch:
3263   case AtomicExpr::AO__atomic_or_fetch:
3264   case AtomicExpr::AO__atomic_xor_fetch:
3265   case AtomicExpr::AO__atomic_nand_fetch:
3266     Val1 = EmitValToTemp(*this, E->getVal1());
3267     break;
3268   }
3269 
3270   if (!E->getType()->isVoidType() && !Dest)
3271     Dest = CreateMemTemp(E->getType(), ".atomicdst");
3272 
3273   // Use a library call.  See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
3274   if (UseLibcall) {
3275 
3276     SmallVector<QualType, 5> Params;
3277     CallArgList Args;
3278     // Size is always the first parameter
3279     Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
3280              getContext().getSizeType());
3281     // Atomic address is always the second parameter
3282     Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
3283              getContext().VoidPtrTy);
3284 
3285     const char* LibCallName;
3286     QualType RetTy = getContext().VoidTy;
3287     switch (E->getOp()) {
3288     // There is only one libcall for compare an exchange, because there is no
3289     // optimisation benefit possible from a libcall version of a weak compare
3290     // and exchange.
3291     // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
3292     //                                void *desired, int success, int failure)
3293     case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3294     case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3295     case AtomicExpr::AO__atomic_compare_exchange:
3296     case AtomicExpr::AO__atomic_compare_exchange_n:
3297       LibCallName = "__atomic_compare_exchange";
3298       RetTy = getContext().BoolTy;
3299       Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3300                getContext().VoidPtrTy);
3301       Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
3302                getContext().VoidPtrTy);
3303       Args.add(RValue::get(Order),
3304                getContext().IntTy);
3305       Order = OrderFail;
3306       break;
3307     // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
3308     //                        int order)
3309     case AtomicExpr::AO__c11_atomic_exchange:
3310     case AtomicExpr::AO__atomic_exchange_n:
3311     case AtomicExpr::AO__atomic_exchange:
3312       LibCallName = "__atomic_exchange";
3313       Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3314                getContext().VoidPtrTy);
3315       Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3316                getContext().VoidPtrTy);
3317       break;
3318     // void __atomic_store(size_t size, void *mem, void *val, int order)
3319     case AtomicExpr::AO__c11_atomic_store:
3320     case AtomicExpr::AO__atomic_store:
3321     case AtomicExpr::AO__atomic_store_n:
3322       LibCallName = "__atomic_store";
3323       Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3324                getContext().VoidPtrTy);
3325       break;
3326     // void __atomic_load(size_t size, void *mem, void *return, int order)
3327     case AtomicExpr::AO__c11_atomic_load:
3328     case AtomicExpr::AO__atomic_load:
3329     case AtomicExpr::AO__atomic_load_n:
3330       LibCallName = "__atomic_load";
3331       Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3332                getContext().VoidPtrTy);
3333       break;
3334 #if 0
3335     // These are only defined for 1-16 byte integers.  It is not clear what
3336     // their semantics would be on anything else...
3337     case AtomicExpr::Add:   LibCallName = "__atomic_fetch_add_generic"; break;
3338     case AtomicExpr::Sub:   LibCallName = "__atomic_fetch_sub_generic"; break;
3339     case AtomicExpr::And:   LibCallName = "__atomic_fetch_and_generic"; break;
3340     case AtomicExpr::Or:    LibCallName = "__atomic_fetch_or_generic"; break;
3341     case AtomicExpr::Xor:   LibCallName = "__atomic_fetch_xor_generic"; break;
3342 #endif
3343     default: return EmitUnsupportedRValue(E, "atomic library call");
3344     }
3345     // order is always the last parameter
3346     Args.add(RValue::get(Order),
3347              getContext().IntTy);
3348 
3349     const CGFunctionInfo &FuncInfo =
3350         CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args,
3351             FunctionType::ExtInfo(), RequiredArgs::All);
3352     llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
3353     llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3354     RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3355     if (E->isCmpXChg())
3356       return Res;
3357     if (E->getType()->isVoidType())
3358       return RValue::get(0);
3359     return ConvertTempToRValue(*this, E->getType(), Dest);
3360   }
3361 
3362   bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3363                  E->getOp() == AtomicExpr::AO__atomic_store ||
3364                  E->getOp() == AtomicExpr::AO__atomic_store_n;
3365   bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3366                 E->getOp() == AtomicExpr::AO__atomic_load ||
3367                 E->getOp() == AtomicExpr::AO__atomic_load_n;
3368 
3369   llvm::Type *IPtrTy =
3370       llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3371   llvm::Value *OrigDest = Dest;
3372   Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3373   if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3374   if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3375   if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3376 
3377   if (isa<llvm::ConstantInt>(Order)) {
3378     int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3379     switch (ord) {
3380     case 0:  // memory_order_relaxed
3381       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3382                    llvm::Monotonic);
3383       break;
3384     case 1:  // memory_order_consume
3385     case 2:  // memory_order_acquire
3386       if (IsStore)
3387         break; // Avoid crashing on code with undefined behavior
3388       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3389                    llvm::Acquire);
3390       break;
3391     case 3:  // memory_order_release
3392       if (IsLoad)
3393         break; // Avoid crashing on code with undefined behavior
3394       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3395                    llvm::Release);
3396       break;
3397     case 4:  // memory_order_acq_rel
3398       if (IsLoad || IsStore)
3399         break; // Avoid crashing on code with undefined behavior
3400       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3401                    llvm::AcquireRelease);
3402       break;
3403     case 5:  // memory_order_seq_cst
3404       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3405                    llvm::SequentiallyConsistent);
3406       break;
3407     default: // invalid order
3408       // We should not ever get here normally, but it's hard to
3409       // enforce that in general.
3410       break;
3411     }
3412     if (E->getType()->isVoidType())
3413       return RValue::get(0);
3414     return ConvertTempToRValue(*this, E->getType(), OrigDest);
3415   }
3416 
3417   // Long case, when Order isn't obviously constant.
3418 
3419   // Create all the relevant BB's
3420   llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3421                    *AcqRelBB = 0, *SeqCstBB = 0;
3422   MonotonicBB = createBasicBlock("monotonic", CurFn);
3423   if (!IsStore)
3424     AcquireBB = createBasicBlock("acquire", CurFn);
3425   if (!IsLoad)
3426     ReleaseBB = createBasicBlock("release", CurFn);
3427   if (!IsLoad && !IsStore)
3428     AcqRelBB = createBasicBlock("acqrel", CurFn);
3429   SeqCstBB = createBasicBlock("seqcst", CurFn);
3430   llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3431 
3432   // Create the switch for the split
3433   // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3434   // doesn't matter unless someone is crazy enough to use something that
3435   // doesn't fold to a constant for the ordering.
3436   Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3437   llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3438 
3439   // Emit all the different atomics
3440   Builder.SetInsertPoint(MonotonicBB);
3441   EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3442                llvm::Monotonic);
3443   Builder.CreateBr(ContBB);
3444   if (!IsStore) {
3445     Builder.SetInsertPoint(AcquireBB);
3446     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3447                  llvm::Acquire);
3448     Builder.CreateBr(ContBB);
3449     SI->addCase(Builder.getInt32(1), AcquireBB);
3450     SI->addCase(Builder.getInt32(2), AcquireBB);
3451   }
3452   if (!IsLoad) {
3453     Builder.SetInsertPoint(ReleaseBB);
3454     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3455                  llvm::Release);
3456     Builder.CreateBr(ContBB);
3457     SI->addCase(Builder.getInt32(3), ReleaseBB);
3458   }
3459   if (!IsLoad && !IsStore) {
3460     Builder.SetInsertPoint(AcqRelBB);
3461     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3462                  llvm::AcquireRelease);
3463     Builder.CreateBr(ContBB);
3464     SI->addCase(Builder.getInt32(4), AcqRelBB);
3465   }
3466   Builder.SetInsertPoint(SeqCstBB);
3467   EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3468                llvm::SequentiallyConsistent);
3469   Builder.CreateBr(ContBB);
3470   SI->addCase(Builder.getInt32(5), SeqCstBB);
3471 
3472   // Cleanup and return
3473   Builder.SetInsertPoint(ContBB);
3474   if (E->getType()->isVoidType())
3475     return RValue::get(0);
3476   return ConvertTempToRValue(*this, E->getType(), OrigDest);
3477 }
3478 
3479 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
3480   assert(Val->getType()->isFPOrFPVectorTy());
3481   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
3482     return;
3483 
3484   llvm::MDBuilder MDHelper(getLLVMContext());
3485   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
3486 
3487   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
3488 }
3489 
3490 namespace {
3491   struct LValueOrRValue {
3492     LValue LV;
3493     RValue RV;
3494   };
3495 }
3496 
3497 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3498                                            const PseudoObjectExpr *E,
3499                                            bool forLValue,
3500                                            AggValueSlot slot) {
3501   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3502 
3503   // Find the result expression, if any.
3504   const Expr *resultExpr = E->getResultExpr();
3505   LValueOrRValue result;
3506 
3507   for (PseudoObjectExpr::const_semantics_iterator
3508          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3509     const Expr *semantic = *i;
3510 
3511     // If this semantic expression is an opaque value, bind it
3512     // to the result of its source expression.
3513     if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3514 
3515       // If this is the result expression, we may need to evaluate
3516       // directly into the slot.
3517       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3518       OVMA opaqueData;
3519       if (ov == resultExpr && ov->isRValue() && !forLValue &&
3520           CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3521           !ov->getType()->isAnyComplexType()) {
3522         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3523 
3524         LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3525         opaqueData = OVMA::bind(CGF, ov, LV);
3526         result.RV = slot.asRValue();
3527 
3528       // Otherwise, emit as normal.
3529       } else {
3530         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3531 
3532         // If this is the result, also evaluate the result now.
3533         if (ov == resultExpr) {
3534           if (forLValue)
3535             result.LV = CGF.EmitLValue(ov);
3536           else
3537             result.RV = CGF.EmitAnyExpr(ov, slot);
3538         }
3539       }
3540 
3541       opaques.push_back(opaqueData);
3542 
3543     // Otherwise, if the expression is the result, evaluate it
3544     // and remember the result.
3545     } else if (semantic == resultExpr) {
3546       if (forLValue)
3547         result.LV = CGF.EmitLValue(semantic);
3548       else
3549         result.RV = CGF.EmitAnyExpr(semantic, slot);
3550 
3551     // Otherwise, evaluate the expression in an ignored context.
3552     } else {
3553       CGF.EmitIgnoredExpr(semantic);
3554     }
3555   }
3556 
3557   // Unbind all the opaques now.
3558   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3559     opaques[i].unbind(CGF);
3560 
3561   return result;
3562 }
3563 
3564 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3565                                                AggValueSlot slot) {
3566   return emitPseudoObjectExpr(*this, E, false, slot).RV;
3567 }
3568 
3569 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3570   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3571 }
3572