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