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