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