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