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