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