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