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