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