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