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