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