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 "CodeGenFunction.h"
15 #include "CGCXXABI.h"
16 #include "CGCall.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "CGRecordLayout.h"
20 #include "CodeGenModule.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/Frontend/CodeGenOptions.h"
26 #include "llvm/ADT/Hashing.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/MDBuilder.h"
32 #include "llvm/Support/ConvertUTF.h"
33 
34 using namespace clang;
35 using namespace CodeGen;
36 
37 //===--------------------------------------------------------------------===//
38 //                        Miscellaneous Helper Methods
39 //===--------------------------------------------------------------------===//
40 
41 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
42   unsigned addressSpace =
43     cast<llvm::PointerType>(value->getType())->getAddressSpace();
44 
45   llvm::PointerType *destType = Int8PtrTy;
46   if (addressSpace)
47     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
48 
49   if (value->getType() == destType) return value;
50   return Builder.CreateBitCast(value, destType);
51 }
52 
53 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
54 /// block.
55 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
56                                                     const Twine &Name) {
57   if (!Builder.isNamePreserving())
58     return new llvm::AllocaInst(Ty, nullptr, "", AllocaInsertPt);
59   return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
60 }
61 
62 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
63                                      llvm::Value *Init) {
64   auto *Store = new llvm::StoreInst(Init, Var);
65   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
66   Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
67 }
68 
69 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
70                                                 const Twine &Name) {
71   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
72   // FIXME: Should we prefer the preferred type alignment here?
73   CharUnits Align = getContext().getTypeAlignInChars(Ty);
74   Alloc->setAlignment(Align.getQuantity());
75   return Alloc;
76 }
77 
78 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
79                                                  const Twine &Name) {
80   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
81   // FIXME: Should we prefer the preferred type alignment here?
82   CharUnits Align = getContext().getTypeAlignInChars(Ty);
83   Alloc->setAlignment(Align.getQuantity());
84   return Alloc;
85 }
86 
87 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
88 /// expression and compare the result against zero, returning an Int1Ty value.
89 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
90   PGO.setCurrentStmt(E);
91   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
92     llvm::Value *MemPtr = EmitScalarExpr(E);
93     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
94   }
95 
96   QualType BoolTy = getContext().BoolTy;
97   if (!E->getType()->isAnyComplexType())
98     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
99 
100   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
101 }
102 
103 /// EmitIgnoredExpr - Emit code to compute the specified expression,
104 /// ignoring the result.
105 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
106   if (E->isRValue())
107     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
108 
109   // Just emit it as an l-value and drop the result.
110   EmitLValue(E);
111 }
112 
113 /// EmitAnyExpr - Emit code to compute the specified expression which
114 /// can have any type.  The result is returned as an RValue struct.
115 /// If this is an aggregate expression, AggSlot indicates where the
116 /// result should be returned.
117 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
118                                     AggValueSlot aggSlot,
119                                     bool ignoreResult) {
120   switch (getEvaluationKind(E->getType())) {
121   case TEK_Scalar:
122     return RValue::get(EmitScalarExpr(E, ignoreResult));
123   case TEK_Complex:
124     return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
125   case TEK_Aggregate:
126     if (!ignoreResult && aggSlot.isIgnored())
127       aggSlot = CreateAggTemp(E->getType(), "agg-temp");
128     EmitAggExpr(E, aggSlot);
129     return aggSlot.asRValue();
130   }
131   llvm_unreachable("bad evaluation kind");
132 }
133 
134 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
135 /// always be accessible even if no aggregate location is provided.
136 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
137   AggValueSlot AggSlot = AggValueSlot::ignored();
138 
139   if (hasAggregateEvaluationKind(E->getType()))
140     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
141   return EmitAnyExpr(E, AggSlot);
142 }
143 
144 /// EmitAnyExprToMem - Evaluate an expression into a given memory
145 /// location.
146 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
147                                        llvm::Value *Location,
148                                        Qualifiers Quals,
149                                        bool IsInit) {
150   // FIXME: This function should take an LValue as an argument.
151   switch (getEvaluationKind(E->getType())) {
152   case TEK_Complex:
153     EmitComplexExprIntoLValue(E,
154                          MakeNaturalAlignAddrLValue(Location, E->getType()),
155                               /*isInit*/ false);
156     return;
157 
158   case TEK_Aggregate: {
159     CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
160     EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
161                                          AggValueSlot::IsDestructed_t(IsInit),
162                                          AggValueSlot::DoesNotNeedGCBarriers,
163                                          AggValueSlot::IsAliased_t(!IsInit)));
164     return;
165   }
166 
167   case TEK_Scalar: {
168     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
169     LValue LV = MakeAddrLValue(Location, E->getType());
170     EmitStoreThroughLValue(RV, LV);
171     return;
172   }
173   }
174   llvm_unreachable("bad evaluation kind");
175 }
176 
177 static void
178 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
179                      const Expr *E, llvm::Value *ReferenceTemporary) {
180   // Objective-C++ ARC:
181   //   If we are binding a reference to a temporary that has ownership, we
182   //   need to perform retain/release operations on the temporary.
183   //
184   // FIXME: This should be looking at E, not M.
185   if (CGF.getLangOpts().ObjCAutoRefCount &&
186       M->getType()->isObjCLifetimeType()) {
187     QualType ObjCARCReferenceLifetimeType = M->getType();
188     switch (Qualifiers::ObjCLifetime Lifetime =
189                 ObjCARCReferenceLifetimeType.getObjCLifetime()) {
190     case Qualifiers::OCL_None:
191     case Qualifiers::OCL_ExplicitNone:
192       // Carry on to normal cleanup handling.
193       break;
194 
195     case Qualifiers::OCL_Autoreleasing:
196       // Nothing to do; cleaned up by an autorelease pool.
197       return;
198 
199     case Qualifiers::OCL_Strong:
200     case Qualifiers::OCL_Weak:
201       switch (StorageDuration Duration = M->getStorageDuration()) {
202       case SD_Static:
203         // Note: we intentionally do not register a cleanup to release
204         // the object on program termination.
205         return;
206 
207       case SD_Thread:
208         // FIXME: We should probably register a cleanup in this case.
209         return;
210 
211       case SD_Automatic:
212       case SD_FullExpression:
213         assert(!ObjCARCReferenceLifetimeType->isArrayType());
214         CodeGenFunction::Destroyer *Destroy;
215         CleanupKind CleanupKind;
216         if (Lifetime == Qualifiers::OCL_Strong) {
217           const ValueDecl *VD = M->getExtendingDecl();
218           bool Precise =
219               VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
220           CleanupKind = CGF.getARCCleanupKind();
221           Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
222                             : &CodeGenFunction::destroyARCStrongImprecise;
223         } else {
224           // __weak objects always get EH cleanups; otherwise, exceptions
225           // could cause really nasty crashes instead of mere leaks.
226           CleanupKind = NormalAndEHCleanup;
227           Destroy = &CodeGenFunction::destroyARCWeak;
228         }
229         if (Duration == SD_FullExpression)
230           CGF.pushDestroy(CleanupKind, ReferenceTemporary,
231                           ObjCARCReferenceLifetimeType, *Destroy,
232                           CleanupKind & EHCleanup);
233         else
234           CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
235                                           ObjCARCReferenceLifetimeType,
236                                           *Destroy, CleanupKind & EHCleanup);
237         return;
238 
239       case SD_Dynamic:
240         llvm_unreachable("temporary cannot have dynamic storage duration");
241       }
242       llvm_unreachable("unknown storage duration");
243     }
244   }
245 
246   CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
247   if (const RecordType *RT =
248           E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
249     // Get the destructor for the reference temporary.
250     auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
251     if (!ClassDecl->hasTrivialDestructor())
252       ReferenceTemporaryDtor = ClassDecl->getDestructor();
253   }
254 
255   if (!ReferenceTemporaryDtor)
256     return;
257 
258   // Call the destructor for the temporary.
259   switch (M->getStorageDuration()) {
260   case SD_Static:
261   case SD_Thread: {
262     llvm::Constant *CleanupFn;
263     llvm::Constant *CleanupArg;
264     if (E->getType()->isArrayType()) {
265       CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
266           cast<llvm::Constant>(ReferenceTemporary), E->getType(),
267           CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
268           dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
269       CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
270     } else {
271       CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
272                                                StructorType::Complete);
273       CleanupArg = cast<llvm::Constant>(ReferenceTemporary);
274     }
275     CGF.CGM.getCXXABI().registerGlobalDtor(
276         CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
277     break;
278   }
279 
280   case SD_FullExpression:
281     CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
282                     CodeGenFunction::destroyCXXObject,
283                     CGF.getLangOpts().Exceptions);
284     break;
285 
286   case SD_Automatic:
287     CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
288                                     ReferenceTemporary, E->getType(),
289                                     CodeGenFunction::destroyCXXObject,
290                                     CGF.getLangOpts().Exceptions);
291     break;
292 
293   case SD_Dynamic:
294     llvm_unreachable("temporary cannot have dynamic storage duration");
295   }
296 }
297 
298 static llvm::Value *
299 createReferenceTemporary(CodeGenFunction &CGF,
300                          const MaterializeTemporaryExpr *M, const Expr *Inner) {
301   switch (M->getStorageDuration()) {
302   case SD_FullExpression:
303   case SD_Automatic:
304     return CGF.CreateMemTemp(Inner->getType(), "ref.tmp");
305 
306   case SD_Thread:
307   case SD_Static:
308     return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
309 
310   case SD_Dynamic:
311     llvm_unreachable("temporary can't have dynamic storage duration");
312   }
313   llvm_unreachable("unknown storage duration");
314 }
315 
316 LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
317                                            const MaterializeTemporaryExpr *M) {
318   const Expr *E = M->GetTemporaryExpr();
319 
320   if (getLangOpts().ObjCAutoRefCount &&
321       M->getType()->isObjCLifetimeType() &&
322       M->getType().getObjCLifetime() != Qualifiers::OCL_None &&
323       M->getType().getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
324     // FIXME: Fold this into the general case below.
325     llvm::Value *Object = createReferenceTemporary(*this, M, E);
326     LValue RefTempDst = MakeAddrLValue(Object, M->getType());
327 
328     if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
329       // We should not have emitted the initializer for this temporary as a
330       // constant.
331       assert(!Var->hasInitializer());
332       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
333     }
334 
335     EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
336 
337     pushTemporaryCleanup(*this, M, E, Object);
338     return RefTempDst;
339   }
340 
341   SmallVector<const Expr *, 2> CommaLHSs;
342   SmallVector<SubobjectAdjustment, 2> Adjustments;
343   E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
344 
345   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
346     EmitIgnoredExpr(CommaLHSs[I]);
347 
348   if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
349     if (opaque->getType()->isRecordType()) {
350       assert(Adjustments.empty());
351       return EmitOpaqueValueLValue(opaque);
352     }
353   }
354 
355   // Create and initialize the reference temporary.
356   llvm::Value *Object = createReferenceTemporary(*this, M, E);
357   if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
358     // If the temporary is a global and has a constant initializer, we may
359     // have already initialized it.
360     if (!Var->hasInitializer()) {
361       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
362       EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
363     }
364   } else {
365     EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
366   }
367   pushTemporaryCleanup(*this, M, E, Object);
368 
369   // Perform derived-to-base casts and/or field accesses, to get from the
370   // temporary object we created (and, potentially, for which we extended
371   // the lifetime) to the subobject we're binding the reference to.
372   for (unsigned I = Adjustments.size(); I != 0; --I) {
373     SubobjectAdjustment &Adjustment = Adjustments[I-1];
374     switch (Adjustment.Kind) {
375     case SubobjectAdjustment::DerivedToBaseAdjustment:
376       Object =
377           GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
378                                 Adjustment.DerivedToBase.BasePath->path_begin(),
379                                 Adjustment.DerivedToBase.BasePath->path_end(),
380                                 /*NullCheckValue=*/ false, E->getExprLoc());
381       break;
382 
383     case SubobjectAdjustment::FieldAdjustment: {
384       LValue LV = MakeAddrLValue(Object, E->getType());
385       LV = EmitLValueForField(LV, Adjustment.Field);
386       assert(LV.isSimple() &&
387              "materialized temporary field is not a simple lvalue");
388       Object = LV.getAddress();
389       break;
390     }
391 
392     case SubobjectAdjustment::MemberPointerAdjustment: {
393       llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
394       Object = CGM.getCXXABI().EmitMemberDataPointerAddress(
395           *this, E, Object, Ptr, Adjustment.Ptr.MPT);
396       break;
397     }
398     }
399   }
400 
401   return MakeAddrLValue(Object, M->getType());
402 }
403 
404 RValue
405 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
406   // Emit the expression as an lvalue.
407   LValue LV = EmitLValue(E);
408   assert(LV.isSimple());
409   llvm::Value *Value = LV.getAddress();
410 
411   if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
412     // C++11 [dcl.ref]p5 (as amended by core issue 453):
413     //   If a glvalue to which a reference is directly bound designates neither
414     //   an existing object or function of an appropriate type nor a region of
415     //   storage of suitable size and alignment to contain an object of the
416     //   reference's type, the behavior is undefined.
417     QualType Ty = E->getType();
418     EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
419   }
420 
421   return RValue::get(Value);
422 }
423 
424 
425 /// getAccessedFieldNo - Given an encoded value and a result number, return the
426 /// input field number being accessed.
427 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
428                                              const llvm::Constant *Elts) {
429   return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
430       ->getZExtValue();
431 }
432 
433 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
434 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
435                                     llvm::Value *High) {
436   llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
437   llvm::Value *K47 = Builder.getInt64(47);
438   llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
439   llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
440   llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
441   llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
442   return Builder.CreateMul(B1, KMul);
443 }
444 
445 bool CodeGenFunction::sanitizePerformTypeCheck() const {
446   return SanOpts->Null | SanOpts->Alignment | SanOpts->ObjectSize |
447          SanOpts->Vptr;
448 }
449 
450 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
451                                     llvm::Value *Address, QualType Ty,
452                                     CharUnits Alignment, bool SkipNullCheck) {
453   if (!sanitizePerformTypeCheck())
454     return;
455 
456   // Don't check pointers outside the default address space. The null check
457   // isn't correct, the object-size check isn't supported by LLVM, and we can't
458   // communicate the addresses to the runtime handler for the vptr check.
459   if (Address->getType()->getPointerAddressSpace())
460     return;
461 
462   SanitizerScope SanScope(this);
463 
464   llvm::Value *Cond = nullptr;
465   llvm::BasicBlock *Done = nullptr;
466 
467   bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
468                            TCK == TCK_UpcastToVirtualBase;
469   if ((SanOpts->Null || AllowNullPointers) && !SkipNullCheck) {
470     // The glvalue must not be an empty glvalue.
471     Cond = Builder.CreateICmpNE(
472         Address, llvm::Constant::getNullValue(Address->getType()));
473 
474     if (AllowNullPointers) {
475       // When performing pointer casts, it's OK if the value is null.
476       // Skip the remaining checks in that case.
477       Done = createBasicBlock("null");
478       llvm::BasicBlock *Rest = createBasicBlock("not.null");
479       Builder.CreateCondBr(Cond, Rest, Done);
480       EmitBlock(Rest);
481       Cond = nullptr;
482     }
483   }
484 
485   if (SanOpts->ObjectSize && !Ty->isIncompleteType()) {
486     uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
487 
488     // The glvalue must refer to a large enough storage region.
489     // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
490     //        to check this.
491     // FIXME: Get object address space
492     llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
493     llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
494     llvm::Value *Min = Builder.getFalse();
495     llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
496     llvm::Value *LargeEnough =
497         Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min),
498                               llvm::ConstantInt::get(IntPtrTy, Size));
499     Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough;
500   }
501 
502   uint64_t AlignVal = 0;
503 
504   if (SanOpts->Alignment) {
505     AlignVal = Alignment.getQuantity();
506     if (!Ty->isIncompleteType() && !AlignVal)
507       AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
508 
509     // The glvalue must be suitably aligned.
510     if (AlignVal) {
511       llvm::Value *Align =
512           Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
513                             llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
514       llvm::Value *Aligned =
515         Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
516       Cond = Cond ? Builder.CreateAnd(Cond, Aligned) : Aligned;
517     }
518   }
519 
520   if (Cond) {
521     llvm::Constant *StaticData[] = {
522       EmitCheckSourceLocation(Loc),
523       EmitCheckTypeDescriptor(Ty),
524       llvm::ConstantInt::get(SizeTy, AlignVal),
525       llvm::ConstantInt::get(Int8Ty, TCK)
526     };
527     EmitCheck(Cond, "type_mismatch", StaticData, Address, CRK_Recoverable);
528   }
529 
530   // If possible, check that the vptr indicates that there is a subobject of
531   // type Ty at offset zero within this object.
532   //
533   // C++11 [basic.life]p5,6:
534   //   [For storage which does not refer to an object within its lifetime]
535   //   The program has undefined behavior if:
536   //    -- the [pointer or glvalue] is used to access a non-static data member
537   //       or call a non-static member function
538   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
539   if (SanOpts->Vptr &&
540       (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
541        TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
542        TCK == TCK_UpcastToVirtualBase) &&
543       RD && RD->hasDefinition() && RD->isDynamicClass()) {
544     // Compute a hash of the mangled name of the type.
545     //
546     // FIXME: This is not guaranteed to be deterministic! Move to a
547     //        fingerprinting mechanism once LLVM provides one. For the time
548     //        being the implementation happens to be deterministic.
549     SmallString<64> MangledName;
550     llvm::raw_svector_ostream Out(MangledName);
551     CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
552                                                      Out);
553 
554     // Blacklist based on the mangled type.
555     if (!CGM.getSanitizerBlacklist().isBlacklistedType(Out.str())) {
556       llvm::hash_code TypeHash = hash_value(Out.str());
557 
558       // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
559       llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
560       llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
561       llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
562       llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
563       llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
564 
565       llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
566       Hash = Builder.CreateTrunc(Hash, IntPtrTy);
567 
568       // Look the hash up in our cache.
569       const int CacheSize = 128;
570       llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
571       llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
572                                                      "__ubsan_vptr_type_cache");
573       llvm::Value *Slot = Builder.CreateAnd(Hash,
574                                             llvm::ConstantInt::get(IntPtrTy,
575                                                                    CacheSize-1));
576       llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
577       llvm::Value *CacheVal =
578         Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
579 
580       // If the hash isn't in the cache, call a runtime handler to perform the
581       // hard work of checking whether the vptr is for an object of the right
582       // type. This will either fill in the cache and return, or produce a
583       // diagnostic.
584       llvm::Constant *StaticData[] = {
585         EmitCheckSourceLocation(Loc),
586         EmitCheckTypeDescriptor(Ty),
587         CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
588         llvm::ConstantInt::get(Int8Ty, TCK)
589       };
590       llvm::Value *DynamicData[] = { Address, Hash };
591       EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash),
592                 "dynamic_type_cache_miss", StaticData, DynamicData,
593                 CRK_AlwaysRecoverable);
594     }
595   }
596 
597   if (Done) {
598     Builder.CreateBr(Done);
599     EmitBlock(Done);
600   }
601 }
602 
603 /// Determine whether this expression refers to a flexible array member in a
604 /// struct. We disable array bounds checks for such members.
605 static bool isFlexibleArrayMemberExpr(const Expr *E) {
606   // For compatibility with existing code, we treat arrays of length 0 or
607   // 1 as flexible array members.
608   const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
609   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
610     if (CAT->getSize().ugt(1))
611       return false;
612   } else if (!isa<IncompleteArrayType>(AT))
613     return false;
614 
615   E = E->IgnoreParens();
616 
617   // A flexible array member must be the last member in the class.
618   if (const auto *ME = dyn_cast<MemberExpr>(E)) {
619     // FIXME: If the base type of the member expr is not FD->getParent(),
620     // this should not be treated as a flexible array member access.
621     if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
622       RecordDecl::field_iterator FI(
623           DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
624       return ++FI == FD->getParent()->field_end();
625     }
626   }
627 
628   return false;
629 }
630 
631 /// If Base is known to point to the start of an array, return the length of
632 /// that array. Return 0 if the length cannot be determined.
633 static llvm::Value *getArrayIndexingBound(
634     CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
635   // For the vector indexing extension, the bound is the number of elements.
636   if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
637     IndexedType = Base->getType();
638     return CGF.Builder.getInt32(VT->getNumElements());
639   }
640 
641   Base = Base->IgnoreParens();
642 
643   if (const auto *CE = dyn_cast<CastExpr>(Base)) {
644     if (CE->getCastKind() == CK_ArrayToPointerDecay &&
645         !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
646       IndexedType = CE->getSubExpr()->getType();
647       const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
648       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
649         return CGF.Builder.getInt(CAT->getSize());
650       else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
651         return CGF.getVLASize(VAT).first;
652     }
653   }
654 
655   return nullptr;
656 }
657 
658 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
659                                       llvm::Value *Index, QualType IndexType,
660                                       bool Accessed) {
661   assert(SanOpts->ArrayBounds &&
662          "should not be called unless adding bounds checks");
663   SanitizerScope SanScope(this);
664 
665   QualType IndexedType;
666   llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
667   if (!Bound)
668     return;
669 
670   bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
671   llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
672   llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
673 
674   llvm::Constant *StaticData[] = {
675     EmitCheckSourceLocation(E->getExprLoc()),
676     EmitCheckTypeDescriptor(IndexedType),
677     EmitCheckTypeDescriptor(IndexType)
678   };
679   llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
680                                 : Builder.CreateICmpULE(IndexVal, BoundVal);
681   EmitCheck(Check, "out_of_bounds", StaticData, Index, CRK_Recoverable);
682 }
683 
684 
685 CodeGenFunction::ComplexPairTy CodeGenFunction::
686 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
687                          bool isInc, bool isPre) {
688   ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
689 
690   llvm::Value *NextVal;
691   if (isa<llvm::IntegerType>(InVal.first->getType())) {
692     uint64_t AmountVal = isInc ? 1 : -1;
693     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
694 
695     // Add the inc/dec to the real part.
696     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
697   } else {
698     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
699     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
700     if (!isInc)
701       FVal.changeSign();
702     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
703 
704     // Add the inc/dec to the real part.
705     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
706   }
707 
708   ComplexPairTy IncVal(NextVal, InVal.second);
709 
710   // Store the updated result through the lvalue.
711   EmitStoreOfComplex(IncVal, LV, /*init*/ false);
712 
713   // If this is a postinc, return the value read from memory, otherwise use the
714   // updated value.
715   return isPre ? IncVal : InVal;
716 }
717 
718 //===----------------------------------------------------------------------===//
719 //                         LValue Expression Emission
720 //===----------------------------------------------------------------------===//
721 
722 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
723   if (Ty->isVoidType())
724     return RValue::get(nullptr);
725 
726   switch (getEvaluationKind(Ty)) {
727   case TEK_Complex: {
728     llvm::Type *EltTy =
729       ConvertType(Ty->castAs<ComplexType>()->getElementType());
730     llvm::Value *U = llvm::UndefValue::get(EltTy);
731     return RValue::getComplex(std::make_pair(U, U));
732   }
733 
734   // If this is a use of an undefined aggregate type, the aggregate must have an
735   // identifiable address.  Just because the contents of the value are undefined
736   // doesn't mean that the address can't be taken and compared.
737   case TEK_Aggregate: {
738     llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
739     return RValue::getAggregate(DestPtr);
740   }
741 
742   case TEK_Scalar:
743     return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
744   }
745   llvm_unreachable("bad evaluation kind");
746 }
747 
748 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
749                                               const char *Name) {
750   ErrorUnsupported(E, Name);
751   return GetUndefRValue(E->getType());
752 }
753 
754 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
755                                               const char *Name) {
756   ErrorUnsupported(E, Name);
757   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
758   return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
759 }
760 
761 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
762   LValue LV;
763   if (SanOpts->ArrayBounds && isa<ArraySubscriptExpr>(E))
764     LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
765   else
766     LV = EmitLValue(E);
767   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
768     EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
769                   E->getType(), LV.getAlignment());
770   return LV;
771 }
772 
773 /// EmitLValue - Emit code to compute a designator that specifies the location
774 /// of the expression.
775 ///
776 /// This can return one of two things: a simple address or a bitfield reference.
777 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
778 /// an LLVM pointer type.
779 ///
780 /// If this returns a bitfield reference, nothing about the pointee type of the
781 /// LLVM value is known: For example, it may not be a pointer to an integer.
782 ///
783 /// If this returns a normal address, and if the lvalue's C type is fixed size,
784 /// this method guarantees that the returned pointer type will point to an LLVM
785 /// type of the same size of the lvalue's type.  If the lvalue has a variable
786 /// length type, this is not possible.
787 ///
788 LValue CodeGenFunction::EmitLValue(const Expr *E) {
789   switch (E->getStmtClass()) {
790   default: return EmitUnsupportedLValue(E, "l-value expression");
791 
792   case Expr::ObjCPropertyRefExprClass:
793     llvm_unreachable("cannot emit a property reference directly");
794 
795   case Expr::ObjCSelectorExprClass:
796     return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
797   case Expr::ObjCIsaExprClass:
798     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
799   case Expr::BinaryOperatorClass:
800     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
801   case Expr::CompoundAssignOperatorClass:
802     if (!E->getType()->isAnyComplexType())
803       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
804     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
805   case Expr::CallExprClass:
806   case Expr::CXXMemberCallExprClass:
807   case Expr::CXXOperatorCallExprClass:
808   case Expr::UserDefinedLiteralClass:
809     return EmitCallExprLValue(cast<CallExpr>(E));
810   case Expr::VAArgExprClass:
811     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
812   case Expr::DeclRefExprClass:
813     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
814   case Expr::ParenExprClass:
815     return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
816   case Expr::GenericSelectionExprClass:
817     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
818   case Expr::PredefinedExprClass:
819     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
820   case Expr::StringLiteralClass:
821     return EmitStringLiteralLValue(cast<StringLiteral>(E));
822   case Expr::ObjCEncodeExprClass:
823     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
824   case Expr::PseudoObjectExprClass:
825     return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
826   case Expr::InitListExprClass:
827     return EmitInitListLValue(cast<InitListExpr>(E));
828   case Expr::CXXTemporaryObjectExprClass:
829   case Expr::CXXConstructExprClass:
830     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
831   case Expr::CXXBindTemporaryExprClass:
832     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
833   case Expr::CXXUuidofExprClass:
834     return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
835   case Expr::LambdaExprClass:
836     return EmitLambdaLValue(cast<LambdaExpr>(E));
837 
838   case Expr::ExprWithCleanupsClass: {
839     const auto *cleanups = cast<ExprWithCleanups>(E);
840     enterFullExpression(cleanups);
841     RunCleanupsScope Scope(*this);
842     return EmitLValue(cleanups->getSubExpr());
843   }
844 
845   case Expr::CXXDefaultArgExprClass:
846     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
847   case Expr::CXXDefaultInitExprClass: {
848     CXXDefaultInitExprScope Scope(*this);
849     return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
850   }
851   case Expr::CXXTypeidExprClass:
852     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
853 
854   case Expr::ObjCMessageExprClass:
855     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
856   case Expr::ObjCIvarRefExprClass:
857     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
858   case Expr::StmtExprClass:
859     return EmitStmtExprLValue(cast<StmtExpr>(E));
860   case Expr::UnaryOperatorClass:
861     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
862   case Expr::ArraySubscriptExprClass:
863     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
864   case Expr::ExtVectorElementExprClass:
865     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
866   case Expr::MemberExprClass:
867     return EmitMemberExpr(cast<MemberExpr>(E));
868   case Expr::CompoundLiteralExprClass:
869     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
870   case Expr::ConditionalOperatorClass:
871     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
872   case Expr::BinaryConditionalOperatorClass:
873     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
874   case Expr::ChooseExprClass:
875     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
876   case Expr::OpaqueValueExprClass:
877     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
878   case Expr::SubstNonTypeTemplateParmExprClass:
879     return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
880   case Expr::ImplicitCastExprClass:
881   case Expr::CStyleCastExprClass:
882   case Expr::CXXFunctionalCastExprClass:
883   case Expr::CXXStaticCastExprClass:
884   case Expr::CXXDynamicCastExprClass:
885   case Expr::CXXReinterpretCastExprClass:
886   case Expr::CXXConstCastExprClass:
887   case Expr::ObjCBridgedCastExprClass:
888     return EmitCastLValue(cast<CastExpr>(E));
889 
890   case Expr::MaterializeTemporaryExprClass:
891     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
892   }
893 }
894 
895 /// Given an object of the given canonical type, can we safely copy a
896 /// value out of it based on its initializer?
897 static bool isConstantEmittableObjectType(QualType type) {
898   assert(type.isCanonical());
899   assert(!type->isReferenceType());
900 
901   // Must be const-qualified but non-volatile.
902   Qualifiers qs = type.getLocalQualifiers();
903   if (!qs.hasConst() || qs.hasVolatile()) return false;
904 
905   // Otherwise, all object types satisfy this except C++ classes with
906   // mutable subobjects or non-trivial copy/destroy behavior.
907   if (const auto *RT = dyn_cast<RecordType>(type))
908     if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
909       if (RD->hasMutableFields() || !RD->isTrivial())
910         return false;
911 
912   return true;
913 }
914 
915 /// Can we constant-emit a load of a reference to a variable of the
916 /// given type?  This is different from predicates like
917 /// Decl::isUsableInConstantExpressions because we do want it to apply
918 /// in situations that don't necessarily satisfy the language's rules
919 /// for this (e.g. C++'s ODR-use rules).  For example, we want to able
920 /// to do this with const float variables even if those variables
921 /// aren't marked 'constexpr'.
922 enum ConstantEmissionKind {
923   CEK_None,
924   CEK_AsReferenceOnly,
925   CEK_AsValueOrReference,
926   CEK_AsValueOnly
927 };
928 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
929   type = type.getCanonicalType();
930   if (const auto *ref = dyn_cast<ReferenceType>(type)) {
931     if (isConstantEmittableObjectType(ref->getPointeeType()))
932       return CEK_AsValueOrReference;
933     return CEK_AsReferenceOnly;
934   }
935   if (isConstantEmittableObjectType(type))
936     return CEK_AsValueOnly;
937   return CEK_None;
938 }
939 
940 /// Try to emit a reference to the given value without producing it as
941 /// an l-value.  This is actually more than an optimization: we can't
942 /// produce an l-value for variables that we never actually captured
943 /// in a block or lambda, which means const int variables or constexpr
944 /// literals or similar.
945 CodeGenFunction::ConstantEmission
946 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
947   ValueDecl *value = refExpr->getDecl();
948 
949   // The value needs to be an enum constant or a constant variable.
950   ConstantEmissionKind CEK;
951   if (isa<ParmVarDecl>(value)) {
952     CEK = CEK_None;
953   } else if (auto *var = dyn_cast<VarDecl>(value)) {
954     CEK = checkVarTypeForConstantEmission(var->getType());
955   } else if (isa<EnumConstantDecl>(value)) {
956     CEK = CEK_AsValueOnly;
957   } else {
958     CEK = CEK_None;
959   }
960   if (CEK == CEK_None) return ConstantEmission();
961 
962   Expr::EvalResult result;
963   bool resultIsReference;
964   QualType resultType;
965 
966   // It's best to evaluate all the way as an r-value if that's permitted.
967   if (CEK != CEK_AsReferenceOnly &&
968       refExpr->EvaluateAsRValue(result, getContext())) {
969     resultIsReference = false;
970     resultType = refExpr->getType();
971 
972   // Otherwise, try to evaluate as an l-value.
973   } else if (CEK != CEK_AsValueOnly &&
974              refExpr->EvaluateAsLValue(result, getContext())) {
975     resultIsReference = true;
976     resultType = value->getType();
977 
978   // Failure.
979   } else {
980     return ConstantEmission();
981   }
982 
983   // In any case, if the initializer has side-effects, abandon ship.
984   if (result.HasSideEffects)
985     return ConstantEmission();
986 
987   // Emit as a constant.
988   llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
989 
990   // Make sure we emit a debug reference to the global variable.
991   // This should probably fire even for
992   if (isa<VarDecl>(value)) {
993     if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
994       EmitDeclRefExprDbgValue(refExpr, C);
995   } else {
996     assert(isa<EnumConstantDecl>(value));
997     EmitDeclRefExprDbgValue(refExpr, C);
998   }
999 
1000   // If we emitted a reference constant, we need to dereference that.
1001   if (resultIsReference)
1002     return ConstantEmission::forReference(C);
1003 
1004   return ConstantEmission::forValue(C);
1005 }
1006 
1007 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1008                                                SourceLocation Loc) {
1009   return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1010                           lvalue.getAlignment().getQuantity(),
1011                           lvalue.getType(), Loc, lvalue.getTBAAInfo(),
1012                           lvalue.getTBAABaseType(), lvalue.getTBAAOffset());
1013 }
1014 
1015 static bool hasBooleanRepresentation(QualType Ty) {
1016   if (Ty->isBooleanType())
1017     return true;
1018 
1019   if (const EnumType *ET = Ty->getAs<EnumType>())
1020     return ET->getDecl()->getIntegerType()->isBooleanType();
1021 
1022   if (const AtomicType *AT = Ty->getAs<AtomicType>())
1023     return hasBooleanRepresentation(AT->getValueType());
1024 
1025   return false;
1026 }
1027 
1028 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1029                             llvm::APInt &Min, llvm::APInt &End,
1030                             bool StrictEnums) {
1031   const EnumType *ET = Ty->getAs<EnumType>();
1032   bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1033                                 ET && !ET->getDecl()->isFixed();
1034   bool IsBool = hasBooleanRepresentation(Ty);
1035   if (!IsBool && !IsRegularCPlusPlusEnum)
1036     return false;
1037 
1038   if (IsBool) {
1039     Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1040     End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1041   } else {
1042     const EnumDecl *ED = ET->getDecl();
1043     llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1044     unsigned Bitwidth = LTy->getScalarSizeInBits();
1045     unsigned NumNegativeBits = ED->getNumNegativeBits();
1046     unsigned NumPositiveBits = ED->getNumPositiveBits();
1047 
1048     if (NumNegativeBits) {
1049       unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1050       assert(NumBits <= Bitwidth);
1051       End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1052       Min = -End;
1053     } else {
1054       assert(NumPositiveBits <= Bitwidth);
1055       End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1056       Min = llvm::APInt(Bitwidth, 0);
1057     }
1058   }
1059   return true;
1060 }
1061 
1062 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1063   llvm::APInt Min, End;
1064   if (!getRangeForType(*this, Ty, Min, End,
1065                        CGM.getCodeGenOpts().StrictEnums))
1066     return nullptr;
1067 
1068   llvm::MDBuilder MDHelper(getLLVMContext());
1069   return MDHelper.createRange(Min, End);
1070 }
1071 
1072 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1073                                                unsigned Alignment, QualType Ty,
1074                                                SourceLocation Loc,
1075                                                llvm::MDNode *TBAAInfo,
1076                                                QualType TBAABaseType,
1077                                                uint64_t TBAAOffset) {
1078   // For better performance, handle vector loads differently.
1079   if (Ty->isVectorType()) {
1080     llvm::Value *V;
1081     const llvm::Type *EltTy =
1082     cast<llvm::PointerType>(Addr->getType())->getElementType();
1083 
1084     const auto *VTy = cast<llvm::VectorType>(EltTy);
1085 
1086     // Handle vectors of size 3, like size 4 for better performance.
1087     if (VTy->getNumElements() == 3) {
1088 
1089       // Bitcast to vec4 type.
1090       llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1091                                                          4);
1092       llvm::PointerType *ptVec4Ty =
1093       llvm::PointerType::get(vec4Ty,
1094                              (cast<llvm::PointerType>(
1095                                       Addr->getType()))->getAddressSpace());
1096       llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
1097                                                 "castToVec4");
1098       // Now load value.
1099       llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1100 
1101       // Shuffle vector to get vec3.
1102       llvm::Constant *Mask[] = {
1103         llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
1104         llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
1105         llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
1106       };
1107 
1108       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1109       V = Builder.CreateShuffleVector(LoadVal,
1110                                       llvm::UndefValue::get(vec4Ty),
1111                                       MaskV, "extractVec");
1112       return EmitFromMemory(V, Ty);
1113     }
1114   }
1115 
1116   // Atomic operations have to be done on integral types.
1117   if (Ty->isAtomicType()) {
1118     LValue lvalue = LValue::MakeAddr(Addr, Ty,
1119                                      CharUnits::fromQuantity(Alignment),
1120                                      getContext(), TBAAInfo);
1121     return EmitAtomicLoad(lvalue, Loc).getScalarVal();
1122   }
1123 
1124   llvm::LoadInst *Load = Builder.CreateLoad(Addr);
1125   if (Volatile)
1126     Load->setVolatile(true);
1127   if (Alignment)
1128     Load->setAlignment(Alignment);
1129   if (TBAAInfo) {
1130     llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1131                                                       TBAAOffset);
1132     if (TBAAPath)
1133       CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
1134   }
1135 
1136   if ((SanOpts->Bool && hasBooleanRepresentation(Ty)) ||
1137       (SanOpts->Enum && Ty->getAs<EnumType>())) {
1138     SanitizerScope SanScope(this);
1139     llvm::APInt Min, End;
1140     if (getRangeForType(*this, Ty, Min, End, true)) {
1141       --End;
1142       llvm::Value *Check;
1143       if (!Min)
1144         Check = Builder.CreateICmpULE(
1145           Load, llvm::ConstantInt::get(getLLVMContext(), End));
1146       else {
1147         llvm::Value *Upper = Builder.CreateICmpSLE(
1148           Load, llvm::ConstantInt::get(getLLVMContext(), End));
1149         llvm::Value *Lower = Builder.CreateICmpSGE(
1150           Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1151         Check = Builder.CreateAnd(Upper, Lower);
1152       }
1153       llvm::Constant *StaticArgs[] = {
1154         EmitCheckSourceLocation(Loc),
1155         EmitCheckTypeDescriptor(Ty)
1156       };
1157       EmitCheck(Check, "load_invalid_value", StaticArgs, EmitCheckValue(Load),
1158                 CRK_Recoverable);
1159     }
1160   } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1161     if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1162       Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1163 
1164   return EmitFromMemory(Load, Ty);
1165 }
1166 
1167 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1168   // Bool has a different representation in memory than in registers.
1169   if (hasBooleanRepresentation(Ty)) {
1170     // This should really always be an i1, but sometimes it's already
1171     // an i8, and it's awkward to track those cases down.
1172     if (Value->getType()->isIntegerTy(1))
1173       return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1174     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1175            "wrong value rep of bool");
1176   }
1177 
1178   return Value;
1179 }
1180 
1181 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1182   // Bool has a different representation in memory than in registers.
1183   if (hasBooleanRepresentation(Ty)) {
1184     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1185            "wrong value rep of bool");
1186     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1187   }
1188 
1189   return Value;
1190 }
1191 
1192 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1193                                         bool Volatile, unsigned Alignment,
1194                                         QualType Ty, llvm::MDNode *TBAAInfo,
1195                                         bool isInit, QualType TBAABaseType,
1196                                         uint64_t TBAAOffset) {
1197 
1198   // Handle vectors differently to get better performance.
1199   if (Ty->isVectorType()) {
1200     llvm::Type *SrcTy = Value->getType();
1201     auto *VecTy = cast<llvm::VectorType>(SrcTy);
1202     // Handle vec3 special.
1203     if (VecTy->getNumElements() == 3) {
1204       llvm::LLVMContext &VMContext = getLLVMContext();
1205 
1206       // Our source is a vec3, do a shuffle vector to make it a vec4.
1207       SmallVector<llvm::Constant*, 4> Mask;
1208       Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1209                                             0));
1210       Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1211                                             1));
1212       Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1213                                             2));
1214       Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
1215 
1216       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1217       Value = Builder.CreateShuffleVector(Value,
1218                                           llvm::UndefValue::get(VecTy),
1219                                           MaskV, "extractVec");
1220       SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1221     }
1222     auto *DstPtr = cast<llvm::PointerType>(Addr->getType());
1223     if (DstPtr->getElementType() != SrcTy) {
1224       llvm::Type *MemTy =
1225       llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1226       Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1227     }
1228   }
1229 
1230   Value = EmitToMemory(Value, Ty);
1231 
1232   if (Ty->isAtomicType()) {
1233     EmitAtomicStore(RValue::get(Value),
1234                     LValue::MakeAddr(Addr, Ty,
1235                                      CharUnits::fromQuantity(Alignment),
1236                                      getContext(), TBAAInfo),
1237                     isInit);
1238     return;
1239   }
1240 
1241   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1242   if (Alignment)
1243     Store->setAlignment(Alignment);
1244   if (TBAAInfo) {
1245     llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1246                                                       TBAAOffset);
1247     if (TBAAPath)
1248       CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
1249   }
1250 }
1251 
1252 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1253                                         bool isInit) {
1254   EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1255                     lvalue.getAlignment().getQuantity(), lvalue.getType(),
1256                     lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1257                     lvalue.getTBAAOffset());
1258 }
1259 
1260 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1261 /// method emits the address of the lvalue, then loads the result as an rvalue,
1262 /// returning the rvalue.
1263 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1264   if (LV.isObjCWeak()) {
1265     // load of a __weak object.
1266     llvm::Value *AddrWeakObj = LV.getAddress();
1267     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1268                                                              AddrWeakObj));
1269   }
1270   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1271     llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1272     Object = EmitObjCConsumeObject(LV.getType(), Object);
1273     return RValue::get(Object);
1274   }
1275 
1276   if (LV.isSimple()) {
1277     assert(!LV.getType()->isFunctionType());
1278 
1279     // Everything needs a load.
1280     return RValue::get(EmitLoadOfScalar(LV, Loc));
1281   }
1282 
1283   if (LV.isVectorElt()) {
1284     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1285                                               LV.isVolatileQualified());
1286     Load->setAlignment(LV.getAlignment().getQuantity());
1287     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1288                                                     "vecext"));
1289   }
1290 
1291   // If this is a reference to a subset of the elements of a vector, either
1292   // shuffle the input or extract/insert them as appropriate.
1293   if (LV.isExtVectorElt())
1294     return EmitLoadOfExtVectorElementLValue(LV);
1295 
1296   // Global Register variables always invoke intrinsics
1297   if (LV.isGlobalReg())
1298     return EmitLoadOfGlobalRegLValue(LV);
1299 
1300   assert(LV.isBitField() && "Unknown LValue type!");
1301   return EmitLoadOfBitfieldLValue(LV);
1302 }
1303 
1304 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
1305   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1306 
1307   // Get the output type.
1308   llvm::Type *ResLTy = ConvertType(LV.getType());
1309 
1310   llvm::Value *Ptr = LV.getBitFieldAddr();
1311   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),
1312                                         "bf.load");
1313   cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1314 
1315   if (Info.IsSigned) {
1316     assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1317     unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1318     if (HighBits)
1319       Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1320     if (Info.Offset + HighBits)
1321       Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1322   } else {
1323     if (Info.Offset)
1324       Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1325     if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1326       Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1327                                                               Info.Size),
1328                               "bf.clear");
1329   }
1330   Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1331 
1332   return RValue::get(Val);
1333 }
1334 
1335 // If this is a reference to a subset of the elements of a vector, create an
1336 // appropriate shufflevector.
1337 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1338   llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1339                                             LV.isVolatileQualified());
1340   Load->setAlignment(LV.getAlignment().getQuantity());
1341   llvm::Value *Vec = Load;
1342 
1343   const llvm::Constant *Elts = LV.getExtVectorElts();
1344 
1345   // If the result of the expression is a non-vector type, we must be extracting
1346   // a single element.  Just codegen as an extractelement.
1347   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1348   if (!ExprVT) {
1349     unsigned InIdx = getAccessedFieldNo(0, Elts);
1350     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1351     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1352   }
1353 
1354   // Always use shuffle vector to try to retain the original program structure
1355   unsigned NumResultElts = ExprVT->getNumElements();
1356 
1357   SmallVector<llvm::Constant*, 4> Mask;
1358   for (unsigned i = 0; i != NumResultElts; ++i)
1359     Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1360 
1361   llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1362   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1363                                     MaskV);
1364   return RValue::get(Vec);
1365 }
1366 
1367 /// @brief Generates lvalue for partial ext_vector access.
1368 llvm::Value *CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1369   llvm::Value *VectorAddress = LV.getExtVectorAddr();
1370   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1371   QualType EQT = ExprVT->getElementType();
1372   llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1373   llvm::Type *VectorElementPtrToTy = VectorElementTy->getPointerTo();
1374 
1375   llvm::Value *CastToPointerElement =
1376     Builder.CreateBitCast(VectorAddress,
1377                           VectorElementPtrToTy, "conv.ptr.element");
1378 
1379   const llvm::Constant *Elts = LV.getExtVectorElts();
1380   unsigned ix = getAccessedFieldNo(0, Elts);
1381 
1382   llvm::Value *VectorBasePtrPlusIx =
1383     Builder.CreateInBoundsGEP(CastToPointerElement,
1384                               llvm::ConstantInt::get(SizeTy, ix), "add.ptr");
1385 
1386   return VectorBasePtrPlusIx;
1387 }
1388 
1389 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1390 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1391   assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1392          "Bad type for register variable");
1393   llvm::MDNode *RegName = dyn_cast<llvm::MDNode>(LV.getGlobalReg());
1394   assert(RegName && "Register LValue is not metadata");
1395 
1396   // We accept integer and pointer types only
1397   llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1398   llvm::Type *Ty = OrigTy;
1399   if (OrigTy->isPointerTy())
1400     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1401   llvm::Type *Types[] = { Ty };
1402 
1403   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1404   llvm::Value *Call = Builder.CreateCall(F, RegName);
1405   if (OrigTy->isPointerTy())
1406     Call = Builder.CreateIntToPtr(Call, OrigTy);
1407   return RValue::get(Call);
1408 }
1409 
1410 
1411 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1412 /// lvalue, where both are guaranteed to the have the same type, and that type
1413 /// is 'Ty'.
1414 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1415                                              bool isInit) {
1416   if (!Dst.isSimple()) {
1417     if (Dst.isVectorElt()) {
1418       // Read/modify/write the vector, inserting the new element.
1419       llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1420                                                 Dst.isVolatileQualified());
1421       Load->setAlignment(Dst.getAlignment().getQuantity());
1422       llvm::Value *Vec = Load;
1423       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1424                                         Dst.getVectorIdx(), "vecins");
1425       llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1426                                                    Dst.isVolatileQualified());
1427       Store->setAlignment(Dst.getAlignment().getQuantity());
1428       return;
1429     }
1430 
1431     // If this is an update of extended vector elements, insert them as
1432     // appropriate.
1433     if (Dst.isExtVectorElt())
1434       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1435 
1436     if (Dst.isGlobalReg())
1437       return EmitStoreThroughGlobalRegLValue(Src, Dst);
1438 
1439     assert(Dst.isBitField() && "Unknown LValue type");
1440     return EmitStoreThroughBitfieldLValue(Src, Dst);
1441   }
1442 
1443   // There's special magic for assigning into an ARC-qualified l-value.
1444   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1445     switch (Lifetime) {
1446     case Qualifiers::OCL_None:
1447       llvm_unreachable("present but none");
1448 
1449     case Qualifiers::OCL_ExplicitNone:
1450       // nothing special
1451       break;
1452 
1453     case Qualifiers::OCL_Strong:
1454       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1455       return;
1456 
1457     case Qualifiers::OCL_Weak:
1458       EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1459       return;
1460 
1461     case Qualifiers::OCL_Autoreleasing:
1462       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1463                                                      Src.getScalarVal()));
1464       // fall into the normal path
1465       break;
1466     }
1467   }
1468 
1469   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1470     // load of a __weak object.
1471     llvm::Value *LvalueDst = Dst.getAddress();
1472     llvm::Value *src = Src.getScalarVal();
1473      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1474     return;
1475   }
1476 
1477   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1478     // load of a __strong object.
1479     llvm::Value *LvalueDst = Dst.getAddress();
1480     llvm::Value *src = Src.getScalarVal();
1481     if (Dst.isObjCIvar()) {
1482       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1483       llvm::Type *ResultType = ConvertType(getContext().LongTy);
1484       llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
1485       llvm::Value *dst = RHS;
1486       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1487       llvm::Value *LHS =
1488         Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1489       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1490       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1491                                               BytesBetween);
1492     } else if (Dst.isGlobalObjCRef()) {
1493       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1494                                                 Dst.isThreadLocalRef());
1495     }
1496     else
1497       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1498     return;
1499   }
1500 
1501   assert(Src.isScalar() && "Can't emit an agg store with this method");
1502   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1503 }
1504 
1505 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1506                                                      llvm::Value **Result) {
1507   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1508   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1509   llvm::Value *Ptr = Dst.getBitFieldAddr();
1510 
1511   // Get the source value, truncated to the width of the bit-field.
1512   llvm::Value *SrcVal = Src.getScalarVal();
1513 
1514   // Cast the source to the storage type and shift it into place.
1515   SrcVal = Builder.CreateIntCast(SrcVal,
1516                                  Ptr->getType()->getPointerElementType(),
1517                                  /*IsSigned=*/false);
1518   llvm::Value *MaskedVal = SrcVal;
1519 
1520   // See if there are other bits in the bitfield's storage we'll need to load
1521   // and mask together with source before storing.
1522   if (Info.StorageSize != Info.Size) {
1523     assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1524     llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
1525                                           "bf.load");
1526     cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1527 
1528     // Mask the source value as needed.
1529     if (!hasBooleanRepresentation(Dst.getType()))
1530       SrcVal = Builder.CreateAnd(SrcVal,
1531                                  llvm::APInt::getLowBitsSet(Info.StorageSize,
1532                                                             Info.Size),
1533                                  "bf.value");
1534     MaskedVal = SrcVal;
1535     if (Info.Offset)
1536       SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1537 
1538     // Mask out the original value.
1539     Val = Builder.CreateAnd(Val,
1540                             ~llvm::APInt::getBitsSet(Info.StorageSize,
1541                                                      Info.Offset,
1542                                                      Info.Offset + Info.Size),
1543                             "bf.clear");
1544 
1545     // Or together the unchanged values and the source value.
1546     SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1547   } else {
1548     assert(Info.Offset == 0);
1549   }
1550 
1551   // Write the new value back out.
1552   llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr,
1553                                                Dst.isVolatileQualified());
1554   Store->setAlignment(Info.StorageAlignment);
1555 
1556   // Return the new value of the bit-field, if requested.
1557   if (Result) {
1558     llvm::Value *ResultVal = MaskedVal;
1559 
1560     // Sign extend the value if needed.
1561     if (Info.IsSigned) {
1562       assert(Info.Size <= Info.StorageSize);
1563       unsigned HighBits = Info.StorageSize - Info.Size;
1564       if (HighBits) {
1565         ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1566         ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1567       }
1568     }
1569 
1570     ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1571                                       "bf.result.cast");
1572     *Result = EmitFromMemory(ResultVal, Dst.getType());
1573   }
1574 }
1575 
1576 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1577                                                                LValue Dst) {
1578   // This access turns into a read/modify/write of the vector.  Load the input
1579   // value now.
1580   llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1581                                             Dst.isVolatileQualified());
1582   Load->setAlignment(Dst.getAlignment().getQuantity());
1583   llvm::Value *Vec = Load;
1584   const llvm::Constant *Elts = Dst.getExtVectorElts();
1585 
1586   llvm::Value *SrcVal = Src.getScalarVal();
1587 
1588   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1589     unsigned NumSrcElts = VTy->getNumElements();
1590     unsigned NumDstElts =
1591        cast<llvm::VectorType>(Vec->getType())->getNumElements();
1592     if (NumDstElts == NumSrcElts) {
1593       // Use shuffle vector is the src and destination are the same number of
1594       // elements and restore the vector mask since it is on the side it will be
1595       // stored.
1596       SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1597       for (unsigned i = 0; i != NumSrcElts; ++i)
1598         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1599 
1600       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1601       Vec = Builder.CreateShuffleVector(SrcVal,
1602                                         llvm::UndefValue::get(Vec->getType()),
1603                                         MaskV);
1604     } else if (NumDstElts > NumSrcElts) {
1605       // Extended the source vector to the same length and then shuffle it
1606       // into the destination.
1607       // FIXME: since we're shuffling with undef, can we just use the indices
1608       //        into that?  This could be simpler.
1609       SmallVector<llvm::Constant*, 4> ExtMask;
1610       for (unsigned i = 0; i != NumSrcElts; ++i)
1611         ExtMask.push_back(Builder.getInt32(i));
1612       ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1613       llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1614       llvm::Value *ExtSrcVal =
1615         Builder.CreateShuffleVector(SrcVal,
1616                                     llvm::UndefValue::get(SrcVal->getType()),
1617                                     ExtMaskV);
1618       // build identity
1619       SmallVector<llvm::Constant*, 4> Mask;
1620       for (unsigned i = 0; i != NumDstElts; ++i)
1621         Mask.push_back(Builder.getInt32(i));
1622 
1623       // When the vector size is odd and .odd or .hi is used, the last element
1624       // of the Elts constant array will be one past the size of the vector.
1625       // Ignore the last element here, if it is greater than the mask size.
1626       if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1627         NumSrcElts--;
1628 
1629       // modify when what gets shuffled in
1630       for (unsigned i = 0; i != NumSrcElts; ++i)
1631         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1632       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1633       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1634     } else {
1635       // We should never shorten the vector
1636       llvm_unreachable("unexpected shorten vector length");
1637     }
1638   } else {
1639     // If the Src is a scalar (not a vector) it must be updating one element.
1640     unsigned InIdx = getAccessedFieldNo(0, Elts);
1641     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1642     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1643   }
1644 
1645   llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1646                                                Dst.isVolatileQualified());
1647   Store->setAlignment(Dst.getAlignment().getQuantity());
1648 }
1649 
1650 /// @brief Store of global named registers are always calls to intrinsics.
1651 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1652   assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1653          "Bad type for register variable");
1654   llvm::MDNode *RegName = dyn_cast<llvm::MDNode>(Dst.getGlobalReg());
1655   assert(RegName && "Register LValue is not metadata");
1656 
1657   // We accept integer and pointer types only
1658   llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.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::write_register, Types);
1665   llvm::Value *Value = Src.getScalarVal();
1666   if (OrigTy->isPointerTy())
1667     Value = Builder.CreatePtrToInt(Value, Ty);
1668   Builder.CreateCall2(F, RegName, Value);
1669 }
1670 
1671 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1672 // generating write-barries API. It is currently a global, ivar,
1673 // or neither.
1674 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1675                                  LValue &LV,
1676                                  bool IsMemberAccess=false) {
1677   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1678     return;
1679 
1680   if (isa<ObjCIvarRefExpr>(E)) {
1681     QualType ExpTy = E->getType();
1682     if (IsMemberAccess && ExpTy->isPointerType()) {
1683       // If ivar is a structure pointer, assigning to field of
1684       // this struct follows gcc's behavior and makes it a non-ivar
1685       // writer-barrier conservatively.
1686       ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1687       if (ExpTy->isRecordType()) {
1688         LV.setObjCIvar(false);
1689         return;
1690       }
1691     }
1692     LV.setObjCIvar(true);
1693     auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
1694     LV.setBaseIvarExp(Exp->getBase());
1695     LV.setObjCArray(E->getType()->isArrayType());
1696     return;
1697   }
1698 
1699   if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1700     if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1701       if (VD->hasGlobalStorage()) {
1702         LV.setGlobalObjCRef(true);
1703         LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
1704       }
1705     }
1706     LV.setObjCArray(E->getType()->isArrayType());
1707     return;
1708   }
1709 
1710   if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
1711     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1712     return;
1713   }
1714 
1715   if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
1716     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1717     if (LV.isObjCIvar()) {
1718       // If cast is to a structure pointer, follow gcc's behavior and make it
1719       // a non-ivar write-barrier.
1720       QualType ExpTy = E->getType();
1721       if (ExpTy->isPointerType())
1722         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1723       if (ExpTy->isRecordType())
1724         LV.setObjCIvar(false);
1725     }
1726     return;
1727   }
1728 
1729   if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1730     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1731     return;
1732   }
1733 
1734   if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1735     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1736     return;
1737   }
1738 
1739   if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
1740     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1741     return;
1742   }
1743 
1744   if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
1745     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1746     return;
1747   }
1748 
1749   if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1750     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1751     if (LV.isObjCIvar() && !LV.isObjCArray())
1752       // Using array syntax to assigning to what an ivar points to is not
1753       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1754       LV.setObjCIvar(false);
1755     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1756       // Using array syntax to assigning to what global points to is not
1757       // same as assigning to the global itself. {id *G;} G[i] = 0;
1758       LV.setGlobalObjCRef(false);
1759     return;
1760   }
1761 
1762   if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
1763     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
1764     // We don't know if member is an 'ivar', but this flag is looked at
1765     // only in the context of LV.isObjCIvar().
1766     LV.setObjCArray(E->getType()->isArrayType());
1767     return;
1768   }
1769 }
1770 
1771 static llvm::Value *
1772 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
1773                                 llvm::Value *V, llvm::Type *IRType,
1774                                 StringRef Name = StringRef()) {
1775   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
1776   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
1777 }
1778 
1779 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1780                                       const Expr *E, const VarDecl *VD) {
1781   QualType T = E->getType();
1782 
1783   // If it's thread_local, emit a call to its wrapper function instead.
1784   if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1785       CGF.CGM.getCXXABI().usesThreadWrapperFunction())
1786     return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1787 
1788   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1789   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1790   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
1791   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
1792   LValue LV;
1793   if (VD->getType()->isReferenceType()) {
1794     llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
1795     LI->setAlignment(Alignment.getQuantity());
1796     V = LI;
1797     LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1798   } else {
1799     LV = CGF.MakeAddrLValue(V, T, Alignment);
1800   }
1801   setObjCGCLValueClass(CGF.getContext(), E, LV);
1802   return LV;
1803 }
1804 
1805 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1806                                      const Expr *E, const FunctionDecl *FD) {
1807   llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1808   if (!FD->hasPrototype()) {
1809     if (const FunctionProtoType *Proto =
1810             FD->getType()->getAs<FunctionProtoType>()) {
1811       // Ugly case: for a K&R-style definition, the type of the definition
1812       // isn't the same as the type of a use.  Correct for this with a
1813       // bitcast.
1814       QualType NoProtoType =
1815           CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
1816       NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1817       V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
1818     }
1819   }
1820   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
1821   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1822 }
1823 
1824 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
1825                                       llvm::Value *ThisValue) {
1826   QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
1827   LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
1828   return CGF.EmitLValueForField(LV, FD);
1829 }
1830 
1831 /// Named Registers are named metadata pointing to the register name
1832 /// which will be read from/written to as an argument to the intrinsic
1833 /// @llvm.read/write_register.
1834 /// So far, only the name is being passed down, but other options such as
1835 /// register type, allocation type or even optimization options could be
1836 /// passed down via the metadata node.
1837 static LValue EmitGlobalNamedRegister(const VarDecl *VD,
1838                                       CodeGenModule &CGM,
1839                                       CharUnits Alignment) {
1840   SmallString<64> Name("llvm.named.register.");
1841   AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
1842   assert(Asm->getLabel().size() < 64-Name.size() &&
1843       "Register name too big");
1844   Name.append(Asm->getLabel());
1845   llvm::NamedMDNode *M =
1846     CGM.getModule().getOrInsertNamedMetadata(Name);
1847   if (M->getNumOperands() == 0) {
1848     llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
1849                                               Asm->getLabel());
1850     llvm::Value *Ops[] = { Str };
1851     M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1852   }
1853   return LValue::MakeGlobalReg(M->getOperand(0), VD->getType(), Alignment);
1854 }
1855 
1856 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1857   const NamedDecl *ND = E->getDecl();
1858   CharUnits Alignment = getContext().getDeclAlign(ND);
1859   QualType T = E->getType();
1860 
1861   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
1862     // Global Named registers access via intrinsics only
1863     if (VD->getStorageClass() == SC_Register &&
1864         VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
1865       return EmitGlobalNamedRegister(VD, CGM, Alignment);
1866 
1867     // A DeclRefExpr for a reference initialized by a constant expression can
1868     // appear without being odr-used. Directly emit the constant initializer.
1869     const Expr *Init = VD->getAnyInitializer(VD);
1870     if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1871         VD->isUsableInConstantExpressions(getContext()) &&
1872         VD->checkInitIsICE()) {
1873       llvm::Constant *Val =
1874         CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1875       assert(Val && "failed to emit reference constant expression");
1876       // FIXME: Eventually we will want to emit vector element references.
1877       return MakeAddrLValue(Val, T, Alignment);
1878     }
1879   }
1880 
1881   // FIXME: We should be able to assert this for FunctionDecls as well!
1882   // FIXME: We should be able to assert this for all DeclRefExprs, not just
1883   // those with a valid source location.
1884   assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1885           !E->getLocation().isValid()) &&
1886          "Should not use decl without marking it used!");
1887 
1888   if (ND->hasAttr<WeakRefAttr>()) {
1889     const auto *VD = cast<ValueDecl>(ND);
1890     llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1891     return MakeAddrLValue(Aliasee, T, Alignment);
1892   }
1893 
1894   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
1895     // Check if this is a global variable.
1896     if (VD->hasLinkage() || VD->isStaticDataMember())
1897       return EmitGlobalVarDeclLValue(*this, E, VD);
1898 
1899     bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1900 
1901     llvm::Value *V = LocalDeclMap.lookup(VD);
1902     if (!V && VD->isStaticLocal())
1903       V = CGM.getOrCreateStaticVarDecl(
1904           *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1905 
1906     // Use special handling for lambdas.
1907     if (!V) {
1908       if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1909         return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
1910       } else if (CapturedStmtInfo) {
1911         if (const FieldDecl *FD = CapturedStmtInfo->lookup(VD))
1912           return EmitCapturedFieldLValue(*this, FD,
1913                                          CapturedStmtInfo->getContextValue());
1914       }
1915 
1916       assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
1917       return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
1918                             T, Alignment);
1919     }
1920 
1921     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1922 
1923     if (isBlockVariable)
1924       V = BuildBlockByrefAddress(V, VD);
1925 
1926     LValue LV;
1927     if (VD->getType()->isReferenceType()) {
1928       llvm::LoadInst *LI = Builder.CreateLoad(V);
1929       LI->setAlignment(Alignment.getQuantity());
1930       V = LI;
1931       LV = MakeNaturalAlignAddrLValue(V, T);
1932     } else {
1933       LV = MakeAddrLValue(V, T, Alignment);
1934     }
1935 
1936     bool isLocalStorage = VD->hasLocalStorage();
1937 
1938     bool NonGCable = isLocalStorage &&
1939                      !VD->getType()->isReferenceType() &&
1940                      !isBlockVariable;
1941     if (NonGCable) {
1942       LV.getQuals().removeObjCGCAttr();
1943       LV.setNonGC(true);
1944     }
1945 
1946     bool isImpreciseLifetime =
1947       (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
1948     if (isImpreciseLifetime)
1949       LV.setARCPreciseLifetime(ARCImpreciseLifetime);
1950     setObjCGCLValueClass(getContext(), E, LV);
1951     return LV;
1952   }
1953 
1954   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1955     return EmitFunctionDeclLValue(*this, E, FD);
1956 
1957   llvm_unreachable("Unhandled DeclRefExpr");
1958 }
1959 
1960 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1961   // __extension__ doesn't affect lvalue-ness.
1962   if (E->getOpcode() == UO_Extension)
1963     return EmitLValue(E->getSubExpr());
1964 
1965   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1966   switch (E->getOpcode()) {
1967   default: llvm_unreachable("Unknown unary operator lvalue!");
1968   case UO_Deref: {
1969     QualType T = E->getSubExpr()->getType()->getPointeeType();
1970     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1971 
1972     LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1973     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1974 
1975     // We should not generate __weak write barrier on indirect reference
1976     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1977     // But, we continue to generate __strong write barrier on indirect write
1978     // into a pointer to object.
1979     if (getLangOpts().ObjC1 &&
1980         getLangOpts().getGC() != LangOptions::NonGC &&
1981         LV.isObjCWeak())
1982       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1983     return LV;
1984   }
1985   case UO_Real:
1986   case UO_Imag: {
1987     LValue LV = EmitLValue(E->getSubExpr());
1988     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1989     llvm::Value *Addr = LV.getAddress();
1990 
1991     // __real is valid on scalars.  This is a faster way of testing that.
1992     // __imag can only produce an rvalue on scalars.
1993     if (E->getOpcode() == UO_Real &&
1994         !cast<llvm::PointerType>(Addr->getType())
1995            ->getElementType()->isStructTy()) {
1996       assert(E->getSubExpr()->getType()->isArithmeticType());
1997       return LV;
1998     }
1999 
2000     assert(E->getSubExpr()->getType()->isAnyComplexType());
2001 
2002     unsigned Idx = E->getOpcode() == UO_Imag;
2003     return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
2004                                                   Idx, "idx"),
2005                           ExprTy);
2006   }
2007   case UO_PreInc:
2008   case UO_PreDec: {
2009     LValue LV = EmitLValue(E->getSubExpr());
2010     bool isInc = E->getOpcode() == UO_PreInc;
2011 
2012     if (E->getType()->isAnyComplexType())
2013       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2014     else
2015       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2016     return LV;
2017   }
2018   }
2019 }
2020 
2021 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2022   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2023                         E->getType());
2024 }
2025 
2026 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2027   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2028                         E->getType());
2029 }
2030 
2031 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2032   auto SL = E->getFunctionName();
2033   assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2034   StringRef FnName = CurFn->getName();
2035   if (FnName.startswith("\01"))
2036     FnName = FnName.substr(1);
2037   StringRef NameItems[] = {
2038       PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2039   std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2040 
2041   auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2042   return MakeAddrLValue(C, E->getType());
2043 }
2044 
2045 /// Emit a type description suitable for use by a runtime sanitizer library. The
2046 /// format of a type descriptor is
2047 ///
2048 /// \code
2049 ///   { i16 TypeKind, i16 TypeInfo }
2050 /// \endcode
2051 ///
2052 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2053 /// integer, 1 for a floating point value, and -1 for anything else.
2054 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2055   // Only emit each type's descriptor once.
2056   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2057     return C;
2058 
2059   uint16_t TypeKind = -1;
2060   uint16_t TypeInfo = 0;
2061 
2062   if (T->isIntegerType()) {
2063     TypeKind = 0;
2064     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2065                (T->isSignedIntegerType() ? 1 : 0);
2066   } else if (T->isFloatingType()) {
2067     TypeKind = 1;
2068     TypeInfo = getContext().getTypeSize(T);
2069   }
2070 
2071   // Format the type name as if for a diagnostic, including quotes and
2072   // optionally an 'aka'.
2073   SmallString<32> Buffer;
2074   CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2075                                     (intptr_t)T.getAsOpaquePtr(),
2076                                     StringRef(), StringRef(), None, Buffer,
2077                                     None);
2078 
2079   llvm::Constant *Components[] = {
2080     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2081     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2082   };
2083   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2084 
2085   auto *GV = new llvm::GlobalVariable(
2086       CGM.getModule(), Descriptor->getType(),
2087       /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2088   GV->setUnnamedAddr(true);
2089   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2090 
2091   // Remember the descriptor for this type.
2092   CGM.setTypeDescriptorInMap(T, GV);
2093 
2094   return GV;
2095 }
2096 
2097 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2098   llvm::Type *TargetTy = IntPtrTy;
2099 
2100   // Floating-point types which fit into intptr_t are bitcast to integers
2101   // and then passed directly (after zero-extension, if necessary).
2102   if (V->getType()->isFloatingPointTy()) {
2103     unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2104     if (Bits <= TargetTy->getIntegerBitWidth())
2105       V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2106                                                          Bits));
2107   }
2108 
2109   // Integers which fit in intptr_t are zero-extended and passed directly.
2110   if (V->getType()->isIntegerTy() &&
2111       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2112     return Builder.CreateZExt(V, TargetTy);
2113 
2114   // Pointers are passed directly, everything else is passed by address.
2115   if (!V->getType()->isPointerTy()) {
2116     llvm::Value *Ptr = CreateTempAlloca(V->getType());
2117     Builder.CreateStore(V, Ptr);
2118     V = Ptr;
2119   }
2120   return Builder.CreatePtrToInt(V, TargetTy);
2121 }
2122 
2123 /// \brief Emit a representation of a SourceLocation for passing to a handler
2124 /// in a sanitizer runtime library. The format for this data is:
2125 /// \code
2126 ///   struct SourceLocation {
2127 ///     const char *Filename;
2128 ///     int32_t Line, Column;
2129 ///   };
2130 /// \endcode
2131 /// For an invalid SourceLocation, the Filename pointer is null.
2132 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2133   llvm::Constant *Filename;
2134   int Line, Column;
2135 
2136   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2137   if (PLoc.isValid()) {
2138     auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
2139     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(FilenameGV);
2140     Filename = FilenameGV;
2141     Line = PLoc.getLine();
2142     Column = PLoc.getColumn();
2143   } else {
2144     Filename = llvm::Constant::getNullValue(Int8PtrTy);
2145     Line = Column = 0;
2146   }
2147 
2148   llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2149                             Builder.getInt32(Column)};
2150 
2151   return llvm::ConstantStruct::getAnon(Data);
2152 }
2153 
2154 void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName,
2155                                 ArrayRef<llvm::Constant *> StaticArgs,
2156                                 ArrayRef<llvm::Value *> DynamicArgs,
2157                                 CheckRecoverableKind RecoverKind) {
2158   assert(SanOpts != &SanitizerOptions::Disabled);
2159   assert(IsSanitizerScope);
2160 
2161   if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
2162     assert (RecoverKind != CRK_AlwaysRecoverable &&
2163             "Runtime call required for AlwaysRecoverable kind!");
2164     return EmitTrapCheck(Checked);
2165   }
2166 
2167   llvm::BasicBlock *Cont = createBasicBlock("cont");
2168 
2169   llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
2170 
2171   llvm::Instruction *Branch = Builder.CreateCondBr(Checked, Cont, Handler);
2172 
2173   // Give hint that we very much don't expect to execute the handler
2174   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2175   llvm::MDBuilder MDHelper(getLLVMContext());
2176   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2177   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2178 
2179   EmitBlock(Handler);
2180 
2181   llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2182   auto *InfoPtr =
2183       new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2184                                llvm::GlobalVariable::PrivateLinkage, Info);
2185   InfoPtr->setUnnamedAddr(true);
2186   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2187 
2188   SmallVector<llvm::Value *, 4> Args;
2189   SmallVector<llvm::Type *, 4> ArgTypes;
2190   Args.reserve(DynamicArgs.size() + 1);
2191   ArgTypes.reserve(DynamicArgs.size() + 1);
2192 
2193   // Handler functions take an i8* pointing to the (handler-specific) static
2194   // information block, followed by a sequence of intptr_t arguments
2195   // representing operand values.
2196   Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2197   ArgTypes.push_back(Int8PtrTy);
2198   for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2199     Args.push_back(EmitCheckValue(DynamicArgs[i]));
2200     ArgTypes.push_back(IntPtrTy);
2201   }
2202 
2203   bool Recover = RecoverKind == CRK_AlwaysRecoverable ||
2204                  (RecoverKind == CRK_Recoverable &&
2205                   CGM.getCodeGenOpts().SanitizeRecover);
2206 
2207   llvm::FunctionType *FnType =
2208     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2209   llvm::AttrBuilder B;
2210   if (!Recover) {
2211     B.addAttribute(llvm::Attribute::NoReturn)
2212      .addAttribute(llvm::Attribute::NoUnwind);
2213   }
2214   B.addAttribute(llvm::Attribute::UWTable);
2215 
2216   // Checks that have two variants use a suffix to differentiate them
2217   bool NeedsAbortSuffix = RecoverKind != CRK_Unrecoverable &&
2218                           !CGM.getCodeGenOpts().SanitizeRecover;
2219   std::string FunctionName = ("__ubsan_handle_" + CheckName +
2220                               (NeedsAbortSuffix? "_abort" : "")).str();
2221   llvm::Value *Fn = CGM.CreateRuntimeFunction(
2222       FnType, FunctionName,
2223       llvm::AttributeSet::get(getLLVMContext(),
2224                               llvm::AttributeSet::FunctionIndex, B));
2225   llvm::CallInst *HandlerCall = EmitNounwindRuntimeCall(Fn, Args);
2226   if (Recover) {
2227     Builder.CreateBr(Cont);
2228   } else {
2229     HandlerCall->setDoesNotReturn();
2230     Builder.CreateUnreachable();
2231   }
2232 
2233   EmitBlock(Cont);
2234 }
2235 
2236 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2237   llvm::BasicBlock *Cont = createBasicBlock("cont");
2238 
2239   // If we're optimizing, collapse all calls to trap down to just one per
2240   // function to save on code size.
2241   if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2242     TrapBB = createBasicBlock("trap");
2243     Builder.CreateCondBr(Checked, Cont, TrapBB);
2244     EmitBlock(TrapBB);
2245     llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2246     llvm::CallInst *TrapCall = Builder.CreateCall(F);
2247     TrapCall->setDoesNotReturn();
2248     TrapCall->setDoesNotThrow();
2249     Builder.CreateUnreachable();
2250   } else {
2251     Builder.CreateCondBr(Checked, Cont, TrapBB);
2252   }
2253 
2254   EmitBlock(Cont);
2255 }
2256 
2257 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2258 /// array to pointer, return the array subexpression.
2259 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2260   // If this isn't just an array->pointer decay, bail out.
2261   const auto *CE = dyn_cast<CastExpr>(E);
2262   if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
2263     return nullptr;
2264 
2265   // If this is a decay from variable width array, bail out.
2266   const Expr *SubExpr = CE->getSubExpr();
2267   if (SubExpr->getType()->isVariableArrayType())
2268     return nullptr;
2269 
2270   return SubExpr;
2271 }
2272 
2273 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2274                                                bool Accessed) {
2275   // The index must always be an integer, which is not an aggregate.  Emit it.
2276   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
2277   QualType IdxTy  = E->getIdx()->getType();
2278   bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2279 
2280   if (SanOpts->ArrayBounds)
2281     EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2282 
2283   // If the base is a vector type, then we are forming a vector element lvalue
2284   // with this subscript.
2285   if (E->getBase()->getType()->isVectorType() &&
2286       !isa<ExtVectorElementExpr>(E->getBase())) {
2287     // Emit the vector as an lvalue to get its address.
2288     LValue LHS = EmitLValue(E->getBase());
2289     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
2290     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
2291                                  E->getBase()->getType(), LHS.getAlignment());
2292   }
2293 
2294   // Extend or truncate the index type to 32 or 64-bits.
2295   if (Idx->getType() != IntPtrTy)
2296     Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2297 
2298   // We know that the pointer points to a type of the correct size, unless the
2299   // size is a VLA or Objective-C interface.
2300   llvm::Value *Address = nullptr;
2301   CharUnits ArrayAlignment;
2302   if (isa<ExtVectorElementExpr>(E->getBase())) {
2303     LValue LV = EmitLValue(E->getBase());
2304     Address = EmitExtVectorElementLValue(LV);
2305     Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
2306     const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2307     QualType EQT = ExprVT->getElementType();
2308     return MakeAddrLValue(Address, EQT,
2309                           getContext().getTypeAlignInChars(EQT));
2310   }
2311   else if (const VariableArrayType *vla =
2312            getContext().getAsVariableArrayType(E->getType())) {
2313     // The base must be a pointer, which is not an aggregate.  Emit
2314     // it.  It needs to be emitted first in case it's what captures
2315     // the VLA bounds.
2316     Address = EmitScalarExpr(E->getBase());
2317 
2318     // The element count here is the total number of non-VLA elements.
2319     llvm::Value *numElements = getVLASize(vla).first;
2320 
2321     // Effectively, the multiply by the VLA size is part of the GEP.
2322     // GEP indexes are signed, and scaling an index isn't permitted to
2323     // signed-overflow, so we use the same semantics for our explicit
2324     // multiply.  We suppress this if overflow is not undefined behavior.
2325     if (getLangOpts().isSignedOverflowDefined()) {
2326       Idx = Builder.CreateMul(Idx, numElements);
2327       Address = Builder.CreateGEP(Address, Idx, "arrayidx");
2328     } else {
2329       Idx = Builder.CreateNSWMul(Idx, numElements);
2330       Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
2331     }
2332   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2333     // Indexing over an interface, as in "NSString *P; P[4];"
2334     llvm::Value *InterfaceSize =
2335       llvm::ConstantInt::get(Idx->getType(),
2336           getContext().getTypeSizeInChars(OIT).getQuantity());
2337 
2338     Idx = Builder.CreateMul(Idx, InterfaceSize);
2339 
2340     // The base must be a pointer, which is not an aggregate.  Emit it.
2341     llvm::Value *Base = EmitScalarExpr(E->getBase());
2342     Address = EmitCastToVoidPtr(Base);
2343     Address = Builder.CreateGEP(Address, Idx, "arrayidx");
2344     Address = Builder.CreateBitCast(Address, Base->getType());
2345   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2346     // If this is A[i] where A is an array, the frontend will have decayed the
2347     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
2348     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2349     // "gep x, i" here.  Emit one "gep A, 0, i".
2350     assert(Array->getType()->isArrayType() &&
2351            "Array to pointer decay must have array source type!");
2352     LValue ArrayLV;
2353     // For simple multidimensional array indexing, set the 'accessed' flag for
2354     // better bounds-checking of the base expression.
2355     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
2356       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2357     else
2358       ArrayLV = EmitLValue(Array);
2359     llvm::Value *ArrayPtr = ArrayLV.getAddress();
2360     llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2361     llvm::Value *Args[] = { Zero, Idx };
2362 
2363     // Propagate the alignment from the array itself to the result.
2364     ArrayAlignment = ArrayLV.getAlignment();
2365 
2366     if (getLangOpts().isSignedOverflowDefined())
2367       Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
2368     else
2369       Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
2370   } else {
2371     // The base must be a pointer, which is not an aggregate.  Emit it.
2372     llvm::Value *Base = EmitScalarExpr(E->getBase());
2373     if (getLangOpts().isSignedOverflowDefined())
2374       Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2375     else
2376       Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
2377   }
2378 
2379   QualType T = E->getBase()->getType()->getPointeeType();
2380   assert(!T.isNull() &&
2381          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
2382 
2383 
2384   // Limit the alignment to that of the result type.
2385   LValue LV;
2386   if (!ArrayAlignment.isZero()) {
2387     CharUnits Align = getContext().getTypeAlignInChars(T);
2388     ArrayAlignment = std::min(Align, ArrayAlignment);
2389     LV = MakeAddrLValue(Address, T, ArrayAlignment);
2390   } else {
2391     LV = MakeNaturalAlignAddrLValue(Address, T);
2392   }
2393 
2394   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
2395 
2396   if (getLangOpts().ObjC1 &&
2397       getLangOpts().getGC() != LangOptions::NonGC) {
2398     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2399     setObjCGCLValueClass(getContext(), E, LV);
2400   }
2401   return LV;
2402 }
2403 
2404 static
2405 llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
2406                                        SmallVectorImpl<unsigned> &Elts) {
2407   SmallVector<llvm::Constant*, 4> CElts;
2408   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
2409     CElts.push_back(Builder.getInt32(Elts[i]));
2410 
2411   return llvm::ConstantVector::get(CElts);
2412 }
2413 
2414 LValue CodeGenFunction::
2415 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
2416   // Emit the base vector as an l-value.
2417   LValue Base;
2418 
2419   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
2420   if (E->isArrow()) {
2421     // If it is a pointer to a vector, emit the address and form an lvalue with
2422     // it.
2423     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
2424     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
2425     Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2426     Base.getQuals().removeObjCGCAttr();
2427   } else if (E->getBase()->isGLValue()) {
2428     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2429     // emit the base as an lvalue.
2430     assert(E->getBase()->getType()->isVectorType());
2431     Base = EmitLValue(E->getBase());
2432   } else {
2433     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
2434     assert(E->getBase()->getType()->isVectorType() &&
2435            "Result must be a vector");
2436     llvm::Value *Vec = EmitScalarExpr(E->getBase());
2437 
2438     // Store the vector to memory (because LValue wants an address).
2439     llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
2440     Builder.CreateStore(Vec, VecMem);
2441     Base = MakeAddrLValue(VecMem, E->getBase()->getType());
2442   }
2443 
2444   QualType type =
2445     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
2446 
2447   // Encode the element access list into a vector of unsigned indices.
2448   SmallVector<unsigned, 4> Indices;
2449   E->getEncodedElementAccess(Indices);
2450 
2451   if (Base.isSimple()) {
2452     llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
2453     return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2454                                     Base.getAlignment());
2455   }
2456   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2457 
2458   llvm::Constant *BaseElts = Base.getExtVectorElts();
2459   SmallVector<llvm::Constant *, 4> CElts;
2460 
2461   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2462     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
2463   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
2464   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2465                                   Base.getAlignment());
2466 }
2467 
2468 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
2469   Expr *BaseExpr = E->getBase();
2470 
2471   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
2472   LValue BaseLV;
2473   if (E->isArrow()) {
2474     llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2475     QualType PtrTy = BaseExpr->getType()->getPointeeType();
2476     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
2477     BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2478   } else
2479     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
2480 
2481   NamedDecl *ND = E->getMemberDecl();
2482   if (auto *Field = dyn_cast<FieldDecl>(ND)) {
2483     LValue LV = EmitLValueForField(BaseLV, Field);
2484     setObjCGCLValueClass(getContext(), E, LV);
2485     return LV;
2486   }
2487 
2488   if (auto *VD = dyn_cast<VarDecl>(ND))
2489     return EmitGlobalVarDeclLValue(*this, E, VD);
2490 
2491   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2492     return EmitFunctionDeclLValue(*this, E, FD);
2493 
2494   llvm_unreachable("Unhandled member declaration!");
2495 }
2496 
2497 /// Given that we are currently emitting a lambda, emit an l-value for
2498 /// one of its members.
2499 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
2500   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
2501   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
2502   QualType LambdaTagType =
2503     getContext().getTagDeclType(Field->getParent());
2504   LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
2505   return EmitLValueForField(LambdaLV, Field);
2506 }
2507 
2508 LValue CodeGenFunction::EmitLValueForField(LValue base,
2509                                            const FieldDecl *field) {
2510   if (field->isBitField()) {
2511     const CGRecordLayout &RL =
2512       CGM.getTypes().getCGRecordLayout(field->getParent());
2513     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
2514     llvm::Value *Addr = base.getAddress();
2515     unsigned Idx = RL.getLLVMFieldNo(field);
2516     if (Idx != 0)
2517       // For structs, we GEP to the field that the record layout suggests.
2518       Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
2519     // Get the access type.
2520     llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
2521       getLLVMContext(), Info.StorageSize,
2522       CGM.getContext().getTargetAddressSpace(base.getType()));
2523     if (Addr->getType() != PtrTy)
2524       Addr = Builder.CreateBitCast(Addr, PtrTy);
2525 
2526     QualType fieldType =
2527       field->getType().withCVRQualifiers(base.getVRQualifiers());
2528     return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
2529   }
2530 
2531   const RecordDecl *rec = field->getParent();
2532   QualType type = field->getType();
2533   CharUnits alignment = getContext().getDeclAlign(field);
2534 
2535   // FIXME: It should be impossible to have an LValue without alignment for a
2536   // complete type.
2537   if (!base.getAlignment().isZero())
2538     alignment = std::min(alignment, base.getAlignment());
2539 
2540   bool mayAlias = rec->hasAttr<MayAliasAttr>();
2541 
2542   llvm::Value *addr = base.getAddress();
2543   unsigned cvr = base.getVRQualifiers();
2544   bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
2545   if (rec->isUnion()) {
2546     // For unions, there is no pointer adjustment.
2547     assert(!type->isReferenceType() && "union has reference member");
2548     // TODO: handle path-aware TBAA for union.
2549     TBAAPath = false;
2550   } else {
2551     // For structs, we GEP to the field that the record layout suggests.
2552     unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
2553     addr = Builder.CreateStructGEP(addr, idx, field->getName());
2554 
2555     // If this is a reference field, load the reference right now.
2556     if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2557       llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2558       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
2559       load->setAlignment(alignment.getQuantity());
2560 
2561       // Loading the reference will disable path-aware TBAA.
2562       TBAAPath = false;
2563       if (CGM.shouldUseTBAA()) {
2564         llvm::MDNode *tbaa;
2565         if (mayAlias)
2566           tbaa = CGM.getTBAAInfo(getContext().CharTy);
2567         else
2568           tbaa = CGM.getTBAAInfo(type);
2569         if (tbaa)
2570           CGM.DecorateInstruction(load, tbaa);
2571       }
2572 
2573       addr = load;
2574       mayAlias = false;
2575       type = refType->getPointeeType();
2576       if (type->isIncompleteType())
2577         alignment = CharUnits();
2578       else
2579         alignment = getContext().getTypeAlignInChars(type);
2580       cvr = 0; // qualifiers don't recursively apply to referencee
2581     }
2582   }
2583 
2584   // Make sure that the address is pointing to the right type.  This is critical
2585   // for both unions and structs.  A union needs a bitcast, a struct element
2586   // will need a bitcast if the LLVM type laid out doesn't match the desired
2587   // type.
2588   addr = EmitBitCastOfLValueToProperType(*this, addr,
2589                                          CGM.getTypes().ConvertTypeForMem(type),
2590                                          field->getName());
2591 
2592   if (field->hasAttr<AnnotateAttr>())
2593     addr = EmitFieldAnnotations(field, addr);
2594 
2595   LValue LV = MakeAddrLValue(addr, type, alignment);
2596   LV.getQuals().addCVRQualifiers(cvr);
2597   if (TBAAPath) {
2598     const ASTRecordLayout &Layout =
2599         getContext().getASTRecordLayout(field->getParent());
2600     // Set the base type to be the base type of the base LValue and
2601     // update offset to be relative to the base type.
2602     LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
2603     LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
2604                      Layout.getFieldOffset(field->getFieldIndex()) /
2605                                            getContext().getCharWidth());
2606   }
2607 
2608   // __weak attribute on a field is ignored.
2609   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2610     LV.getQuals().removeObjCGCAttr();
2611 
2612   // Fields of may_alias structs act like 'char' for TBAA purposes.
2613   // FIXME: this should get propagated down through anonymous structs
2614   // and unions.
2615   if (mayAlias && LV.getTBAAInfo())
2616     LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2617 
2618   return LV;
2619 }
2620 
2621 LValue
2622 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2623                                                   const FieldDecl *Field) {
2624   QualType FieldType = Field->getType();
2625 
2626   if (!FieldType->isReferenceType())
2627     return EmitLValueForField(Base, Field);
2628 
2629   const CGRecordLayout &RL =
2630     CGM.getTypes().getCGRecordLayout(Field->getParent());
2631   unsigned idx = RL.getLLVMFieldNo(Field);
2632   llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
2633   assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2634 
2635   // Make sure that the address is pointing to the right type.  This is critical
2636   // for both unions and structs.  A union needs a bitcast, a struct element
2637   // will need a bitcast if the LLVM type laid out doesn't match the desired
2638   // type.
2639   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
2640   V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2641 
2642   CharUnits Alignment = getContext().getDeclAlign(Field);
2643 
2644   // FIXME: It should be impossible to have an LValue without alignment for a
2645   // complete type.
2646   if (!Base.getAlignment().isZero())
2647     Alignment = std::min(Alignment, Base.getAlignment());
2648 
2649   return MakeAddrLValue(V, FieldType, Alignment);
2650 }
2651 
2652 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
2653   if (E->isFileScope()) {
2654     llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2655     return MakeAddrLValue(GlobalPtr, E->getType());
2656   }
2657   if (E->getType()->isVariablyModifiedType())
2658     // make sure to emit the VLA size.
2659     EmitVariablyModifiedType(E->getType());
2660 
2661   llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
2662   const Expr *InitExpr = E->getInitializer();
2663   LValue Result = MakeAddrLValue(DeclPtr, E->getType());
2664 
2665   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2666                    /*Init*/ true);
2667 
2668   return Result;
2669 }
2670 
2671 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2672   if (!E->isGLValue())
2673     // Initializing an aggregate temporary in C++11: T{...}.
2674     return EmitAggExprToLValue(E);
2675 
2676   // An lvalue initializer list must be initializing a reference.
2677   assert(E->getNumInits() == 1 && "reference init with multiple values");
2678   return EmitLValue(E->getInit(0));
2679 }
2680 
2681 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
2682 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
2683 /// LValue is returned and the current block has been terminated.
2684 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
2685                                                     const Expr *Operand) {
2686   if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
2687     CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
2688     return None;
2689   }
2690 
2691   return CGF.EmitLValue(Operand);
2692 }
2693 
2694 LValue CodeGenFunction::
2695 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2696   if (!expr->isGLValue()) {
2697     // ?: here should be an aggregate.
2698     assert(hasAggregateEvaluationKind(expr->getType()) &&
2699            "Unexpected conditional operator!");
2700     return EmitAggExprToLValue(expr);
2701   }
2702 
2703   OpaqueValueMapping binding(*this, expr);
2704   RegionCounter Cnt = getPGORegionCounter(expr);
2705 
2706   const Expr *condExpr = expr->getCond();
2707   bool CondExprBool;
2708   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2709     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
2710     if (!CondExprBool) std::swap(live, dead);
2711 
2712     if (!ContainsLabel(dead)) {
2713       // If the true case is live, we need to track its region.
2714       if (CondExprBool)
2715         Cnt.beginRegion(Builder);
2716       return EmitLValue(live);
2717     }
2718   }
2719 
2720   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2721   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2722   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
2723 
2724   ConditionalEvaluation eval(*this);
2725   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, Cnt.getCount());
2726 
2727   // Any temporaries created here are conditional.
2728   EmitBlock(lhsBlock);
2729   Cnt.beginRegion(Builder);
2730   eval.begin(*this);
2731   Optional<LValue> lhs =
2732       EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
2733   eval.end(*this);
2734 
2735   if (lhs && !lhs->isSimple())
2736     return EmitUnsupportedLValue(expr, "conditional operator");
2737 
2738   lhsBlock = Builder.GetInsertBlock();
2739   if (lhs)
2740     Builder.CreateBr(contBlock);
2741 
2742   // Any temporaries created here are conditional.
2743   EmitBlock(rhsBlock);
2744   eval.begin(*this);
2745   Optional<LValue> rhs =
2746       EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
2747   eval.end(*this);
2748   if (rhs && !rhs->isSimple())
2749     return EmitUnsupportedLValue(expr, "conditional operator");
2750   rhsBlock = Builder.GetInsertBlock();
2751 
2752   EmitBlock(contBlock);
2753 
2754   if (lhs && rhs) {
2755     llvm::PHINode *phi = Builder.CreatePHI(lhs->getAddress()->getType(),
2756                                            2, "cond-lvalue");
2757     phi->addIncoming(lhs->getAddress(), lhsBlock);
2758     phi->addIncoming(rhs->getAddress(), rhsBlock);
2759     return MakeAddrLValue(phi, expr->getType());
2760   } else {
2761     assert((lhs || rhs) &&
2762            "both operands of glvalue conditional are throw-expressions?");
2763     return lhs ? *lhs : *rhs;
2764   }
2765 }
2766 
2767 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2768 /// type. If the cast is to a reference, we can have the usual lvalue result,
2769 /// otherwise if a cast is needed by the code generator in an lvalue context,
2770 /// then it must mean that we need the address of an aggregate in order to
2771 /// access one of its members.  This can happen for all the reasons that casts
2772 /// are permitted with aggregate result, including noop aggregate casts, and
2773 /// cast from scalar to union.
2774 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
2775   switch (E->getCastKind()) {
2776   case CK_ToVoid:
2777   case CK_BitCast:
2778   case CK_ArrayToPointerDecay:
2779   case CK_FunctionToPointerDecay:
2780   case CK_NullToMemberPointer:
2781   case CK_NullToPointer:
2782   case CK_IntegralToPointer:
2783   case CK_PointerToIntegral:
2784   case CK_PointerToBoolean:
2785   case CK_VectorSplat:
2786   case CK_IntegralCast:
2787   case CK_IntegralToBoolean:
2788   case CK_IntegralToFloating:
2789   case CK_FloatingToIntegral:
2790   case CK_FloatingToBoolean:
2791   case CK_FloatingCast:
2792   case CK_FloatingRealToComplex:
2793   case CK_FloatingComplexToReal:
2794   case CK_FloatingComplexToBoolean:
2795   case CK_FloatingComplexCast:
2796   case CK_FloatingComplexToIntegralComplex:
2797   case CK_IntegralRealToComplex:
2798   case CK_IntegralComplexToReal:
2799   case CK_IntegralComplexToBoolean:
2800   case CK_IntegralComplexCast:
2801   case CK_IntegralComplexToFloatingComplex:
2802   case CK_DerivedToBaseMemberPointer:
2803   case CK_BaseToDerivedMemberPointer:
2804   case CK_MemberPointerToBoolean:
2805   case CK_ReinterpretMemberPointer:
2806   case CK_AnyPointerToBlockPointerCast:
2807   case CK_ARCProduceObject:
2808   case CK_ARCConsumeObject:
2809   case CK_ARCReclaimReturnedObject:
2810   case CK_ARCExtendBlockObject:
2811   case CK_CopyAndAutoreleaseBlockObject:
2812   case CK_AddressSpaceConversion:
2813     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
2814 
2815   case CK_Dependent:
2816     llvm_unreachable("dependent cast kind in IR gen!");
2817 
2818   case CK_BuiltinFnToFnPtr:
2819     llvm_unreachable("builtin functions are handled elsewhere");
2820 
2821   // These are never l-values; just use the aggregate emission code.
2822   case CK_NonAtomicToAtomic:
2823   case CK_AtomicToNonAtomic:
2824     return EmitAggExprToLValue(E);
2825 
2826   case CK_Dynamic: {
2827     LValue LV = EmitLValue(E->getSubExpr());
2828     llvm::Value *V = LV.getAddress();
2829     const auto *DCE = cast<CXXDynamicCastExpr>(E);
2830     return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
2831   }
2832 
2833   case CK_ConstructorConversion:
2834   case CK_UserDefinedConversion:
2835   case CK_CPointerToObjCPointerCast:
2836   case CK_BlockPointerToObjCPointerCast:
2837   case CK_NoOp:
2838   case CK_LValueToRValue:
2839     return EmitLValue(E->getSubExpr());
2840 
2841   case CK_UncheckedDerivedToBase:
2842   case CK_DerivedToBase: {
2843     const RecordType *DerivedClassTy =
2844       E->getSubExpr()->getType()->getAs<RecordType>();
2845     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2846 
2847     LValue LV = EmitLValue(E->getSubExpr());
2848     llvm::Value *This = LV.getAddress();
2849 
2850     // Perform the derived-to-base conversion
2851     llvm::Value *Base = GetAddressOfBaseClass(
2852         This, DerivedClassDecl, E->path_begin(), E->path_end(),
2853         /*NullCheckValue=*/false, E->getExprLoc());
2854 
2855     return MakeAddrLValue(Base, E->getType());
2856   }
2857   case CK_ToUnion:
2858     return EmitAggExprToLValue(E);
2859   case CK_BaseToDerived: {
2860     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2861     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2862 
2863     LValue LV = EmitLValue(E->getSubExpr());
2864 
2865     // Perform the base-to-derived conversion
2866     llvm::Value *Derived =
2867       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
2868                                E->path_begin(), E->path_end(),
2869                                /*NullCheckValue=*/false);
2870 
2871     // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
2872     // performed and the object is not of the derived type.
2873     if (sanitizePerformTypeCheck())
2874       EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
2875                     Derived, E->getType());
2876 
2877     return MakeAddrLValue(Derived, E->getType());
2878   }
2879   case CK_LValueBitCast: {
2880     // This must be a reinterpret_cast (or c-style equivalent).
2881     const auto *CE = cast<ExplicitCastExpr>(E);
2882 
2883     LValue LV = EmitLValue(E->getSubExpr());
2884     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2885                                            ConvertType(CE->getTypeAsWritten()));
2886     return MakeAddrLValue(V, E->getType());
2887   }
2888   case CK_ObjCObjectLValueCast: {
2889     LValue LV = EmitLValue(E->getSubExpr());
2890     QualType ToType = getContext().getLValueReferenceType(E->getType());
2891     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2892                                            ConvertType(ToType));
2893     return MakeAddrLValue(V, E->getType());
2894   }
2895   case CK_ZeroToOCLEvent:
2896     llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
2897   }
2898 
2899   llvm_unreachable("Unhandled lvalue cast kind?");
2900 }
2901 
2902 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
2903   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
2904   return getOpaqueLValueMapping(e);
2905 }
2906 
2907 RValue CodeGenFunction::EmitRValueForField(LValue LV,
2908                                            const FieldDecl *FD,
2909                                            SourceLocation Loc) {
2910   QualType FT = FD->getType();
2911   LValue FieldLV = EmitLValueForField(LV, FD);
2912   switch (getEvaluationKind(FT)) {
2913   case TEK_Complex:
2914     return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
2915   case TEK_Aggregate:
2916     return FieldLV.asAggregateRValue();
2917   case TEK_Scalar:
2918     return EmitLoadOfLValue(FieldLV, Loc);
2919   }
2920   llvm_unreachable("bad evaluation kind");
2921 }
2922 
2923 //===--------------------------------------------------------------------===//
2924 //                             Expression Emission
2925 //===--------------------------------------------------------------------===//
2926 
2927 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2928                                      ReturnValueSlot ReturnValue) {
2929   if (CGDebugInfo *DI = getDebugInfo()) {
2930     SourceLocation Loc = E->getLocStart();
2931     // Force column info to be generated so we can differentiate
2932     // multiple call sites on the same line in the debug info.
2933     // FIXME: This is insufficient. Two calls coming from the same macro
2934     // expansion will still get the same line/column and break debug info. It's
2935     // possible that LLVM can be fixed to not rely on this uniqueness, at which
2936     // point this workaround can be removed.
2937     const FunctionDecl* Callee = E->getDirectCallee();
2938     bool ForceColumnInfo = Callee && Callee->isInlineSpecified();
2939     DI->EmitLocation(Builder, Loc, ForceColumnInfo);
2940   }
2941 
2942   // Builtins never have block type.
2943   if (E->getCallee()->getType()->isBlockPointerType())
2944     return EmitBlockCallExpr(E, ReturnValue);
2945 
2946   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
2947     return EmitCXXMemberCallExpr(CE, ReturnValue);
2948 
2949   if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
2950     return EmitCUDAKernelCallExpr(CE, ReturnValue);
2951 
2952   const Decl *TargetDecl = E->getCalleeDecl();
2953   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2954     if (unsigned builtinID = FD->getBuiltinID())
2955       return EmitBuiltinExpr(FD, builtinID, E);
2956   }
2957 
2958   if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
2959     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
2960       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
2961 
2962   if (const auto *PseudoDtor =
2963           dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2964     QualType DestroyedType = PseudoDtor->getDestroyedType();
2965     if (getLangOpts().ObjCAutoRefCount &&
2966         DestroyedType->isObjCLifetimeType() &&
2967         (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2968          DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
2969       // Automatic Reference Counting:
2970       //   If the pseudo-expression names a retainable object with weak or
2971       //   strong lifetime, the object shall be released.
2972       Expr *BaseExpr = PseudoDtor->getBase();
2973       llvm::Value *BaseValue = nullptr;
2974       Qualifiers BaseQuals;
2975 
2976       // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
2977       if (PseudoDtor->isArrow()) {
2978         BaseValue = EmitScalarExpr(BaseExpr);
2979         const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2980         BaseQuals = PTy->getPointeeType().getQualifiers();
2981       } else {
2982         LValue BaseLV = EmitLValue(BaseExpr);
2983         BaseValue = BaseLV.getAddress();
2984         QualType BaseTy = BaseExpr->getType();
2985         BaseQuals = BaseTy.getQualifiers();
2986       }
2987 
2988       switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2989       case Qualifiers::OCL_None:
2990       case Qualifiers::OCL_ExplicitNone:
2991       case Qualifiers::OCL_Autoreleasing:
2992         break;
2993 
2994       case Qualifiers::OCL_Strong:
2995         EmitARCRelease(Builder.CreateLoad(BaseValue,
2996                           PseudoDtor->getDestroyedType().isVolatileQualified()),
2997                        ARCPreciseLifetime);
2998         break;
2999 
3000       case Qualifiers::OCL_Weak:
3001         EmitARCDestroyWeak(BaseValue);
3002         break;
3003       }
3004     } else {
3005       // C++ [expr.pseudo]p1:
3006       //   The result shall only be used as the operand for the function call
3007       //   operator (), and the result of such a call has type void. The only
3008       //   effect is the evaluation of the postfix-expression before the dot or
3009       //   arrow.
3010       EmitScalarExpr(E->getCallee());
3011     }
3012 
3013     return RValue::get(nullptr);
3014   }
3015 
3016   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
3017   return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3018                   TargetDecl);
3019 }
3020 
3021 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
3022   // Comma expressions just emit their LHS then their RHS as an l-value.
3023   if (E->getOpcode() == BO_Comma) {
3024     EmitIgnoredExpr(E->getLHS());
3025     EnsureInsertPoint();
3026     return EmitLValue(E->getRHS());
3027   }
3028 
3029   if (E->getOpcode() == BO_PtrMemD ||
3030       E->getOpcode() == BO_PtrMemI)
3031     return EmitPointerToDataMemberBinaryExpr(E);
3032 
3033   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
3034 
3035   // Note that in all of these cases, __block variables need the RHS
3036   // evaluated first just in case the variable gets moved by the RHS.
3037 
3038   switch (getEvaluationKind(E->getType())) {
3039   case TEK_Scalar: {
3040     switch (E->getLHS()->getType().getObjCLifetime()) {
3041     case Qualifiers::OCL_Strong:
3042       return EmitARCStoreStrong(E, /*ignored*/ false).first;
3043 
3044     case Qualifiers::OCL_Autoreleasing:
3045       return EmitARCStoreAutoreleasing(E).first;
3046 
3047     // No reason to do any of these differently.
3048     case Qualifiers::OCL_None:
3049     case Qualifiers::OCL_ExplicitNone:
3050     case Qualifiers::OCL_Weak:
3051       break;
3052     }
3053 
3054     RValue RV = EmitAnyExpr(E->getRHS());
3055     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
3056     EmitStoreThroughLValue(RV, LV);
3057     return LV;
3058   }
3059 
3060   case TEK_Complex:
3061     return EmitComplexAssignmentLValue(E);
3062 
3063   case TEK_Aggregate:
3064     return EmitAggExprToLValue(E);
3065   }
3066   llvm_unreachable("bad evaluation kind");
3067 }
3068 
3069 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
3070   RValue RV = EmitCallExpr(E);
3071 
3072   if (!RV.isScalar())
3073     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
3074 
3075   assert(E->getCallReturnType()->isReferenceType() &&
3076          "Can't have a scalar return unless the return type is a "
3077          "reference type!");
3078 
3079   return MakeAddrLValue(RV.getScalarVal(), E->getType());
3080 }
3081 
3082 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3083   // FIXME: This shouldn't require another copy.
3084   return EmitAggExprToLValue(E);
3085 }
3086 
3087 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
3088   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3089          && "binding l-value to type which needs a temporary");
3090   AggValueSlot Slot = CreateAggTemp(E->getType());
3091   EmitCXXConstructExpr(E, Slot);
3092   return MakeAddrLValue(Slot.getAddr(), E->getType());
3093 }
3094 
3095 LValue
3096 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
3097   return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
3098 }
3099 
3100 llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3101   return Builder.CreateBitCast(CGM.GetAddrOfUuidDescriptor(E),
3102                                ConvertType(E->getType())->getPointerTo());
3103 }
3104 
3105 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
3106   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
3107 }
3108 
3109 LValue
3110 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
3111   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
3112   Slot.setExternallyDestructed();
3113   EmitAggExpr(E->getSubExpr(), Slot);
3114   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
3115   return MakeAddrLValue(Slot.getAddr(), E->getType());
3116 }
3117 
3118 LValue
3119 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
3120   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
3121   EmitLambdaExpr(E, Slot);
3122   return MakeAddrLValue(Slot.getAddr(), E->getType());
3123 }
3124 
3125 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
3126   RValue RV = EmitObjCMessageExpr(E);
3127 
3128   if (!RV.isScalar())
3129     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
3130 
3131   assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
3132          "Can't have a scalar return unless the return type is a "
3133          "reference type!");
3134 
3135   return MakeAddrLValue(RV.getScalarVal(), E->getType());
3136 }
3137 
3138 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
3139   llvm::Value *V =
3140     CGM.getObjCRuntime().GetSelector(*this, E->getSelector(), true);
3141   return MakeAddrLValue(V, E->getType());
3142 }
3143 
3144 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3145                                              const ObjCIvarDecl *Ivar) {
3146   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
3147 }
3148 
3149 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3150                                           llvm::Value *BaseValue,
3151                                           const ObjCIvarDecl *Ivar,
3152                                           unsigned CVRQualifiers) {
3153   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
3154                                                    Ivar, CVRQualifiers);
3155 }
3156 
3157 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
3158   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
3159   llvm::Value *BaseValue = nullptr;
3160   const Expr *BaseExpr = E->getBase();
3161   Qualifiers BaseQuals;
3162   QualType ObjectTy;
3163   if (E->isArrow()) {
3164     BaseValue = EmitScalarExpr(BaseExpr);
3165     ObjectTy = BaseExpr->getType()->getPointeeType();
3166     BaseQuals = ObjectTy.getQualifiers();
3167   } else {
3168     LValue BaseLV = EmitLValue(BaseExpr);
3169     // FIXME: this isn't right for bitfields.
3170     BaseValue = BaseLV.getAddress();
3171     ObjectTy = BaseExpr->getType();
3172     BaseQuals = ObjectTy.getQualifiers();
3173   }
3174 
3175   LValue LV =
3176     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3177                       BaseQuals.getCVRQualifiers());
3178   setObjCGCLValueClass(getContext(), E, LV);
3179   return LV;
3180 }
3181 
3182 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
3183   // Can only get l-value for message expression returning aggregate type
3184   RValue RV = EmitAnyExprToTemp(E);
3185   return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
3186 }
3187 
3188 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
3189                                  const CallExpr *E, ReturnValueSlot ReturnValue,
3190                                  const Decl *TargetDecl) {
3191   // Get the actual function type. The callee type will always be a pointer to
3192   // function type or a block pointer type.
3193   assert(CalleeType->isFunctionPointerType() &&
3194          "Call must have function pointer type!");
3195 
3196   CalleeType = getContext().getCanonicalType(CalleeType);
3197 
3198   const auto *FnType =
3199       cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
3200 
3201   // Force column info to differentiate multiple inlined call sites on
3202   // the same line, analoguous to EmitCallExpr.
3203   // FIXME: This is insufficient. Two calls coming from the same macro expansion
3204   // will still get the same line/column and break debug info. It's possible
3205   // that LLVM can be fixed to not rely on this uniqueness, at which point this
3206   // workaround can be removed.
3207   bool ForceColumnInfo = false;
3208   if (const FunctionDecl* FD = dyn_cast_or_null<const FunctionDecl>(TargetDecl))
3209     ForceColumnInfo = FD->isInlineSpecified();
3210 
3211   if (getLangOpts().CPlusPlus && SanOpts->Function &&
3212       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3213     if (llvm::Constant *PrefixSig =
3214             CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
3215       SanitizerScope SanScope(this);
3216       llvm::Constant *FTRTTIConst =
3217           CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3218       llvm::Type *PrefixStructTyElems[] = {
3219         PrefixSig->getType(),
3220         FTRTTIConst->getType()
3221       };
3222       llvm::StructType *PrefixStructTy = llvm::StructType::get(
3223           CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3224 
3225       llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3226           Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3227       llvm::Value *CalleeSigPtr =
3228           Builder.CreateConstGEP2_32(CalleePrefixStruct, 0, 0);
3229       llvm::Value *CalleeSig = Builder.CreateLoad(CalleeSigPtr);
3230       llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3231 
3232       llvm::BasicBlock *Cont = createBasicBlock("cont");
3233       llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3234       Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3235 
3236       EmitBlock(TypeCheck);
3237       llvm::Value *CalleeRTTIPtr =
3238           Builder.CreateConstGEP2_32(CalleePrefixStruct, 0, 1);
3239       llvm::Value *CalleeRTTI = Builder.CreateLoad(CalleeRTTIPtr);
3240       llvm::Value *CalleeRTTIMatch =
3241           Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
3242       llvm::Constant *StaticData[] = {
3243         EmitCheckSourceLocation(E->getLocStart()),
3244         EmitCheckTypeDescriptor(CalleeType)
3245       };
3246       EmitCheck(CalleeRTTIMatch,
3247                 "function_type_mismatch",
3248                 StaticData,
3249                 Callee,
3250                 CRK_Recoverable);
3251 
3252       Builder.CreateBr(Cont);
3253       EmitBlock(Cont);
3254     }
3255   }
3256 
3257   CallArgList Args;
3258   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arg_begin(),
3259                E->arg_end(), E->getDirectCallee(), /*ParamsToSkip*/ 0,
3260                ForceColumnInfo);
3261 
3262   const CGFunctionInfo &FnInfo =
3263     CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
3264 
3265   // C99 6.5.2.2p6:
3266   //   If the expression that denotes the called function has a type
3267   //   that does not include a prototype, [the default argument
3268   //   promotions are performed]. If the number of arguments does not
3269   //   equal the number of parameters, the behavior is undefined. If
3270   //   the function is defined with a type that includes a prototype,
3271   //   and either the prototype ends with an ellipsis (, ...) or the
3272   //   types of the arguments after promotion are not compatible with
3273   //   the types of the parameters, the behavior is undefined. If the
3274   //   function is defined with a type that does not include a
3275   //   prototype, and the types of the arguments after promotion are
3276   //   not compatible with those of the parameters after promotion,
3277   //   the behavior is undefined [except in some trivial cases].
3278   // That is, in the general case, we should assume that a call
3279   // through an unprototyped function type works like a *non-variadic*
3280   // call.  The way we make this work is to cast to the exact type
3281   // of the promoted arguments.
3282   if (isa<FunctionNoProtoType>(FnType)) {
3283     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
3284     CalleeTy = CalleeTy->getPointerTo();
3285     Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3286   }
3287 
3288   return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
3289 }
3290 
3291 LValue CodeGenFunction::
3292 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
3293   llvm::Value *BaseV;
3294   if (E->getOpcode() == BO_PtrMemI)
3295     BaseV = EmitScalarExpr(E->getLHS());
3296   else
3297     BaseV = EmitLValue(E->getLHS()).getAddress();
3298 
3299   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3300 
3301   const MemberPointerType *MPT
3302     = E->getRHS()->getType()->getAs<MemberPointerType>();
3303 
3304   llvm::Value *AddV = CGM.getCXXABI().EmitMemberDataPointerAddress(
3305       *this, E, BaseV, OffsetV, MPT);
3306 
3307   return MakeAddrLValue(AddV, MPT->getPointeeType());
3308 }
3309 
3310 /// Given the address of a temporary variable, produce an r-value of
3311 /// its type.
3312 RValue CodeGenFunction::convertTempToRValue(llvm::Value *addr,
3313                                             QualType type,
3314                                             SourceLocation loc) {
3315   LValue lvalue = MakeNaturalAlignAddrLValue(addr, type);
3316   switch (getEvaluationKind(type)) {
3317   case TEK_Complex:
3318     return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
3319   case TEK_Aggregate:
3320     return lvalue.asAggregateRValue();
3321   case TEK_Scalar:
3322     return RValue::get(EmitLoadOfScalar(lvalue, loc));
3323   }
3324   llvm_unreachable("bad evaluation kind");
3325 }
3326 
3327 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
3328   assert(Val->getType()->isFPOrFPVectorTy());
3329   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
3330     return;
3331 
3332   llvm::MDBuilder MDHelper(getLLVMContext());
3333   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
3334 
3335   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
3336 }
3337 
3338 namespace {
3339   struct LValueOrRValue {
3340     LValue LV;
3341     RValue RV;
3342   };
3343 }
3344 
3345 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3346                                            const PseudoObjectExpr *E,
3347                                            bool forLValue,
3348                                            AggValueSlot slot) {
3349   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3350 
3351   // Find the result expression, if any.
3352   const Expr *resultExpr = E->getResultExpr();
3353   LValueOrRValue result;
3354 
3355   for (PseudoObjectExpr::const_semantics_iterator
3356          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3357     const Expr *semantic = *i;
3358 
3359     // If this semantic expression is an opaque value, bind it
3360     // to the result of its source expression.
3361     if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3362 
3363       // If this is the result expression, we may need to evaluate
3364       // directly into the slot.
3365       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3366       OVMA opaqueData;
3367       if (ov == resultExpr && ov->isRValue() && !forLValue &&
3368           CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
3369         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3370 
3371         LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3372         opaqueData = OVMA::bind(CGF, ov, LV);
3373         result.RV = slot.asRValue();
3374 
3375       // Otherwise, emit as normal.
3376       } else {
3377         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3378 
3379         // If this is the result, also evaluate the result now.
3380         if (ov == resultExpr) {
3381           if (forLValue)
3382             result.LV = CGF.EmitLValue(ov);
3383           else
3384             result.RV = CGF.EmitAnyExpr(ov, slot);
3385         }
3386       }
3387 
3388       opaques.push_back(opaqueData);
3389 
3390     // Otherwise, if the expression is the result, evaluate it
3391     // and remember the result.
3392     } else if (semantic == resultExpr) {
3393       if (forLValue)
3394         result.LV = CGF.EmitLValue(semantic);
3395       else
3396         result.RV = CGF.EmitAnyExpr(semantic, slot);
3397 
3398     // Otherwise, evaluate the expression in an ignored context.
3399     } else {
3400       CGF.EmitIgnoredExpr(semantic);
3401     }
3402   }
3403 
3404   // Unbind all the opaques now.
3405   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3406     opaques[i].unbind(CGF);
3407 
3408   return result;
3409 }
3410 
3411 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3412                                                AggValueSlot slot) {
3413   return emitPseudoObjectExpr(*this, E, false, slot).RV;
3414 }
3415 
3416 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3417   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3418 }
3419