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