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