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