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