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