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