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