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