1f22ef01cSRoman Divacky //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This contains code to emit Expr nodes as LLVM code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14e580952dSDimitry Andric #include "CGCXXABI.h"
15139f7f9bSDimitry Andric #include "CGCall.h"
16e7145dcbSDimitry Andric #include "CGCleanup.h"
173b0f4066SDimitry Andric #include "CGDebugInfo.h"
18f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
1939d628a0SDimitry Andric #include "CGOpenMPRuntime.h"
20139f7f9bSDimitry Andric #include "CGRecordLayout.h"
21e7145dcbSDimitry Andric #include "CodeGenFunction.h"
22139f7f9bSDimitry Andric #include "CodeGenModule.h"
236122f3e6SDimitry Andric #include "TargetInfo.h"
24f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
2559d1ed5bSDimitry Andric #include "clang/AST/Attr.h"
2639d628a0SDimitry Andric #include "clang/AST/DeclObjC.h"
2744290647SDimitry Andric #include "clang/AST/NSAPI.h"
28ffd1746dSEd Schouten #include "clang/Frontend/CodeGenOptions.h"
293861d79fSDimitry Andric #include "llvm/ADT/Hashing.h"
3039d628a0SDimitry Andric #include "llvm/ADT/StringExtras.h"
31139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
32139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
33139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
34139f7f9bSDimitry Andric #include "llvm/IR/MDBuilder.h"
35139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
3633956c43SDimitry Andric #include "llvm/Support/MathExtras.h"
37e7145dcbSDimitry Andric #include "llvm/Support/Path.h"
38e7145dcbSDimitry Andric #include "llvm/Transforms/Utils/SanitizerStats.h"
39139f7f9bSDimitry Andric 
4044290647SDimitry Andric #include <string>
4144290647SDimitry Andric 
42f22ef01cSRoman Divacky using namespace clang;
43f22ef01cSRoman Divacky using namespace CodeGen;
44f22ef01cSRoman Divacky 
45f22ef01cSRoman Divacky //===--------------------------------------------------------------------===//
46f22ef01cSRoman Divacky //                        Miscellaneous Helper Methods
47f22ef01cSRoman Divacky //===--------------------------------------------------------------------===//
48f22ef01cSRoman Divacky 
492754fe60SDimitry Andric llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
502754fe60SDimitry Andric   unsigned addressSpace =
512754fe60SDimitry Andric     cast<llvm::PointerType>(value->getType())->getAddressSpace();
522754fe60SDimitry Andric 
536122f3e6SDimitry Andric   llvm::PointerType *destType = Int8PtrTy;
542754fe60SDimitry Andric   if (addressSpace)
552754fe60SDimitry Andric     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
562754fe60SDimitry Andric 
572754fe60SDimitry Andric   if (value->getType() == destType) return value;
582754fe60SDimitry Andric   return Builder.CreateBitCast(value, destType);
592754fe60SDimitry Andric }
602754fe60SDimitry Andric 
61f22ef01cSRoman Divacky /// CreateTempAlloca - This creates a alloca and inserts it into the entry
62f22ef01cSRoman Divacky /// block.
630623d748SDimitry Andric Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
64edd7eaddSDimitry Andric                                           const Twine &Name,
65edd7eaddSDimitry Andric                                           llvm::Value *ArraySize,
66edd7eaddSDimitry Andric                                           bool CastToDefaultAddrSpace) {
67edd7eaddSDimitry Andric   auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
680623d748SDimitry Andric   Alloca->setAlignment(Align.getQuantity());
69edd7eaddSDimitry Andric   llvm::Value *V = Alloca;
70edd7eaddSDimitry Andric   // Alloca always returns a pointer in alloca address space, which may
71edd7eaddSDimitry Andric   // be different from the type defined by the language. For example,
72edd7eaddSDimitry Andric   // in C++ the auto variables are in the default address space. Therefore
73edd7eaddSDimitry Andric   // cast alloca to the default address space when necessary.
74edd7eaddSDimitry Andric   if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
75edd7eaddSDimitry Andric     auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
76edd7eaddSDimitry Andric     V = getTargetHooks().performAddrSpaceCast(
77edd7eaddSDimitry Andric         *this, V, getASTAllocaAddressSpace(), LangAS::Default,
78edd7eaddSDimitry Andric         Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
790623d748SDimitry Andric   }
800623d748SDimitry Andric 
81edd7eaddSDimitry Andric   return Address(V, Align);
82edd7eaddSDimitry Andric }
83edd7eaddSDimitry Andric 
84edd7eaddSDimitry Andric /// CreateTempAlloca - This creates an alloca and inserts it into the entry
85edd7eaddSDimitry Andric /// block if \p ArraySize is nullptr, otherwise inserts it at the current
86edd7eaddSDimitry Andric /// insertion point of the builder.
876122f3e6SDimitry Andric llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
88edd7eaddSDimitry Andric                                                     const Twine &Name,
89edd7eaddSDimitry Andric                                                     llvm::Value *ArraySize) {
90edd7eaddSDimitry Andric   if (ArraySize)
91edd7eaddSDimitry Andric     return Builder.CreateAlloca(Ty, ArraySize, Name);
9220e90f04SDimitry Andric   return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
93edd7eaddSDimitry Andric                               ArraySize, Name, AllocaInsertPt);
94f22ef01cSRoman Divacky }
95f22ef01cSRoman Divacky 
960623d748SDimitry Andric /// CreateDefaultAlignTempAlloca - This creates an alloca with the
970623d748SDimitry Andric /// default alignment of the corresponding LLVM type, which is *not*
980623d748SDimitry Andric /// guaranteed to be related in any way to the expected alignment of
990623d748SDimitry Andric /// an AST type that might have been lowered to Ty.
1000623d748SDimitry Andric Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1010623d748SDimitry Andric                                                       const Twine &Name) {
1020623d748SDimitry Andric   CharUnits Align =
1030623d748SDimitry Andric     CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
1040623d748SDimitry Andric   return CreateTempAlloca(Ty, Align, Name);
1050623d748SDimitry Andric }
1060623d748SDimitry Andric 
1070623d748SDimitry Andric void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
1080623d748SDimitry Andric   assert(isa<llvm::AllocaInst>(Var.getPointer()));
1090623d748SDimitry Andric   auto *Store = new llvm::StoreInst(Init, Var.getPointer());
1100623d748SDimitry Andric   Store->setAlignment(Var.getAlignment().getQuantity());
111f22ef01cSRoman Divacky   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
1120623d748SDimitry Andric   Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
113f22ef01cSRoman Divacky }
114f22ef01cSRoman Divacky 
1150623d748SDimitry Andric Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
116f22ef01cSRoman Divacky   CharUnits Align = getContext().getTypeAlignInChars(Ty);
1170623d748SDimitry Andric   return CreateTempAlloca(ConvertType(Ty), Align, Name);
118f22ef01cSRoman Divacky }
119f22ef01cSRoman Divacky 
120edd7eaddSDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
121edd7eaddSDimitry Andric                                        bool CastToDefaultAddrSpace) {
122f22ef01cSRoman Divacky   // FIXME: Should we prefer the preferred type alignment here?
123edd7eaddSDimitry Andric   return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
124edd7eaddSDimitry Andric                        CastToDefaultAddrSpace);
1250623d748SDimitry Andric }
1260623d748SDimitry Andric 
1270623d748SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
128edd7eaddSDimitry Andric                                        const Twine &Name,
129edd7eaddSDimitry Andric                                        bool CastToDefaultAddrSpace) {
130edd7eaddSDimitry Andric   return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
131edd7eaddSDimitry Andric                           CastToDefaultAddrSpace);
132f22ef01cSRoman Divacky }
133f22ef01cSRoman Divacky 
134f22ef01cSRoman Divacky /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
135f22ef01cSRoman Divacky /// expression and compare the result against zero, returning an Int1Ty value.
136f22ef01cSRoman Divacky llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
13759d1ed5bSDimitry Andric   PGO.setCurrentStmt(E);
138e580952dSDimitry Andric   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
139e580952dSDimitry Andric     llvm::Value *MemPtr = EmitScalarExpr(E);
1402754fe60SDimitry Andric     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
141f22ef01cSRoman Divacky   }
142e580952dSDimitry Andric 
143e580952dSDimitry Andric   QualType BoolTy = getContext().BoolTy;
1440623d748SDimitry Andric   SourceLocation Loc = E->getExprLoc();
145f22ef01cSRoman Divacky   if (!E->getType()->isAnyComplexType())
1460623d748SDimitry Andric     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
147f22ef01cSRoman Divacky 
1480623d748SDimitry Andric   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
1490623d748SDimitry Andric                                        Loc);
150f22ef01cSRoman Divacky }
151f22ef01cSRoman Divacky 
1522754fe60SDimitry Andric /// EmitIgnoredExpr - Emit code to compute the specified expression,
1532754fe60SDimitry Andric /// ignoring the result.
1542754fe60SDimitry Andric void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
1552754fe60SDimitry Andric   if (E->isRValue())
1562754fe60SDimitry Andric     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
1572754fe60SDimitry Andric 
1582754fe60SDimitry Andric   // Just emit it as an l-value and drop the result.
1592754fe60SDimitry Andric   EmitLValue(E);
1602754fe60SDimitry Andric }
1612754fe60SDimitry Andric 
1622754fe60SDimitry Andric /// EmitAnyExpr - Emit code to compute the specified expression which
1632754fe60SDimitry Andric /// can have any type.  The result is returned as an RValue struct.
1642754fe60SDimitry Andric /// If this is an aggregate expression, AggSlot indicates where the
165f22ef01cSRoman Divacky /// result should be returned.
1667ae0e2c9SDimitry Andric RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
1677ae0e2c9SDimitry Andric                                     AggValueSlot aggSlot,
1687ae0e2c9SDimitry Andric                                     bool ignoreResult) {
169139f7f9bSDimitry Andric   switch (getEvaluationKind(E->getType())) {
170139f7f9bSDimitry Andric   case TEK_Scalar:
1717ae0e2c9SDimitry Andric     return RValue::get(EmitScalarExpr(E, ignoreResult));
172139f7f9bSDimitry Andric   case TEK_Complex:
1737ae0e2c9SDimitry Andric     return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
174139f7f9bSDimitry Andric   case TEK_Aggregate:
1757ae0e2c9SDimitry Andric     if (!ignoreResult && aggSlot.isIgnored())
1767ae0e2c9SDimitry Andric       aggSlot = CreateAggTemp(E->getType(), "agg-temp");
1777ae0e2c9SDimitry Andric     EmitAggExpr(E, aggSlot);
1787ae0e2c9SDimitry Andric     return aggSlot.asRValue();
179f22ef01cSRoman Divacky   }
180139f7f9bSDimitry Andric   llvm_unreachable("bad evaluation kind");
181139f7f9bSDimitry Andric }
182f22ef01cSRoman Divacky 
183f22ef01cSRoman Divacky /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
184f22ef01cSRoman Divacky /// always be accessible even if no aggregate location is provided.
1852754fe60SDimitry Andric RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
1862754fe60SDimitry Andric   AggValueSlot AggSlot = AggValueSlot::ignored();
187f22ef01cSRoman Divacky 
188139f7f9bSDimitry Andric   if (hasAggregateEvaluationKind(E->getType()))
1892754fe60SDimitry Andric     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
1902754fe60SDimitry Andric   return EmitAnyExpr(E, AggSlot);
191f22ef01cSRoman Divacky }
192f22ef01cSRoman Divacky 
193f22ef01cSRoman Divacky /// EmitAnyExprToMem - Evaluate an expression into a given memory
194f22ef01cSRoman Divacky /// location.
195f22ef01cSRoman Divacky void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
1960623d748SDimitry Andric                                        Address Location,
19717a519f9SDimitry Andric                                        Qualifiers Quals,
198f22ef01cSRoman Divacky                                        bool IsInit) {
199dff0c46cSDimitry Andric   // FIXME: This function should take an LValue as an argument.
200139f7f9bSDimitry Andric   switch (getEvaluationKind(E->getType())) {
201139f7f9bSDimitry Andric   case TEK_Complex:
2020623d748SDimitry Andric     EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
203139f7f9bSDimitry Andric                               /*isInit*/ false);
204139f7f9bSDimitry Andric     return;
205139f7f9bSDimitry Andric 
206139f7f9bSDimitry Andric   case TEK_Aggregate: {
2070623d748SDimitry Andric     EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
2086122f3e6SDimitry Andric                                          AggValueSlot::IsDestructed_t(IsInit),
2096122f3e6SDimitry Andric                                          AggValueSlot::DoesNotNeedGCBarriers,
2106122f3e6SDimitry Andric                                          AggValueSlot::IsAliased_t(!IsInit)));
211139f7f9bSDimitry Andric     return;
212139f7f9bSDimitry Andric   }
213139f7f9bSDimitry Andric 
214139f7f9bSDimitry Andric   case TEK_Scalar: {
215f22ef01cSRoman Divacky     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
216e580952dSDimitry Andric     LValue LV = MakeAddrLValue(Location, E->getType());
21717a519f9SDimitry Andric     EmitStoreThroughLValue(RV, LV);
218139f7f9bSDimitry Andric     return;
219f22ef01cSRoman Divacky   }
220f22ef01cSRoman Divacky   }
221139f7f9bSDimitry Andric   llvm_unreachable("bad evaluation kind");
222139f7f9bSDimitry Andric }
223f22ef01cSRoman Divacky 
224f785676fSDimitry Andric static void
225f785676fSDimitry Andric pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
2260623d748SDimitry Andric                      const Expr *E, Address ReferenceTemporary) {
22717a519f9SDimitry Andric   // Objective-C++ ARC:
22817a519f9SDimitry Andric   //   If we are binding a reference to a temporary that has ownership, we
22917a519f9SDimitry Andric   //   need to perform retain/release operations on the temporary.
230f785676fSDimitry Andric   //
231f785676fSDimitry Andric   // FIXME: This should be looking at E, not M.
2320623d748SDimitry Andric   if (auto Lifetime = M->getType().getObjCLifetime()) {
2330623d748SDimitry Andric     switch (Lifetime) {
23417a519f9SDimitry Andric     case Qualifiers::OCL_None:
23517a519f9SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
236f785676fSDimitry Andric       // Carry on to normal cleanup handling.
237f785676fSDimitry Andric       break;
238f785676fSDimitry Andric 
23917a519f9SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
240f785676fSDimitry Andric       // Nothing to do; cleaned up by an autorelease pool.
241f785676fSDimitry Andric       return;
24217a519f9SDimitry Andric 
243f785676fSDimitry Andric     case Qualifiers::OCL_Strong:
24417a519f9SDimitry Andric     case Qualifiers::OCL_Weak:
245f785676fSDimitry Andric       switch (StorageDuration Duration = M->getStorageDuration()) {
246f785676fSDimitry Andric       case SD_Static:
247f785676fSDimitry Andric         // Note: we intentionally do not register a cleanup to release
248f785676fSDimitry Andric         // the object on program termination.
249f785676fSDimitry Andric         return;
250f785676fSDimitry Andric 
251f785676fSDimitry Andric       case SD_Thread:
252f785676fSDimitry Andric         // FIXME: We should probably register a cleanup in this case.
253f785676fSDimitry Andric         return;
254f785676fSDimitry Andric 
255f785676fSDimitry Andric       case SD_Automatic:
256f785676fSDimitry Andric       case SD_FullExpression:
257f785676fSDimitry Andric         CodeGenFunction::Destroyer *Destroy;
258f785676fSDimitry Andric         CleanupKind CleanupKind;
259f785676fSDimitry Andric         if (Lifetime == Qualifiers::OCL_Strong) {
260f785676fSDimitry Andric           const ValueDecl *VD = M->getExtendingDecl();
261f785676fSDimitry Andric           bool Precise =
262f785676fSDimitry Andric               VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
263f785676fSDimitry Andric           CleanupKind = CGF.getARCCleanupKind();
264f785676fSDimitry Andric           Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
265f785676fSDimitry Andric                             : &CodeGenFunction::destroyARCStrongImprecise;
266f785676fSDimitry Andric         } else {
267f785676fSDimitry Andric           // __weak objects always get EH cleanups; otherwise, exceptions
268f785676fSDimitry Andric           // could cause really nasty crashes instead of mere leaks.
269f785676fSDimitry Andric           CleanupKind = NormalAndEHCleanup;
270f785676fSDimitry Andric           Destroy = &CodeGenFunction::destroyARCWeak;
271f785676fSDimitry Andric         }
272f785676fSDimitry Andric         if (Duration == SD_FullExpression)
273f785676fSDimitry Andric           CGF.pushDestroy(CleanupKind, ReferenceTemporary,
2740623d748SDimitry Andric                           M->getType(), *Destroy,
275f785676fSDimitry Andric                           CleanupKind & EHCleanup);
276f785676fSDimitry Andric         else
277f785676fSDimitry Andric           CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
2780623d748SDimitry Andric                                           M->getType(),
279f785676fSDimitry Andric                                           *Destroy, CleanupKind & EHCleanup);
280f785676fSDimitry Andric         return;
281f785676fSDimitry Andric 
282f785676fSDimitry Andric       case SD_Dynamic:
283f785676fSDimitry Andric         llvm_unreachable("temporary cannot have dynamic storage duration");
284f785676fSDimitry Andric       }
285f785676fSDimitry Andric       llvm_unreachable("unknown storage duration");
286f785676fSDimitry Andric     }
28717a519f9SDimitry Andric   }
28817a519f9SDimitry Andric 
28959d1ed5bSDimitry Andric   CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
290f785676fSDimitry Andric   if (const RecordType *RT =
291139f7f9bSDimitry Andric           E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
292284c1978SDimitry Andric     // Get the destructor for the reference temporary.
29359d1ed5bSDimitry Andric     auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
294ffd1746dSEd Schouten     if (!ClassDecl->hasTrivialDestructor())
295ffd1746dSEd Schouten       ReferenceTemporaryDtor = ClassDecl->getDestructor();
296f22ef01cSRoman Divacky   }
297f785676fSDimitry Andric 
298f785676fSDimitry Andric   if (!ReferenceTemporaryDtor)
299f785676fSDimitry Andric     return;
300f785676fSDimitry Andric 
301f785676fSDimitry Andric   // Call the destructor for the temporary.
302f785676fSDimitry Andric   switch (M->getStorageDuration()) {
303f785676fSDimitry Andric   case SD_Static:
304f785676fSDimitry Andric   case SD_Thread: {
305f785676fSDimitry Andric     llvm::Constant *CleanupFn;
306f785676fSDimitry Andric     llvm::Constant *CleanupArg;
307f785676fSDimitry Andric     if (E->getType()->isArrayType()) {
308f785676fSDimitry Andric       CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
3090623d748SDimitry Andric           ReferenceTemporary, E->getType(),
310f785676fSDimitry Andric           CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
311f785676fSDimitry Andric           dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
312f785676fSDimitry Andric       CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
313f785676fSDimitry Andric     } else {
31439d628a0SDimitry Andric       CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
31539d628a0SDimitry Andric                                                StructorType::Complete);
3160623d748SDimitry Andric       CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
317f785676fSDimitry Andric     }
318f785676fSDimitry Andric     CGF.CGM.getCXXABI().registerGlobalDtor(
319f785676fSDimitry Andric         CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
320f785676fSDimitry Andric     break;
321f22ef01cSRoman Divacky   }
322f22ef01cSRoman Divacky 
323f785676fSDimitry Andric   case SD_FullExpression:
324f785676fSDimitry Andric     CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
325f785676fSDimitry Andric                     CodeGenFunction::destroyCXXObject,
326f785676fSDimitry Andric                     CGF.getLangOpts().Exceptions);
327f785676fSDimitry Andric     break;
32817a519f9SDimitry Andric 
329f785676fSDimitry Andric   case SD_Automatic:
330f785676fSDimitry Andric     CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
331f785676fSDimitry Andric                                     ReferenceTemporary, E->getType(),
332f785676fSDimitry Andric                                     CodeGenFunction::destroyCXXObject,
333f785676fSDimitry Andric                                     CGF.getLangOpts().Exceptions);
334f785676fSDimitry Andric     break;
335f785676fSDimitry Andric 
336f785676fSDimitry Andric   case SD_Dynamic:
337f785676fSDimitry Andric     llvm_unreachable("temporary cannot have dynamic storage duration");
338f785676fSDimitry Andric   }
339f785676fSDimitry Andric }
340f785676fSDimitry Andric 
3410623d748SDimitry Andric static Address
342f785676fSDimitry Andric createReferenceTemporary(CodeGenFunction &CGF,
343f785676fSDimitry Andric                          const MaterializeTemporaryExpr *M, const Expr *Inner) {
344f785676fSDimitry Andric   switch (M->getStorageDuration()) {
345f785676fSDimitry Andric   case SD_FullExpression:
34633956c43SDimitry Andric   case SD_Automatic: {
34733956c43SDimitry Andric     // If we have a constant temporary array or record try to promote it into a
34833956c43SDimitry Andric     // constant global under the same rules a normal constant would've been
34933956c43SDimitry Andric     // promoted. This is easier on the optimizer and generally emits fewer
35033956c43SDimitry Andric     // instructions.
35133956c43SDimitry Andric     QualType Ty = Inner->getType();
35233956c43SDimitry Andric     if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
35333956c43SDimitry Andric         (Ty->isArrayType() || Ty->isRecordType()) &&
35433956c43SDimitry Andric         CGF.CGM.isTypeConstant(Ty, true))
35533956c43SDimitry Andric       if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
35633956c43SDimitry Andric         auto *GV = new llvm::GlobalVariable(
35733956c43SDimitry Andric             CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
35833956c43SDimitry Andric             llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
3590623d748SDimitry Andric         CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
3600623d748SDimitry Andric         GV->setAlignment(alignment.getQuantity());
36133956c43SDimitry Andric         // FIXME: Should we put the new global into a COMDAT?
3620623d748SDimitry Andric         return Address(GV, alignment);
36333956c43SDimitry Andric       }
36433956c43SDimitry Andric     return CGF.CreateMemTemp(Ty, "ref.tmp");
36533956c43SDimitry Andric   }
366f785676fSDimitry Andric   case SD_Thread:
367f785676fSDimitry Andric   case SD_Static:
368f785676fSDimitry Andric     return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
369f785676fSDimitry Andric 
370f785676fSDimitry Andric   case SD_Dynamic:
371f785676fSDimitry Andric     llvm_unreachable("temporary can't have dynamic storage duration");
372f785676fSDimitry Andric   }
373f785676fSDimitry Andric   llvm_unreachable("unknown storage duration");
374f785676fSDimitry Andric }
375f785676fSDimitry Andric 
37639d628a0SDimitry Andric LValue CodeGenFunction::
37739d628a0SDimitry Andric EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
378f785676fSDimitry Andric   const Expr *E = M->GetTemporaryExpr();
379f785676fSDimitry Andric 
38039d628a0SDimitry Andric     // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
38139d628a0SDimitry Andric     // as that will cause the lifetime adjustment to be lost for ARC
3820623d748SDimitry Andric   auto ownership = M->getType().getObjCLifetime();
3830623d748SDimitry Andric   if (ownership != Qualifiers::OCL_None &&
3840623d748SDimitry Andric       ownership != Qualifiers::OCL_ExplicitNone) {
3850623d748SDimitry Andric     Address Object = createReferenceTemporary(*this, M, E);
3860623d748SDimitry Andric     if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
3870623d748SDimitry Andric       Object = Address(llvm::ConstantExpr::getBitCast(Var,
3880623d748SDimitry Andric                            ConvertTypeForMem(E->getType())
3890623d748SDimitry Andric                              ->getPointerTo(Object.getAddressSpace())),
3900623d748SDimitry Andric                        Object.getAlignment());
391e7145dcbSDimitry Andric 
392e7145dcbSDimitry Andric       // createReferenceTemporary will promote the temporary to a global with a
393e7145dcbSDimitry Andric       // constant initializer if it can.  It can only do this to a value of
394e7145dcbSDimitry Andric       // ARC-manageable type if the value is global and therefore "immune" to
395e7145dcbSDimitry Andric       // ref-counting operations.  Therefore we have no need to emit either a
396e7145dcbSDimitry Andric       // dynamic initialization or a cleanup and we can just return the address
397e7145dcbSDimitry Andric       // of the temporary.
398e7145dcbSDimitry Andric       if (Var->hasInitializer())
399d8866befSDimitry Andric         return MakeAddrLValue(Object, M->getType(),
400d8866befSDimitry Andric                               LValueBaseInfo(AlignmentSource::Decl, false));
401e7145dcbSDimitry Andric 
402f785676fSDimitry Andric       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
403f785676fSDimitry Andric     }
4040623d748SDimitry Andric     LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
405d8866befSDimitry Andric                                        LValueBaseInfo(AlignmentSource::Decl,
406d8866befSDimitry Andric                                                       false));
407f785676fSDimitry Andric 
40839d628a0SDimitry Andric     switch (getEvaluationKind(E->getType())) {
40939d628a0SDimitry Andric     default: llvm_unreachable("expected scalar or aggregate expression");
41039d628a0SDimitry Andric     case TEK_Scalar:
411f785676fSDimitry Andric       EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
41239d628a0SDimitry Andric       break;
41339d628a0SDimitry Andric     case TEK_Aggregate: {
4140623d748SDimitry Andric       EmitAggExpr(E, AggValueSlot::forAddr(Object,
41539d628a0SDimitry Andric                                            E->getType().getQualifiers(),
41639d628a0SDimitry Andric                                            AggValueSlot::IsDestructed,
41739d628a0SDimitry Andric                                            AggValueSlot::DoesNotNeedGCBarriers,
41839d628a0SDimitry Andric                                            AggValueSlot::IsNotAliased));
41939d628a0SDimitry Andric       break;
42039d628a0SDimitry Andric     }
42139d628a0SDimitry Andric     }
422f785676fSDimitry Andric 
423f785676fSDimitry Andric     pushTemporaryCleanup(*this, M, E, Object);
424f785676fSDimitry Andric     return RefTempDst;
425f785676fSDimitry Andric   }
426f785676fSDimitry Andric 
427f785676fSDimitry Andric   SmallVector<const Expr *, 2> CommaLHSs;
428f785676fSDimitry Andric   SmallVector<SubobjectAdjustment, 2> Adjustments;
429f785676fSDimitry Andric   E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
430f785676fSDimitry Andric 
43139d628a0SDimitry Andric   for (const auto &Ignored : CommaLHSs)
43239d628a0SDimitry Andric     EmitIgnoredExpr(Ignored);
433f785676fSDimitry Andric 
43459d1ed5bSDimitry Andric   if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
435f785676fSDimitry Andric     if (opaque->getType()->isRecordType()) {
436f785676fSDimitry Andric       assert(Adjustments.empty());
437f785676fSDimitry Andric       return EmitOpaqueValueLValue(opaque);
438f785676fSDimitry Andric     }
439f785676fSDimitry Andric   }
440f785676fSDimitry Andric 
441f785676fSDimitry Andric   // Create and initialize the reference temporary.
4420623d748SDimitry Andric   Address Object = createReferenceTemporary(*this, M, E);
4430623d748SDimitry Andric   if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
4440623d748SDimitry Andric     Object = Address(llvm::ConstantExpr::getBitCast(
4450623d748SDimitry Andric         Var, ConvertTypeForMem(E->getType())->getPointerTo()),
4460623d748SDimitry Andric                      Object.getAlignment());
44733956c43SDimitry Andric     // If the temporary is a global and has a constant initializer or is a
44833956c43SDimitry Andric     // constant temporary that we promoted to a global, we may have already
44933956c43SDimitry Andric     // initialized it.
450f785676fSDimitry Andric     if (!Var->hasInitializer()) {
451f785676fSDimitry Andric       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
452f785676fSDimitry Andric       EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
453f785676fSDimitry Andric     }
454f785676fSDimitry Andric   } else {
455e7145dcbSDimitry Andric     switch (M->getStorageDuration()) {
456e7145dcbSDimitry Andric     case SD_Automatic:
457e7145dcbSDimitry Andric     case SD_FullExpression:
458e7145dcbSDimitry Andric       if (auto *Size = EmitLifetimeStart(
459e7145dcbSDimitry Andric               CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
460e7145dcbSDimitry Andric               Object.getPointer())) {
461e7145dcbSDimitry Andric         if (M->getStorageDuration() == SD_Automatic)
462e7145dcbSDimitry Andric           pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
463e7145dcbSDimitry Andric                                                     Object, Size);
464e7145dcbSDimitry Andric         else
465e7145dcbSDimitry Andric           pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
466e7145dcbSDimitry Andric                                                Size);
467e7145dcbSDimitry Andric       }
468e7145dcbSDimitry Andric       break;
469e7145dcbSDimitry Andric     default:
470e7145dcbSDimitry Andric       break;
471e7145dcbSDimitry Andric     }
472f785676fSDimitry Andric     EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
473f785676fSDimitry Andric   }
474f785676fSDimitry Andric   pushTemporaryCleanup(*this, M, E, Object);
475f785676fSDimitry Andric 
476f785676fSDimitry Andric   // Perform derived-to-base casts and/or field accesses, to get from the
477f785676fSDimitry Andric   // temporary object we created (and, potentially, for which we extended
478f785676fSDimitry Andric   // the lifetime) to the subobject we're binding the reference to.
479f22ef01cSRoman Divacky   for (unsigned I = Adjustments.size(); I != 0; --I) {
480f22ef01cSRoman Divacky     SubobjectAdjustment &Adjustment = Adjustments[I-1];
481f22ef01cSRoman Divacky     switch (Adjustment.Kind) {
482f22ef01cSRoman Divacky     case SubobjectAdjustment::DerivedToBaseAdjustment:
483ffd1746dSEd Schouten       Object =
484f785676fSDimitry Andric           GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
485e580952dSDimitry Andric                                 Adjustment.DerivedToBase.BasePath->path_begin(),
486e580952dSDimitry Andric                                 Adjustment.DerivedToBase.BasePath->path_end(),
48739d628a0SDimitry Andric                                 /*NullCheckValue=*/ false, E->getExprLoc());
488f22ef01cSRoman Divacky       break;
489f22ef01cSRoman Divacky 
490f22ef01cSRoman Divacky     case SubobjectAdjustment::FieldAdjustment: {
4910623d748SDimitry Andric       LValue LV = MakeAddrLValue(Object, E->getType(),
492d8866befSDimitry Andric                                  LValueBaseInfo(AlignmentSource::Decl, false));
493f785676fSDimitry Andric       LV = EmitLValueForField(LV, Adjustment.Field);
494f785676fSDimitry Andric       assert(LV.isSimple() &&
495f785676fSDimitry Andric              "materialized temporary field is not a simple lvalue");
496f22ef01cSRoman Divacky       Object = LV.getAddress();
497f22ef01cSRoman Divacky       break;
498f22ef01cSRoman Divacky     }
499f22ef01cSRoman Divacky 
5007ae0e2c9SDimitry Andric     case SubobjectAdjustment::MemberPointerAdjustment: {
501f785676fSDimitry Andric       llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
5020623d748SDimitry Andric       Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
5030623d748SDimitry Andric                                                Adjustment.Ptr.MPT);
5047ae0e2c9SDimitry Andric       break;
5057ae0e2c9SDimitry Andric     }
506f22ef01cSRoman Divacky     }
507f22ef01cSRoman Divacky   }
508f22ef01cSRoman Divacky 
509d8866befSDimitry Andric   return MakeAddrLValue(Object, M->getType(),
510d8866befSDimitry Andric                         LValueBaseInfo(AlignmentSource::Decl, false));
511f22ef01cSRoman Divacky }
512f22ef01cSRoman Divacky 
513ffd1746dSEd Schouten RValue
514f785676fSDimitry Andric CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
515f785676fSDimitry Andric   // Emit the expression as an lvalue.
516f785676fSDimitry Andric   LValue LV = EmitLValue(E);
517f785676fSDimitry Andric   assert(LV.isSimple());
5180623d748SDimitry Andric   llvm::Value *Value = LV.getPointer();
519f785676fSDimitry Andric 
52059d1ed5bSDimitry Andric   if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
5213861d79fSDimitry Andric     // C++11 [dcl.ref]p5 (as amended by core issue 453):
5223861d79fSDimitry Andric     //   If a glvalue to which a reference is directly bound designates neither
5233861d79fSDimitry Andric     //   an existing object or function of an appropriate type nor a region of
5243861d79fSDimitry Andric     //   storage of suitable size and alignment to contain an object of the
5253861d79fSDimitry Andric     //   reference's type, the behavior is undefined.
5263861d79fSDimitry Andric     QualType Ty = E->getType();
5273861d79fSDimitry Andric     EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
5283861d79fSDimitry Andric   }
529ffd1746dSEd Schouten 
530ffd1746dSEd Schouten   return RValue::get(Value);
531f22ef01cSRoman Divacky }
532f22ef01cSRoman Divacky 
533f22ef01cSRoman Divacky 
534f22ef01cSRoman Divacky /// getAccessedFieldNo - Given an encoded value and a result number, return the
535f22ef01cSRoman Divacky /// input field number being accessed.
536f22ef01cSRoman Divacky unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
537f22ef01cSRoman Divacky                                              const llvm::Constant *Elts) {
538dff0c46cSDimitry Andric   return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
539dff0c46cSDimitry Andric       ->getZExtValue();
540f22ef01cSRoman Divacky }
541f22ef01cSRoman Divacky 
5423861d79fSDimitry Andric /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
5433861d79fSDimitry Andric static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
5443861d79fSDimitry Andric                                     llvm::Value *High) {
5453861d79fSDimitry Andric   llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
5463861d79fSDimitry Andric   llvm::Value *K47 = Builder.getInt64(47);
5473861d79fSDimitry Andric   llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
5483861d79fSDimitry Andric   llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
5493861d79fSDimitry Andric   llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
5503861d79fSDimitry Andric   llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
5513861d79fSDimitry Andric   return Builder.CreateMul(B1, KMul);
5523861d79fSDimitry Andric }
5533861d79fSDimitry Andric 
55459d1ed5bSDimitry Andric bool CodeGenFunction::sanitizePerformTypeCheck() const {
55539d628a0SDimitry Andric   return SanOpts.has(SanitizerKind::Null) |
55639d628a0SDimitry Andric          SanOpts.has(SanitizerKind::Alignment) |
55739d628a0SDimitry Andric          SanOpts.has(SanitizerKind::ObjectSize) |
55839d628a0SDimitry Andric          SanOpts.has(SanitizerKind::Vptr);
55959d1ed5bSDimitry Andric }
56059d1ed5bSDimitry Andric 
5613861d79fSDimitry Andric void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
5620623d748SDimitry Andric                                     llvm::Value *Ptr, QualType Ty,
56320e90f04SDimitry Andric                                     CharUnits Alignment,
56420e90f04SDimitry Andric                                     SanitizerSet SkippedChecks) {
56559d1ed5bSDimitry Andric   if (!sanitizePerformTypeCheck())
566f22ef01cSRoman Divacky     return;
567f22ef01cSRoman Divacky 
5683861d79fSDimitry Andric   // Don't check pointers outside the default address space. The null check
5693861d79fSDimitry Andric   // isn't correct, the object-size check isn't supported by LLVM, and we can't
5703861d79fSDimitry Andric   // communicate the addresses to the runtime handler for the vptr check.
5710623d748SDimitry Andric   if (Ptr->getType()->getPointerAddressSpace())
5723861d79fSDimitry Andric     return;
573f22ef01cSRoman Divacky 
57424d58133SDimitry Andric   // Don't check pointers to volatile data. The behavior here is implementation-
57524d58133SDimitry Andric   // defined.
57624d58133SDimitry Andric   if (Ty.isVolatileQualified())
57724d58133SDimitry Andric     return;
57824d58133SDimitry Andric 
57959d1ed5bSDimitry Andric   SanitizerScope SanScope(this);
5803861d79fSDimitry Andric 
58133956c43SDimitry Andric   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
58259d1ed5bSDimitry Andric   llvm::BasicBlock *Done = nullptr;
58359d1ed5bSDimitry Andric 
58451690af2SDimitry Andric   // Quickly determine whether we have a pointer to an alloca. It's possible
58551690af2SDimitry Andric   // to skip null checks, and some alignment checks, for these pointers. This
58651690af2SDimitry Andric   // can reduce compile-time significantly.
58751690af2SDimitry Andric   auto PtrToAlloca =
58851690af2SDimitry Andric       dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
58951690af2SDimitry Andric 
59039d628a0SDimitry Andric   bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
59139d628a0SDimitry Andric                            TCK == TCK_UpcastToVirtualBase;
59239d628a0SDimitry Andric   if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
59351690af2SDimitry Andric       !SkippedChecks.has(SanitizerKind::Null) && !PtrToAlloca) {
5943861d79fSDimitry Andric     // The glvalue must not be an empty glvalue.
5950623d748SDimitry Andric     llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
596139f7f9bSDimitry Andric 
5976bc11b14SDimitry Andric     // The IR builder can constant-fold the null check if the pointer points to
5986bc11b14SDimitry Andric     // a constant.
5996bc11b14SDimitry Andric     bool PtrIsNonNull =
6006bc11b14SDimitry Andric         IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
6016bc11b14SDimitry Andric 
6026bc11b14SDimitry Andric     // Skip the null check if the pointer is known to be non-null.
6036bc11b14SDimitry Andric     if (!PtrIsNonNull) {
60439d628a0SDimitry Andric       if (AllowNullPointers) {
60539d628a0SDimitry Andric         // When performing pointer casts, it's OK if the value is null.
606139f7f9bSDimitry Andric         // Skip the remaining checks in that case.
607139f7f9bSDimitry Andric         Done = createBasicBlock("null");
608139f7f9bSDimitry Andric         llvm::BasicBlock *Rest = createBasicBlock("not.null");
60939d628a0SDimitry Andric         Builder.CreateCondBr(IsNonNull, Rest, Done);
610139f7f9bSDimitry Andric         EmitBlock(Rest);
61139d628a0SDimitry Andric       } else {
61239d628a0SDimitry Andric         Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
613139f7f9bSDimitry Andric       }
6143861d79fSDimitry Andric     }
6156bc11b14SDimitry Andric   }
6163861d79fSDimitry Andric 
61720e90f04SDimitry Andric   if (SanOpts.has(SanitizerKind::ObjectSize) &&
61820e90f04SDimitry Andric       !SkippedChecks.has(SanitizerKind::ObjectSize) &&
61920e90f04SDimitry Andric       !Ty->isIncompleteType()) {
6203861d79fSDimitry Andric     uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
6213861d79fSDimitry Andric 
6223861d79fSDimitry Andric     // The glvalue must refer to a large enough storage region.
6233861d79fSDimitry Andric     // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
6243861d79fSDimitry Andric     //        to check this.
625f785676fSDimitry Andric     // FIXME: Get object address space
626f785676fSDimitry Andric     llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
627f785676fSDimitry Andric     llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
6287ae0e2c9SDimitry Andric     llvm::Value *Min = Builder.getFalse();
62920e90f04SDimitry Andric     llvm::Value *NullIsUnknown = Builder.getFalse();
6300623d748SDimitry Andric     llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
63120e90f04SDimitry Andric     llvm::Value *LargeEnough = Builder.CreateICmpUGE(
63220e90f04SDimitry Andric         Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
6333861d79fSDimitry Andric         llvm::ConstantInt::get(IntPtrTy, Size));
63439d628a0SDimitry Andric     Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
6353861d79fSDimitry Andric   }
6363861d79fSDimitry Andric 
6373861d79fSDimitry Andric   uint64_t AlignVal = 0;
6383861d79fSDimitry Andric 
63920e90f04SDimitry Andric   if (SanOpts.has(SanitizerKind::Alignment) &&
64020e90f04SDimitry Andric       !SkippedChecks.has(SanitizerKind::Alignment)) {
6413861d79fSDimitry Andric     AlignVal = Alignment.getQuantity();
6423861d79fSDimitry Andric     if (!Ty->isIncompleteType() && !AlignVal)
6433861d79fSDimitry Andric       AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
6443861d79fSDimitry Andric 
6453861d79fSDimitry Andric     // The glvalue must be suitably aligned.
64651690af2SDimitry Andric     if (AlignVal > 1 &&
64751690af2SDimitry Andric         (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
6483861d79fSDimitry Andric       llvm::Value *Align =
6490623d748SDimitry Andric           Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
6503861d79fSDimitry Andric                             llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
6513861d79fSDimitry Andric       llvm::Value *Aligned =
6523861d79fSDimitry Andric         Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
65339d628a0SDimitry Andric       Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
6543861d79fSDimitry Andric     }
6553861d79fSDimitry Andric   }
6563861d79fSDimitry Andric 
65739d628a0SDimitry Andric   if (Checks.size() > 0) {
65895ec533aSDimitry Andric     // Make sure we're not losing information. Alignment needs to be a power of
65995ec533aSDimitry Andric     // 2
66095ec533aSDimitry Andric     assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
6613861d79fSDimitry Andric     llvm::Constant *StaticData[] = {
66295ec533aSDimitry Andric         EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
66395ec533aSDimitry Andric         llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
66495ec533aSDimitry Andric         llvm::ConstantInt::get(Int8Ty, TCK)};
66544290647SDimitry Andric     EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
6663861d79fSDimitry Andric   }
6673861d79fSDimitry Andric 
6683861d79fSDimitry Andric   // If possible, check that the vptr indicates that there is a subobject of
6693861d79fSDimitry Andric   // type Ty at offset zero within this object.
670139f7f9bSDimitry Andric   //
671139f7f9bSDimitry Andric   // C++11 [basic.life]p5,6:
672139f7f9bSDimitry Andric   //   [For storage which does not refer to an object within its lifetime]
673139f7f9bSDimitry Andric   //   The program has undefined behavior if:
674139f7f9bSDimitry Andric   //    -- the [pointer or glvalue] is used to access a non-static data member
675139f7f9bSDimitry Andric   //       or call a non-static member function
6763861d79fSDimitry Andric   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
67739d628a0SDimitry Andric   if (SanOpts.has(SanitizerKind::Vptr) &&
67820e90f04SDimitry Andric       !SkippedChecks.has(SanitizerKind::Vptr) &&
679139f7f9bSDimitry Andric       (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
68039d628a0SDimitry Andric        TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
68139d628a0SDimitry Andric        TCK == TCK_UpcastToVirtualBase) &&
6823861d79fSDimitry Andric       RD && RD->hasDefinition() && RD->isDynamicClass()) {
6833861d79fSDimitry Andric     // Compute a hash of the mangled name of the type.
6843861d79fSDimitry Andric     //
6853861d79fSDimitry Andric     // FIXME: This is not guaranteed to be deterministic! Move to a
6863861d79fSDimitry Andric     //        fingerprinting mechanism once LLVM provides one. For the time
6873861d79fSDimitry Andric     //        being the implementation happens to be deterministic.
688139f7f9bSDimitry Andric     SmallString<64> MangledName;
6893861d79fSDimitry Andric     llvm::raw_svector_ostream Out(MangledName);
6903861d79fSDimitry Andric     CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
6913861d79fSDimitry Andric                                                      Out);
69259d1ed5bSDimitry Andric 
69359d1ed5bSDimitry Andric     // Blacklist based on the mangled type.
69439d628a0SDimitry Andric     if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
69539d628a0SDimitry Andric             Out.str())) {
6963861d79fSDimitry Andric       llvm::hash_code TypeHash = hash_value(Out.str());
6973861d79fSDimitry Andric 
6983861d79fSDimitry Andric       // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
6993861d79fSDimitry Andric       llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
7003861d79fSDimitry Andric       llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
7010623d748SDimitry Andric       Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
7023861d79fSDimitry Andric       llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
7033861d79fSDimitry Andric       llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
7043861d79fSDimitry Andric 
7053861d79fSDimitry Andric       llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
7063861d79fSDimitry Andric       Hash = Builder.CreateTrunc(Hash, IntPtrTy);
7073861d79fSDimitry Andric 
7083861d79fSDimitry Andric       // Look the hash up in our cache.
7093861d79fSDimitry Andric       const int CacheSize = 128;
7103861d79fSDimitry Andric       llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
7113861d79fSDimitry Andric       llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
7123861d79fSDimitry Andric                                                      "__ubsan_vptr_type_cache");
7133861d79fSDimitry Andric       llvm::Value *Slot = Builder.CreateAnd(Hash,
7143861d79fSDimitry Andric                                             llvm::ConstantInt::get(IntPtrTy,
7153861d79fSDimitry Andric                                                                    CacheSize-1));
7163861d79fSDimitry Andric       llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
7173861d79fSDimitry Andric       llvm::Value *CacheVal =
7180623d748SDimitry Andric         Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
7190623d748SDimitry Andric                                   getPointerAlign());
7203861d79fSDimitry Andric 
7213861d79fSDimitry Andric       // If the hash isn't in the cache, call a runtime handler to perform the
7223861d79fSDimitry Andric       // hard work of checking whether the vptr is for an object of the right
7233861d79fSDimitry Andric       // type. This will either fill in the cache and return, or produce a
7243861d79fSDimitry Andric       // diagnostic.
72539d628a0SDimitry Andric       llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
7263861d79fSDimitry Andric       llvm::Constant *StaticData[] = {
7273861d79fSDimitry Andric         EmitCheckSourceLocation(Loc),
7283861d79fSDimitry Andric         EmitCheckTypeDescriptor(Ty),
7293861d79fSDimitry Andric         CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
7303861d79fSDimitry Andric         llvm::ConstantInt::get(Int8Ty, TCK)
7313861d79fSDimitry Andric       };
7320623d748SDimitry Andric       llvm::Value *DynamicData[] = { Ptr, Hash };
73339d628a0SDimitry Andric       EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
73444290647SDimitry Andric                 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
73544290647SDimitry Andric                 DynamicData);
7363861d79fSDimitry Andric     }
73759d1ed5bSDimitry Andric   }
738139f7f9bSDimitry Andric 
739139f7f9bSDimitry Andric   if (Done) {
740139f7f9bSDimitry Andric     Builder.CreateBr(Done);
741139f7f9bSDimitry Andric     EmitBlock(Done);
742139f7f9bSDimitry Andric   }
743139f7f9bSDimitry Andric }
744139f7f9bSDimitry Andric 
745139f7f9bSDimitry Andric /// Determine whether this expression refers to a flexible array member in a
746139f7f9bSDimitry Andric /// struct. We disable array bounds checks for such members.
747139f7f9bSDimitry Andric static bool isFlexibleArrayMemberExpr(const Expr *E) {
748139f7f9bSDimitry Andric   // For compatibility with existing code, we treat arrays of length 0 or
749139f7f9bSDimitry Andric   // 1 as flexible array members.
750139f7f9bSDimitry Andric   const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
75159d1ed5bSDimitry Andric   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
752139f7f9bSDimitry Andric     if (CAT->getSize().ugt(1))
753139f7f9bSDimitry Andric       return false;
754139f7f9bSDimitry Andric   } else if (!isa<IncompleteArrayType>(AT))
755139f7f9bSDimitry Andric     return false;
756139f7f9bSDimitry Andric 
757139f7f9bSDimitry Andric   E = E->IgnoreParens();
758139f7f9bSDimitry Andric 
759139f7f9bSDimitry Andric   // A flexible array member must be the last member in the class.
76059d1ed5bSDimitry Andric   if (const auto *ME = dyn_cast<MemberExpr>(E)) {
761139f7f9bSDimitry Andric     // FIXME: If the base type of the member expr is not FD->getParent(),
762139f7f9bSDimitry Andric     // this should not be treated as a flexible array member access.
76359d1ed5bSDimitry Andric     if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
764139f7f9bSDimitry Andric       RecordDecl::field_iterator FI(
765139f7f9bSDimitry Andric           DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
766139f7f9bSDimitry Andric       return ++FI == FD->getParent()->field_end();
767139f7f9bSDimitry Andric     }
76844290647SDimitry Andric   } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
76944290647SDimitry Andric     return IRE->getDecl()->getNextIvar() == nullptr;
770139f7f9bSDimitry Andric   }
771139f7f9bSDimitry Andric 
772139f7f9bSDimitry Andric   return false;
773139f7f9bSDimitry Andric }
774139f7f9bSDimitry Andric 
775139f7f9bSDimitry Andric /// If Base is known to point to the start of an array, return the length of
776139f7f9bSDimitry Andric /// that array. Return 0 if the length cannot be determined.
777139f7f9bSDimitry Andric static llvm::Value *getArrayIndexingBound(
778139f7f9bSDimitry Andric     CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
779139f7f9bSDimitry Andric   // For the vector indexing extension, the bound is the number of elements.
780139f7f9bSDimitry Andric   if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
781139f7f9bSDimitry Andric     IndexedType = Base->getType();
782139f7f9bSDimitry Andric     return CGF.Builder.getInt32(VT->getNumElements());
783139f7f9bSDimitry Andric   }
784139f7f9bSDimitry Andric 
785139f7f9bSDimitry Andric   Base = Base->IgnoreParens();
786139f7f9bSDimitry Andric 
78759d1ed5bSDimitry Andric   if (const auto *CE = dyn_cast<CastExpr>(Base)) {
788139f7f9bSDimitry Andric     if (CE->getCastKind() == CK_ArrayToPointerDecay &&
789139f7f9bSDimitry Andric         !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
790139f7f9bSDimitry Andric       IndexedType = CE->getSubExpr()->getType();
791139f7f9bSDimitry Andric       const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
79259d1ed5bSDimitry Andric       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
793139f7f9bSDimitry Andric         return CGF.Builder.getInt(CAT->getSize());
79459d1ed5bSDimitry Andric       else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
795139f7f9bSDimitry Andric         return CGF.getVLASize(VAT).first;
796139f7f9bSDimitry Andric     }
797139f7f9bSDimitry Andric   }
798139f7f9bSDimitry Andric 
79959d1ed5bSDimitry Andric   return nullptr;
800139f7f9bSDimitry Andric }
801139f7f9bSDimitry Andric 
802139f7f9bSDimitry Andric void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
803139f7f9bSDimitry Andric                                       llvm::Value *Index, QualType IndexType,
804139f7f9bSDimitry Andric                                       bool Accessed) {
80539d628a0SDimitry Andric   assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
806f785676fSDimitry Andric          "should not be called unless adding bounds checks");
80759d1ed5bSDimitry Andric   SanitizerScope SanScope(this);
808139f7f9bSDimitry Andric 
809139f7f9bSDimitry Andric   QualType IndexedType;
810139f7f9bSDimitry Andric   llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
811139f7f9bSDimitry Andric   if (!Bound)
812139f7f9bSDimitry Andric     return;
813139f7f9bSDimitry Andric 
814139f7f9bSDimitry Andric   bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
815139f7f9bSDimitry Andric   llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
816139f7f9bSDimitry Andric   llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
817139f7f9bSDimitry Andric 
818139f7f9bSDimitry Andric   llvm::Constant *StaticData[] = {
819139f7f9bSDimitry Andric     EmitCheckSourceLocation(E->getExprLoc()),
820139f7f9bSDimitry Andric     EmitCheckTypeDescriptor(IndexedType),
821139f7f9bSDimitry Andric     EmitCheckTypeDescriptor(IndexType)
822139f7f9bSDimitry Andric   };
823139f7f9bSDimitry Andric   llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
824139f7f9bSDimitry Andric                                 : Builder.CreateICmpULE(IndexVal, BoundVal);
82544290647SDimitry Andric   EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
82644290647SDimitry Andric             SanitizerHandler::OutOfBounds, StaticData, Index);
827f22ef01cSRoman Divacky }
828f22ef01cSRoman Divacky 
829f22ef01cSRoman Divacky 
830f22ef01cSRoman Divacky CodeGenFunction::ComplexPairTy CodeGenFunction::
831f22ef01cSRoman Divacky EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
832f22ef01cSRoman Divacky                          bool isInc, bool isPre) {
833f785676fSDimitry Andric   ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
834f22ef01cSRoman Divacky 
835f22ef01cSRoman Divacky   llvm::Value *NextVal;
836f22ef01cSRoman Divacky   if (isa<llvm::IntegerType>(InVal.first->getType())) {
837f22ef01cSRoman Divacky     uint64_t AmountVal = isInc ? 1 : -1;
838f22ef01cSRoman Divacky     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
839f22ef01cSRoman Divacky 
840f22ef01cSRoman Divacky     // Add the inc/dec to the real part.
841f22ef01cSRoman Divacky     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
842f22ef01cSRoman Divacky   } else {
843f22ef01cSRoman Divacky     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
844f22ef01cSRoman Divacky     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
845f22ef01cSRoman Divacky     if (!isInc)
846f22ef01cSRoman Divacky       FVal.changeSign();
847f22ef01cSRoman Divacky     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
848f22ef01cSRoman Divacky 
849f22ef01cSRoman Divacky     // Add the inc/dec to the real part.
850f22ef01cSRoman Divacky     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
851f22ef01cSRoman Divacky   }
852f22ef01cSRoman Divacky 
853f22ef01cSRoman Divacky   ComplexPairTy IncVal(NextVal, InVal.second);
854f22ef01cSRoman Divacky 
855f22ef01cSRoman Divacky   // Store the updated result through the lvalue.
856139f7f9bSDimitry Andric   EmitStoreOfComplex(IncVal, LV, /*init*/ false);
857f22ef01cSRoman Divacky 
858f22ef01cSRoman Divacky   // If this is a postinc, return the value read from memory, otherwise use the
859f22ef01cSRoman Divacky   // updated value.
860f22ef01cSRoman Divacky   return isPre ? IncVal : InVal;
861f22ef01cSRoman Divacky }
862f22ef01cSRoman Divacky 
8630623d748SDimitry Andric void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
8640623d748SDimitry Andric                                              CodeGenFunction *CGF) {
8650623d748SDimitry Andric   // Bind VLAs in the cast type.
8660623d748SDimitry Andric   if (CGF && E->getType()->isVariablyModifiedType())
8670623d748SDimitry Andric     CGF->EmitVariablyModifiedType(E->getType());
8680623d748SDimitry Andric 
8690623d748SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
8700623d748SDimitry Andric     DI->EmitExplicitCastType(E->getType());
8710623d748SDimitry Andric }
8720623d748SDimitry Andric 
873f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
874f22ef01cSRoman Divacky //                         LValue Expression Emission
875f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
876f22ef01cSRoman Divacky 
8770623d748SDimitry Andric /// EmitPointerWithAlignment - Given an expression of pointer type, try to
8780623d748SDimitry Andric /// derive a more accurate bound on the alignment of the pointer.
8790623d748SDimitry Andric Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
880d8866befSDimitry Andric                                                   LValueBaseInfo *BaseInfo) {
8810623d748SDimitry Andric   // We allow this with ObjC object pointers because of fragile ABIs.
8820623d748SDimitry Andric   assert(E->getType()->isPointerType() ||
8830623d748SDimitry Andric          E->getType()->isObjCObjectPointerType());
8840623d748SDimitry Andric   E = E->IgnoreParens();
8850623d748SDimitry Andric 
8860623d748SDimitry Andric   // Casts:
8870623d748SDimitry Andric   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
8880623d748SDimitry Andric     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
8890623d748SDimitry Andric       CGM.EmitExplicitCastExprType(ECE, this);
8900623d748SDimitry Andric 
8910623d748SDimitry Andric     switch (CE->getCastKind()) {
8920623d748SDimitry Andric     // Non-converting casts (but not C's implicit conversion from void*).
8930623d748SDimitry Andric     case CK_BitCast:
8940623d748SDimitry Andric     case CK_NoOp:
8950623d748SDimitry Andric       if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
8960623d748SDimitry Andric         if (PtrTy->getPointeeType()->isVoidType())
8970623d748SDimitry Andric           break;
8980623d748SDimitry Andric 
899d8866befSDimitry Andric         LValueBaseInfo InnerInfo;
900d8866befSDimitry Andric         Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo);
901d8866befSDimitry Andric         if (BaseInfo) *BaseInfo = InnerInfo;
9020623d748SDimitry Andric 
9030623d748SDimitry Andric         // If this is an explicit bitcast, and the source l-value is
9040623d748SDimitry Andric         // opaque, honor the alignment of the casted-to type.
9050623d748SDimitry Andric         if (isa<ExplicitCastExpr>(CE) &&
906d8866befSDimitry Andric             InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
907d8866befSDimitry Andric           LValueBaseInfo ExpInfo;
908d8866befSDimitry Andric           CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
909d8866befSDimitry Andric                                                            &ExpInfo);
910d8866befSDimitry Andric           if (BaseInfo)
911d8866befSDimitry Andric             BaseInfo->mergeForCast(ExpInfo);
912d8866befSDimitry Andric           Addr = Address(Addr.getPointer(), Align);
9130623d748SDimitry Andric         }
9140623d748SDimitry Andric 
915e7145dcbSDimitry Andric         if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
916e7145dcbSDimitry Andric             CE->getCastKind() == CK_BitCast) {
9170623d748SDimitry Andric           if (auto PT = E->getType()->getAs<PointerType>())
9180623d748SDimitry Andric             EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
9190623d748SDimitry Andric                                       /*MayBeNull=*/true,
9200623d748SDimitry Andric                                       CodeGenFunction::CFITCK_UnrelatedCast,
9210623d748SDimitry Andric                                       CE->getLocStart());
9220623d748SDimitry Andric         }
9230623d748SDimitry Andric 
9240623d748SDimitry Andric         return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
9250623d748SDimitry Andric       }
9260623d748SDimitry Andric       break;
9270623d748SDimitry Andric 
9280623d748SDimitry Andric     // Array-to-pointer decay.
9290623d748SDimitry Andric     case CK_ArrayToPointerDecay:
930d8866befSDimitry Andric       return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
9310623d748SDimitry Andric 
9320623d748SDimitry Andric     // Derived-to-base conversions.
9330623d748SDimitry Andric     case CK_UncheckedDerivedToBase:
9340623d748SDimitry Andric     case CK_DerivedToBase: {
935d8866befSDimitry Andric       Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
9360623d748SDimitry Andric       auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
9370623d748SDimitry Andric       return GetAddressOfBaseClass(Addr, Derived,
9380623d748SDimitry Andric                                    CE->path_begin(), CE->path_end(),
9390623d748SDimitry Andric                                    ShouldNullCheckClassCastValue(CE),
9400623d748SDimitry Andric                                    CE->getExprLoc());
9410623d748SDimitry Andric     }
9420623d748SDimitry Andric 
9430623d748SDimitry Andric     // TODO: Is there any reason to treat base-to-derived conversions
9440623d748SDimitry Andric     // specially?
9450623d748SDimitry Andric     default:
9460623d748SDimitry Andric       break;
9470623d748SDimitry Andric     }
9480623d748SDimitry Andric   }
9490623d748SDimitry Andric 
9500623d748SDimitry Andric   // Unary &.
9510623d748SDimitry Andric   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9520623d748SDimitry Andric     if (UO->getOpcode() == UO_AddrOf) {
9530623d748SDimitry Andric       LValue LV = EmitLValue(UO->getSubExpr());
954d8866befSDimitry Andric       if (BaseInfo) *BaseInfo = LV.getBaseInfo();
9550623d748SDimitry Andric       return LV.getAddress();
9560623d748SDimitry Andric     }
9570623d748SDimitry Andric   }
9580623d748SDimitry Andric 
9590623d748SDimitry Andric   // TODO: conditional operators, comma.
9600623d748SDimitry Andric 
9610623d748SDimitry Andric   // Otherwise, use the alignment of the type.
962d8866befSDimitry Andric   CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
9630623d748SDimitry Andric   return Address(EmitScalarExpr(E), Align);
9640623d748SDimitry Andric }
9650623d748SDimitry Andric 
966f22ef01cSRoman Divacky RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
967f22ef01cSRoman Divacky   if (Ty->isVoidType())
96859d1ed5bSDimitry Andric     return RValue::get(nullptr);
969f22ef01cSRoman Divacky 
970139f7f9bSDimitry Andric   switch (getEvaluationKind(Ty)) {
971139f7f9bSDimitry Andric   case TEK_Complex: {
972139f7f9bSDimitry Andric     llvm::Type *EltTy =
973139f7f9bSDimitry Andric       ConvertType(Ty->castAs<ComplexType>()->getElementType());
974f22ef01cSRoman Divacky     llvm::Value *U = llvm::UndefValue::get(EltTy);
975f22ef01cSRoman Divacky     return RValue::getComplex(std::make_pair(U, U));
976f22ef01cSRoman Divacky   }
977f22ef01cSRoman Divacky 
978e580952dSDimitry Andric   // If this is a use of an undefined aggregate type, the aggregate must have an
979e580952dSDimitry Andric   // identifiable address.  Just because the contents of the value are undefined
980e580952dSDimitry Andric   // doesn't mean that the address can't be taken and compared.
981139f7f9bSDimitry Andric   case TEK_Aggregate: {
9820623d748SDimitry Andric     Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
983e580952dSDimitry Andric     return RValue::getAggregate(DestPtr);
984f22ef01cSRoman Divacky   }
985f22ef01cSRoman Divacky 
986139f7f9bSDimitry Andric   case TEK_Scalar:
987f22ef01cSRoman Divacky     return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
988f22ef01cSRoman Divacky   }
989139f7f9bSDimitry Andric   llvm_unreachable("bad evaluation kind");
990139f7f9bSDimitry Andric }
991f22ef01cSRoman Divacky 
992f22ef01cSRoman Divacky RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
993f22ef01cSRoman Divacky                                               const char *Name) {
994f22ef01cSRoman Divacky   ErrorUnsupported(E, Name);
995f22ef01cSRoman Divacky   return GetUndefRValue(E->getType());
996f22ef01cSRoman Divacky }
997f22ef01cSRoman Divacky 
998f22ef01cSRoman Divacky LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
999f22ef01cSRoman Divacky                                               const char *Name) {
1000f22ef01cSRoman Divacky   ErrorUnsupported(E, Name);
1001f22ef01cSRoman Divacky   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
10020623d748SDimitry Andric   return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
10030623d748SDimitry Andric                         E->getType());
1004f22ef01cSRoman Divacky }
1005f22ef01cSRoman Divacky 
100620e90f04SDimitry Andric bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
100720e90f04SDimitry Andric   const Expr *Base = Obj;
100820e90f04SDimitry Andric   while (!isa<CXXThisExpr>(Base)) {
100920e90f04SDimitry Andric     // The result of a dynamic_cast can be null.
101020e90f04SDimitry Andric     if (isa<CXXDynamicCastExpr>(Base))
101120e90f04SDimitry Andric       return false;
101220e90f04SDimitry Andric 
101320e90f04SDimitry Andric     if (const auto *CE = dyn_cast<CastExpr>(Base)) {
101420e90f04SDimitry Andric       Base = CE->getSubExpr();
101520e90f04SDimitry Andric     } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
101620e90f04SDimitry Andric       Base = PE->getSubExpr();
101720e90f04SDimitry Andric     } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
101820e90f04SDimitry Andric       if (UO->getOpcode() == UO_Extension)
101920e90f04SDimitry Andric         Base = UO->getSubExpr();
102020e90f04SDimitry Andric       else
102120e90f04SDimitry Andric         return false;
102220e90f04SDimitry Andric     } else {
102320e90f04SDimitry Andric       return false;
102420e90f04SDimitry Andric     }
102520e90f04SDimitry Andric   }
102620e90f04SDimitry Andric   return true;
102720e90f04SDimitry Andric }
102820e90f04SDimitry Andric 
10293861d79fSDimitry Andric LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1030139f7f9bSDimitry Andric   LValue LV;
103139d628a0SDimitry Andric   if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1032139f7f9bSDimitry Andric     LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1033139f7f9bSDimitry Andric   else
1034139f7f9bSDimitry Andric     LV = EmitLValue(E);
103520e90f04SDimitry Andric   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
103620e90f04SDimitry Andric     SanitizerSet SkippedChecks;
103720e90f04SDimitry Andric     if (const auto *ME = dyn_cast<MemberExpr>(E)) {
103820e90f04SDimitry Andric       bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
103920e90f04SDimitry Andric       if (IsBaseCXXThis)
104020e90f04SDimitry Andric         SkippedChecks.set(SanitizerKind::Alignment, true);
104120e90f04SDimitry Andric       if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
104220e90f04SDimitry Andric         SkippedChecks.set(SanitizerKind::Null, true);
104320e90f04SDimitry Andric     }
10440623d748SDimitry Andric     EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
104520e90f04SDimitry Andric                   E->getType(), LV.getAlignment(), SkippedChecks);
104620e90f04SDimitry Andric   }
1047f22ef01cSRoman Divacky   return LV;
1048f22ef01cSRoman Divacky }
1049f22ef01cSRoman Divacky 
1050f22ef01cSRoman Divacky /// EmitLValue - Emit code to compute a designator that specifies the location
1051f22ef01cSRoman Divacky /// of the expression.
1052f22ef01cSRoman Divacky ///
1053f22ef01cSRoman Divacky /// This can return one of two things: a simple address or a bitfield reference.
1054f22ef01cSRoman Divacky /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1055f22ef01cSRoman Divacky /// an LLVM pointer type.
1056f22ef01cSRoman Divacky ///
1057f22ef01cSRoman Divacky /// If this returns a bitfield reference, nothing about the pointee type of the
1058f22ef01cSRoman Divacky /// LLVM value is known: For example, it may not be a pointer to an integer.
1059f22ef01cSRoman Divacky ///
1060f22ef01cSRoman Divacky /// If this returns a normal address, and if the lvalue's C type is fixed size,
1061f22ef01cSRoman Divacky /// this method guarantees that the returned pointer type will point to an LLVM
1062f22ef01cSRoman Divacky /// type of the same size of the lvalue's type.  If the lvalue has a variable
1063f22ef01cSRoman Divacky /// length type, this is not possible.
1064f22ef01cSRoman Divacky ///
1065f22ef01cSRoman Divacky LValue CodeGenFunction::EmitLValue(const Expr *E) {
106633956c43SDimitry Andric   ApplyDebugLocation DL(*this, E);
1067f22ef01cSRoman Divacky   switch (E->getStmtClass()) {
1068f22ef01cSRoman Divacky   default: return EmitUnsupportedLValue(E, "l-value expression");
1069f22ef01cSRoman Divacky 
1070dff0c46cSDimitry Andric   case Expr::ObjCPropertyRefExprClass:
1071dff0c46cSDimitry Andric     llvm_unreachable("cannot emit a property reference directly");
1072dff0c46cSDimitry Andric 
1073ffd1746dSEd Schouten   case Expr::ObjCSelectorExprClass:
1074ffd1746dSEd Schouten     return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1075f22ef01cSRoman Divacky   case Expr::ObjCIsaExprClass:
1076f22ef01cSRoman Divacky     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1077f22ef01cSRoman Divacky   case Expr::BinaryOperatorClass:
1078f22ef01cSRoman Divacky     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
107933956c43SDimitry Andric   case Expr::CompoundAssignOperatorClass: {
108033956c43SDimitry Andric     QualType Ty = E->getType();
108133956c43SDimitry Andric     if (const AtomicType *AT = Ty->getAs<AtomicType>())
108233956c43SDimitry Andric       Ty = AT->getValueType();
108333956c43SDimitry Andric     if (!Ty->isAnyComplexType())
10842754fe60SDimitry Andric       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
10852754fe60SDimitry Andric     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
108633956c43SDimitry Andric   }
1087f22ef01cSRoman Divacky   case Expr::CallExprClass:
1088f22ef01cSRoman Divacky   case Expr::CXXMemberCallExprClass:
1089f22ef01cSRoman Divacky   case Expr::CXXOperatorCallExprClass:
1090dff0c46cSDimitry Andric   case Expr::UserDefinedLiteralClass:
1091f22ef01cSRoman Divacky     return EmitCallExprLValue(cast<CallExpr>(E));
1092f22ef01cSRoman Divacky   case Expr::VAArgExprClass:
1093f22ef01cSRoman Divacky     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1094f22ef01cSRoman Divacky   case Expr::DeclRefExprClass:
1095f22ef01cSRoman Divacky     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
10966122f3e6SDimitry Andric   case Expr::ParenExprClass:
10976122f3e6SDimitry Andric     return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
10983b0f4066SDimitry Andric   case Expr::GenericSelectionExprClass:
10993b0f4066SDimitry Andric     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1100f22ef01cSRoman Divacky   case Expr::PredefinedExprClass:
1101f22ef01cSRoman Divacky     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1102f22ef01cSRoman Divacky   case Expr::StringLiteralClass:
1103f22ef01cSRoman Divacky     return EmitStringLiteralLValue(cast<StringLiteral>(E));
1104f22ef01cSRoman Divacky   case Expr::ObjCEncodeExprClass:
1105f22ef01cSRoman Divacky     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1106dff0c46cSDimitry Andric   case Expr::PseudoObjectExprClass:
1107dff0c46cSDimitry Andric     return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1108dff0c46cSDimitry Andric   case Expr::InitListExprClass:
11097ae0e2c9SDimitry Andric     return EmitInitListLValue(cast<InitListExpr>(E));
1110f22ef01cSRoman Divacky   case Expr::CXXTemporaryObjectExprClass:
1111f22ef01cSRoman Divacky   case Expr::CXXConstructExprClass:
1112f22ef01cSRoman Divacky     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1113f22ef01cSRoman Divacky   case Expr::CXXBindTemporaryExprClass:
1114f22ef01cSRoman Divacky     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
11153861d79fSDimitry Andric   case Expr::CXXUuidofExprClass:
11163861d79fSDimitry Andric     return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1117dff0c46cSDimitry Andric   case Expr::LambdaExprClass:
1118dff0c46cSDimitry Andric     return EmitLambdaLValue(cast<LambdaExpr>(E));
1119dff0c46cSDimitry Andric 
1120dff0c46cSDimitry Andric   case Expr::ExprWithCleanupsClass: {
112159d1ed5bSDimitry Andric     const auto *cleanups = cast<ExprWithCleanups>(E);
1122dff0c46cSDimitry Andric     enterFullExpression(cleanups);
1123dff0c46cSDimitry Andric     RunCleanupsScope Scope(*this);
112420e90f04SDimitry Andric     LValue LV = EmitLValue(cleanups->getSubExpr());
112520e90f04SDimitry Andric     if (LV.isSimple()) {
112620e90f04SDimitry Andric       // Defend against branches out of gnu statement expressions surrounded by
112720e90f04SDimitry Andric       // cleanups.
112820e90f04SDimitry Andric       llvm::Value *V = LV.getPointer();
112920e90f04SDimitry Andric       Scope.ForceCleanup({&V});
113020e90f04SDimitry Andric       return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1131d8866befSDimitry Andric                               getContext(), LV.getBaseInfo(),
113220e90f04SDimitry Andric                               LV.getTBAAInfo());
113320e90f04SDimitry Andric     }
113420e90f04SDimitry Andric     // FIXME: Is it possible to create an ExprWithCleanups that produces a
113520e90f04SDimitry Andric     // bitfield lvalue or some other non-simple lvalue?
113620e90f04SDimitry Andric     return LV;
1137dff0c46cSDimitry Andric   }
1138dff0c46cSDimitry Andric 
1139f22ef01cSRoman Divacky   case Expr::CXXDefaultArgExprClass:
1140f22ef01cSRoman Divacky     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1141284c1978SDimitry Andric   case Expr::CXXDefaultInitExprClass: {
1142284c1978SDimitry Andric     CXXDefaultInitExprScope Scope(*this);
1143284c1978SDimitry Andric     return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1144284c1978SDimitry Andric   }
1145f22ef01cSRoman Divacky   case Expr::CXXTypeidExprClass:
1146f22ef01cSRoman Divacky     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1147f22ef01cSRoman Divacky 
1148f22ef01cSRoman Divacky   case Expr::ObjCMessageExprClass:
1149f22ef01cSRoman Divacky     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1150f22ef01cSRoman Divacky   case Expr::ObjCIvarRefExprClass:
1151f22ef01cSRoman Divacky     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1152f22ef01cSRoman Divacky   case Expr::StmtExprClass:
1153f22ef01cSRoman Divacky     return EmitStmtExprLValue(cast<StmtExpr>(E));
1154f22ef01cSRoman Divacky   case Expr::UnaryOperatorClass:
1155f22ef01cSRoman Divacky     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1156f22ef01cSRoman Divacky   case Expr::ArraySubscriptExprClass:
1157f22ef01cSRoman Divacky     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
11580623d748SDimitry Andric   case Expr::OMPArraySectionExprClass:
11590623d748SDimitry Andric     return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1160f22ef01cSRoman Divacky   case Expr::ExtVectorElementExprClass:
1161f22ef01cSRoman Divacky     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1162f22ef01cSRoman Divacky   case Expr::MemberExprClass:
1163f22ef01cSRoman Divacky     return EmitMemberExpr(cast<MemberExpr>(E));
1164f22ef01cSRoman Divacky   case Expr::CompoundLiteralExprClass:
1165f22ef01cSRoman Divacky     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1166f22ef01cSRoman Divacky   case Expr::ConditionalOperatorClass:
1167f22ef01cSRoman Divacky     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
11682754fe60SDimitry Andric   case Expr::BinaryConditionalOperatorClass:
11692754fe60SDimitry Andric     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1170f22ef01cSRoman Divacky   case Expr::ChooseExprClass:
1171f785676fSDimitry Andric     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
11722754fe60SDimitry Andric   case Expr::OpaqueValueExprClass:
11732754fe60SDimitry Andric     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
117417a519f9SDimitry Andric   case Expr::SubstNonTypeTemplateParmExprClass:
117517a519f9SDimitry Andric     return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1176f22ef01cSRoman Divacky   case Expr::ImplicitCastExprClass:
1177f22ef01cSRoman Divacky   case Expr::CStyleCastExprClass:
1178f22ef01cSRoman Divacky   case Expr::CXXFunctionalCastExprClass:
1179f22ef01cSRoman Divacky   case Expr::CXXStaticCastExprClass:
1180f22ef01cSRoman Divacky   case Expr::CXXDynamicCastExprClass:
1181f22ef01cSRoman Divacky   case Expr::CXXReinterpretCastExprClass:
1182f22ef01cSRoman Divacky   case Expr::CXXConstCastExprClass:
118317a519f9SDimitry Andric   case Expr::ObjCBridgedCastExprClass:
1184f22ef01cSRoman Divacky     return EmitCastLValue(cast<CastExpr>(E));
118517a519f9SDimitry Andric 
118617a519f9SDimitry Andric   case Expr::MaterializeTemporaryExprClass:
118717a519f9SDimitry Andric     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
118824d58133SDimitry Andric 
118924d58133SDimitry Andric   case Expr::CoawaitExprClass:
119024d58133SDimitry Andric     return EmitCoawaitLValue(cast<CoawaitExpr>(E));
119124d58133SDimitry Andric   case Expr::CoyieldExprClass:
119224d58133SDimitry Andric     return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1193f22ef01cSRoman Divacky   }
1194f22ef01cSRoman Divacky }
1195f22ef01cSRoman Divacky 
1196dff0c46cSDimitry Andric /// Given an object of the given canonical type, can we safely copy a
1197dff0c46cSDimitry Andric /// value out of it based on its initializer?
1198dff0c46cSDimitry Andric static bool isConstantEmittableObjectType(QualType type) {
1199dff0c46cSDimitry Andric   assert(type.isCanonical());
1200dff0c46cSDimitry Andric   assert(!type->isReferenceType());
1201dff0c46cSDimitry Andric 
1202dff0c46cSDimitry Andric   // Must be const-qualified but non-volatile.
1203dff0c46cSDimitry Andric   Qualifiers qs = type.getLocalQualifiers();
1204dff0c46cSDimitry Andric   if (!qs.hasConst() || qs.hasVolatile()) return false;
1205dff0c46cSDimitry Andric 
1206dff0c46cSDimitry Andric   // Otherwise, all object types satisfy this except C++ classes with
1207dff0c46cSDimitry Andric   // mutable subobjects or non-trivial copy/destroy behavior.
120859d1ed5bSDimitry Andric   if (const auto *RT = dyn_cast<RecordType>(type))
120959d1ed5bSDimitry Andric     if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1210dff0c46cSDimitry Andric       if (RD->hasMutableFields() || !RD->isTrivial())
1211dff0c46cSDimitry Andric         return false;
1212dff0c46cSDimitry Andric 
1213dff0c46cSDimitry Andric   return true;
1214dff0c46cSDimitry Andric }
1215dff0c46cSDimitry Andric 
1216dff0c46cSDimitry Andric /// Can we constant-emit a load of a reference to a variable of the
1217dff0c46cSDimitry Andric /// given type?  This is different from predicates like
1218dff0c46cSDimitry Andric /// Decl::isUsableInConstantExpressions because we do want it to apply
1219dff0c46cSDimitry Andric /// in situations that don't necessarily satisfy the language's rules
1220dff0c46cSDimitry Andric /// for this (e.g. C++'s ODR-use rules).  For example, we want to able
1221dff0c46cSDimitry Andric /// to do this with const float variables even if those variables
1222dff0c46cSDimitry Andric /// aren't marked 'constexpr'.
1223dff0c46cSDimitry Andric enum ConstantEmissionKind {
1224dff0c46cSDimitry Andric   CEK_None,
1225dff0c46cSDimitry Andric   CEK_AsReferenceOnly,
1226dff0c46cSDimitry Andric   CEK_AsValueOrReference,
1227dff0c46cSDimitry Andric   CEK_AsValueOnly
1228dff0c46cSDimitry Andric };
1229dff0c46cSDimitry Andric static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1230dff0c46cSDimitry Andric   type = type.getCanonicalType();
123159d1ed5bSDimitry Andric   if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1232dff0c46cSDimitry Andric     if (isConstantEmittableObjectType(ref->getPointeeType()))
1233dff0c46cSDimitry Andric       return CEK_AsValueOrReference;
1234dff0c46cSDimitry Andric     return CEK_AsReferenceOnly;
1235dff0c46cSDimitry Andric   }
1236dff0c46cSDimitry Andric   if (isConstantEmittableObjectType(type))
1237dff0c46cSDimitry Andric     return CEK_AsValueOnly;
1238dff0c46cSDimitry Andric   return CEK_None;
1239dff0c46cSDimitry Andric }
1240dff0c46cSDimitry Andric 
1241dff0c46cSDimitry Andric /// Try to emit a reference to the given value without producing it as
1242dff0c46cSDimitry Andric /// an l-value.  This is actually more than an optimization: we can't
1243dff0c46cSDimitry Andric /// produce an l-value for variables that we never actually captured
1244dff0c46cSDimitry Andric /// in a block or lambda, which means const int variables or constexpr
1245dff0c46cSDimitry Andric /// literals or similar.
1246dff0c46cSDimitry Andric CodeGenFunction::ConstantEmission
1247dff0c46cSDimitry Andric CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1248dff0c46cSDimitry Andric   ValueDecl *value = refExpr->getDecl();
1249dff0c46cSDimitry Andric 
1250dff0c46cSDimitry Andric   // The value needs to be an enum constant or a constant variable.
1251dff0c46cSDimitry Andric   ConstantEmissionKind CEK;
1252dff0c46cSDimitry Andric   if (isa<ParmVarDecl>(value)) {
1253dff0c46cSDimitry Andric     CEK = CEK_None;
125459d1ed5bSDimitry Andric   } else if (auto *var = dyn_cast<VarDecl>(value)) {
1255dff0c46cSDimitry Andric     CEK = checkVarTypeForConstantEmission(var->getType());
1256dff0c46cSDimitry Andric   } else if (isa<EnumConstantDecl>(value)) {
1257dff0c46cSDimitry Andric     CEK = CEK_AsValueOnly;
1258dff0c46cSDimitry Andric   } else {
1259dff0c46cSDimitry Andric     CEK = CEK_None;
1260dff0c46cSDimitry Andric   }
1261dff0c46cSDimitry Andric   if (CEK == CEK_None) return ConstantEmission();
1262dff0c46cSDimitry Andric 
1263dff0c46cSDimitry Andric   Expr::EvalResult result;
1264dff0c46cSDimitry Andric   bool resultIsReference;
1265dff0c46cSDimitry Andric   QualType resultType;
1266dff0c46cSDimitry Andric 
1267dff0c46cSDimitry Andric   // It's best to evaluate all the way as an r-value if that's permitted.
1268dff0c46cSDimitry Andric   if (CEK != CEK_AsReferenceOnly &&
1269dff0c46cSDimitry Andric       refExpr->EvaluateAsRValue(result, getContext())) {
1270dff0c46cSDimitry Andric     resultIsReference = false;
1271dff0c46cSDimitry Andric     resultType = refExpr->getType();
1272dff0c46cSDimitry Andric 
1273dff0c46cSDimitry Andric   // Otherwise, try to evaluate as an l-value.
1274dff0c46cSDimitry Andric   } else if (CEK != CEK_AsValueOnly &&
1275dff0c46cSDimitry Andric              refExpr->EvaluateAsLValue(result, getContext())) {
1276dff0c46cSDimitry Andric     resultIsReference = true;
1277dff0c46cSDimitry Andric     resultType = value->getType();
1278dff0c46cSDimitry Andric 
1279dff0c46cSDimitry Andric   // Failure.
1280dff0c46cSDimitry Andric   } else {
1281dff0c46cSDimitry Andric     return ConstantEmission();
1282dff0c46cSDimitry Andric   }
1283dff0c46cSDimitry Andric 
1284dff0c46cSDimitry Andric   // In any case, if the initializer has side-effects, abandon ship.
1285dff0c46cSDimitry Andric   if (result.HasSideEffects)
1286dff0c46cSDimitry Andric     return ConstantEmission();
1287dff0c46cSDimitry Andric 
1288dff0c46cSDimitry Andric   // Emit as a constant.
1289dff0c46cSDimitry Andric   llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1290dff0c46cSDimitry Andric 
1291dff0c46cSDimitry Andric   // Make sure we emit a debug reference to the global variable.
1292dff0c46cSDimitry Andric   // This should probably fire even for
1293dff0c46cSDimitry Andric   if (isa<VarDecl>(value)) {
1294dff0c46cSDimitry Andric     if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
129544290647SDimitry Andric       EmitDeclRefExprDbgValue(refExpr, result.Val);
1296dff0c46cSDimitry Andric   } else {
1297dff0c46cSDimitry Andric     assert(isa<EnumConstantDecl>(value));
129844290647SDimitry Andric     EmitDeclRefExprDbgValue(refExpr, result.Val);
1299dff0c46cSDimitry Andric   }
1300dff0c46cSDimitry Andric 
1301dff0c46cSDimitry Andric   // If we emitted a reference constant, we need to dereference that.
1302dff0c46cSDimitry Andric   if (resultIsReference)
1303dff0c46cSDimitry Andric     return ConstantEmission::forReference(C);
1304dff0c46cSDimitry Andric 
1305dff0c46cSDimitry Andric   return ConstantEmission::forValue(C);
1306dff0c46cSDimitry Andric }
1307dff0c46cSDimitry Andric 
1308f785676fSDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1309f785676fSDimitry Andric                                                SourceLocation Loc) {
131017a519f9SDimitry Andric   return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1311d8866befSDimitry Andric                           lvalue.getType(), Loc, lvalue.getBaseInfo(),
13120623d748SDimitry Andric                           lvalue.getTBAAInfo(),
13130623d748SDimitry Andric                           lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
13140623d748SDimitry Andric                           lvalue.isNontemporal());
1315dff0c46cSDimitry Andric }
1316dff0c46cSDimitry Andric 
1317dff0c46cSDimitry Andric static bool hasBooleanRepresentation(QualType Ty) {
1318dff0c46cSDimitry Andric   if (Ty->isBooleanType())
1319dff0c46cSDimitry Andric     return true;
1320dff0c46cSDimitry Andric 
1321dff0c46cSDimitry Andric   if (const EnumType *ET = Ty->getAs<EnumType>())
1322dff0c46cSDimitry Andric     return ET->getDecl()->getIntegerType()->isBooleanType();
1323dff0c46cSDimitry Andric 
1324dff0c46cSDimitry Andric   if (const AtomicType *AT = Ty->getAs<AtomicType>())
1325dff0c46cSDimitry Andric     return hasBooleanRepresentation(AT->getValueType());
1326dff0c46cSDimitry Andric 
1327dff0c46cSDimitry Andric   return false;
1328dff0c46cSDimitry Andric }
1329dff0c46cSDimitry Andric 
1330139f7f9bSDimitry Andric static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1331139f7f9bSDimitry Andric                             llvm::APInt &Min, llvm::APInt &End,
133244290647SDimitry Andric                             bool StrictEnums, bool IsBool) {
1333dff0c46cSDimitry Andric   const EnumType *ET = Ty->getAs<EnumType>();
1334139f7f9bSDimitry Andric   bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1335139f7f9bSDimitry Andric                                 ET && !ET->getDecl()->isFixed();
1336dff0c46cSDimitry Andric   if (!IsBool && !IsRegularCPlusPlusEnum)
1337139f7f9bSDimitry Andric     return false;
1338dff0c46cSDimitry Andric 
1339dff0c46cSDimitry Andric   if (IsBool) {
1340139f7f9bSDimitry Andric     Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1341139f7f9bSDimitry Andric     End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1342dff0c46cSDimitry Andric   } else {
1343dff0c46cSDimitry Andric     const EnumDecl *ED = ET->getDecl();
1344139f7f9bSDimitry Andric     llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1345dff0c46cSDimitry Andric     unsigned Bitwidth = LTy->getScalarSizeInBits();
1346dff0c46cSDimitry Andric     unsigned NumNegativeBits = ED->getNumNegativeBits();
1347dff0c46cSDimitry Andric     unsigned NumPositiveBits = ED->getNumPositiveBits();
1348dff0c46cSDimitry Andric 
1349dff0c46cSDimitry Andric     if (NumNegativeBits) {
1350dff0c46cSDimitry Andric       unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1351dff0c46cSDimitry Andric       assert(NumBits <= Bitwidth);
1352dff0c46cSDimitry Andric       End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1353dff0c46cSDimitry Andric       Min = -End;
1354dff0c46cSDimitry Andric     } else {
1355dff0c46cSDimitry Andric       assert(NumPositiveBits <= Bitwidth);
1356dff0c46cSDimitry Andric       End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1357dff0c46cSDimitry Andric       Min = llvm::APInt(Bitwidth, 0);
1358dff0c46cSDimitry Andric     }
1359dff0c46cSDimitry Andric   }
1360139f7f9bSDimitry Andric   return true;
1361139f7f9bSDimitry Andric }
1362139f7f9bSDimitry Andric 
1363139f7f9bSDimitry Andric llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1364139f7f9bSDimitry Andric   llvm::APInt Min, End;
136544290647SDimitry Andric   if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
136644290647SDimitry Andric                        hasBooleanRepresentation(Ty)))
136759d1ed5bSDimitry Andric     return nullptr;
1368dff0c46cSDimitry Andric 
1369cb4dff85SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
1370cb4dff85SDimitry Andric   return MDHelper.createRange(Min, End);
137117a519f9SDimitry Andric }
137217a519f9SDimitry Andric 
137320e90f04SDimitry Andric bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
137420e90f04SDimitry Andric                                            SourceLocation Loc) {
137520e90f04SDimitry Andric   bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
137620e90f04SDimitry Andric   bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
137720e90f04SDimitry Andric   if (!HasBoolCheck && !HasEnumCheck)
137820e90f04SDimitry Andric     return false;
137920e90f04SDimitry Andric 
138020e90f04SDimitry Andric   bool IsBool = hasBooleanRepresentation(Ty) ||
138120e90f04SDimitry Andric                 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
138220e90f04SDimitry Andric   bool NeedsBoolCheck = HasBoolCheck && IsBool;
138320e90f04SDimitry Andric   bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
138420e90f04SDimitry Andric   if (!NeedsBoolCheck && !NeedsEnumCheck)
138520e90f04SDimitry Andric     return false;
138620e90f04SDimitry Andric 
138720e90f04SDimitry Andric   // Single-bit booleans don't need to be checked. Special-case this to avoid
138820e90f04SDimitry Andric   // a bit width mismatch when handling bitfield values. This is handled by
138920e90f04SDimitry Andric   // EmitFromMemory for the non-bitfield case.
139020e90f04SDimitry Andric   if (IsBool &&
139120e90f04SDimitry Andric       cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
139220e90f04SDimitry Andric     return false;
139320e90f04SDimitry Andric 
139420e90f04SDimitry Andric   llvm::APInt Min, End;
139520e90f04SDimitry Andric   if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
139620e90f04SDimitry Andric     return true;
139720e90f04SDimitry Andric 
139820e90f04SDimitry Andric   SanitizerScope SanScope(this);
139920e90f04SDimitry Andric   llvm::Value *Check;
140020e90f04SDimitry Andric   --End;
140120e90f04SDimitry Andric   if (!Min) {
140220e90f04SDimitry Andric     Check = Builder.CreateICmpULE(
140320e90f04SDimitry Andric         Value, llvm::ConstantInt::get(getLLVMContext(), End));
140420e90f04SDimitry Andric   } else {
140520e90f04SDimitry Andric     llvm::Value *Upper = Builder.CreateICmpSLE(
140620e90f04SDimitry Andric         Value, llvm::ConstantInt::get(getLLVMContext(), End));
140720e90f04SDimitry Andric     llvm::Value *Lower = Builder.CreateICmpSGE(
140820e90f04SDimitry Andric         Value, llvm::ConstantInt::get(getLLVMContext(), Min));
140920e90f04SDimitry Andric     Check = Builder.CreateAnd(Upper, Lower);
141020e90f04SDimitry Andric   }
141120e90f04SDimitry Andric   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
141220e90f04SDimitry Andric                                   EmitCheckTypeDescriptor(Ty)};
141320e90f04SDimitry Andric   SanitizerMask Kind =
141420e90f04SDimitry Andric       NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
141520e90f04SDimitry Andric   EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
141620e90f04SDimitry Andric             StaticArgs, EmitCheckValue(Value));
141720e90f04SDimitry Andric   return true;
141820e90f04SDimitry Andric }
141920e90f04SDimitry Andric 
14200623d748SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
14210623d748SDimitry Andric                                                QualType Ty,
1422f785676fSDimitry Andric                                                SourceLocation Loc,
1423d8866befSDimitry Andric                                                LValueBaseInfo BaseInfo,
1424139f7f9bSDimitry Andric                                                llvm::MDNode *TBAAInfo,
1425139f7f9bSDimitry Andric                                                QualType TBAABaseType,
14260623d748SDimitry Andric                                                uint64_t TBAAOffset,
14270623d748SDimitry Andric                                                bool isNontemporal) {
142820e90f04SDimitry Andric   if (!CGM.getCodeGenOpts().PreserveVec3Type) {
14297ae0e2c9SDimitry Andric     // For better performance, handle vector loads differently.
14307ae0e2c9SDimitry Andric     if (Ty->isVectorType()) {
14310623d748SDimitry Andric       const llvm::Type *EltTy = Addr.getElementType();
14327ae0e2c9SDimitry Andric 
143359d1ed5bSDimitry Andric       const auto *VTy = cast<llvm::VectorType>(EltTy);
14347ae0e2c9SDimitry Andric 
14350623d748SDimitry Andric       // Handle vectors of size 3 like size 4 for better performance.
14367ae0e2c9SDimitry Andric       if (VTy->getNumElements() == 3) {
14377ae0e2c9SDimitry Andric 
14387ae0e2c9SDimitry Andric         // Bitcast to vec4 type.
143920e90f04SDimitry Andric         llvm::VectorType *vec4Ty =
144020e90f04SDimitry Andric             llvm::VectorType::get(VTy->getElementType(), 4);
14410623d748SDimitry Andric         Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
14427ae0e2c9SDimitry Andric         // Now load value.
14430623d748SDimitry Andric         llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
14447ae0e2c9SDimitry Andric 
14457ae0e2c9SDimitry Andric         // Shuffle vector to get vec3.
14460623d748SDimitry Andric         V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
14470623d748SDimitry Andric                                         {0, 1, 2}, "extractVec");
14487ae0e2c9SDimitry Andric         return EmitFromMemory(V, Ty);
14497ae0e2c9SDimitry Andric       }
14507ae0e2c9SDimitry Andric     }
145120e90f04SDimitry Andric   }
14527ae0e2c9SDimitry Andric 
1453139f7f9bSDimitry Andric   // Atomic operations have to be done on integral types.
1454e7145dcbSDimitry Andric   LValue AtomicLValue =
1455d8866befSDimitry Andric       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1456e7145dcbSDimitry Andric   if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1457e7145dcbSDimitry Andric     return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1458139f7f9bSDimitry Andric   }
1459139f7f9bSDimitry Andric 
14600623d748SDimitry Andric   llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
14610623d748SDimitry Andric   if (isNontemporal) {
14620623d748SDimitry Andric     llvm::MDNode *Node = llvm::MDNode::get(
14630623d748SDimitry Andric         Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
14640623d748SDimitry Andric     Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
14650623d748SDimitry Andric   }
1466139f7f9bSDimitry Andric   if (TBAAInfo) {
1467302affcbSDimitry Andric     bool MayAlias = BaseInfo.getMayAlias();
1468302affcbSDimitry Andric     llvm::MDNode *TBAA = MayAlias
1469302affcbSDimitry Andric         ? CGM.getTBAAInfo(getContext().CharTy)
1470302affcbSDimitry Andric         : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1471302affcbSDimitry Andric     if (TBAA)
1472302affcbSDimitry Andric       CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias);
1473139f7f9bSDimitry Andric   }
1474dff0c46cSDimitry Andric 
147520e90f04SDimitry Andric   if (EmitScalarRangeCheck(Load, Ty, Loc)) {
147620e90f04SDimitry Andric     // In order to prevent the optimizer from throwing away the check, don't
147720e90f04SDimitry Andric     // attach range metadata to the load.
1478139f7f9bSDimitry Andric   } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1479dff0c46cSDimitry Andric     if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1480dff0c46cSDimitry Andric       Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1481f22ef01cSRoman Divacky 
14822754fe60SDimitry Andric   return EmitFromMemory(Load, Ty);
14832754fe60SDimitry Andric }
1484f22ef01cSRoman Divacky 
14852754fe60SDimitry Andric llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
14862754fe60SDimitry Andric   // Bool has a different representation in memory than in registers.
1487dff0c46cSDimitry Andric   if (hasBooleanRepresentation(Ty)) {
14882754fe60SDimitry Andric     // This should really always be an i1, but sometimes it's already
14892754fe60SDimitry Andric     // an i8, and it's awkward to track those cases down.
14902754fe60SDimitry Andric     if (Value->getType()->isIntegerTy(1))
1491139f7f9bSDimitry Andric       return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1492139f7f9bSDimitry Andric     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1493139f7f9bSDimitry Andric            "wrong value rep of bool");
14942754fe60SDimitry Andric   }
14952754fe60SDimitry Andric 
14962754fe60SDimitry Andric   return Value;
14972754fe60SDimitry Andric }
14982754fe60SDimitry Andric 
14992754fe60SDimitry Andric llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
15002754fe60SDimitry Andric   // Bool has a different representation in memory than in registers.
1501dff0c46cSDimitry Andric   if (hasBooleanRepresentation(Ty)) {
1502139f7f9bSDimitry Andric     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1503139f7f9bSDimitry Andric            "wrong value rep of bool");
15042754fe60SDimitry Andric     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
15052754fe60SDimitry Andric   }
15062754fe60SDimitry Andric 
15072754fe60SDimitry Andric   return Value;
1508f22ef01cSRoman Divacky }
1509f22ef01cSRoman Divacky 
15100623d748SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
15110623d748SDimitry Andric                                         bool Volatile, QualType Ty,
1512d8866befSDimitry Andric                                         LValueBaseInfo BaseInfo,
15130623d748SDimitry Andric                                         llvm::MDNode *TBAAInfo,
1514139f7f9bSDimitry Andric                                         bool isInit, QualType TBAABaseType,
15150623d748SDimitry Andric                                         uint64_t TBAAOffset,
15160623d748SDimitry Andric                                         bool isNontemporal) {
15177ae0e2c9SDimitry Andric 
151820e90f04SDimitry Andric   if (!CGM.getCodeGenOpts().PreserveVec3Type) {
15197ae0e2c9SDimitry Andric     // Handle vectors differently to get better performance.
15207ae0e2c9SDimitry Andric     if (Ty->isVectorType()) {
15217ae0e2c9SDimitry Andric       llvm::Type *SrcTy = Value->getType();
15226d97bb29SDimitry Andric       auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
15237ae0e2c9SDimitry Andric       // Handle vec3 special.
15246d97bb29SDimitry Andric       if (VecTy && VecTy->getNumElements() == 3) {
15257ae0e2c9SDimitry Andric         // Our source is a vec3, do a shuffle vector to make it a vec4.
15260623d748SDimitry Andric         llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
15270623d748SDimitry Andric                                   Builder.getInt32(2),
15280623d748SDimitry Andric                                   llvm::UndefValue::get(Builder.getInt32Ty())};
15297ae0e2c9SDimitry Andric         llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
153020e90f04SDimitry Andric         Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
15317ae0e2c9SDimitry Andric                                             MaskV, "extractVec");
15327ae0e2c9SDimitry Andric         SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
15337ae0e2c9SDimitry Andric       }
15340623d748SDimitry Andric       if (Addr.getElementType() != SrcTy) {
15350623d748SDimitry Andric         Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
15367ae0e2c9SDimitry Andric       }
15377ae0e2c9SDimitry Andric     }
153820e90f04SDimitry Andric   }
15397ae0e2c9SDimitry Andric 
15402754fe60SDimitry Andric   Value = EmitToMemory(Value, Ty);
154117a519f9SDimitry Andric 
1542e7145dcbSDimitry Andric   LValue AtomicLValue =
1543d8866befSDimitry Andric       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
154433956c43SDimitry Andric   if (Ty->isAtomicType() ||
1545e7145dcbSDimitry Andric       (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1546e7145dcbSDimitry Andric     EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1547139f7f9bSDimitry Andric     return;
1548139f7f9bSDimitry Andric   }
1549139f7f9bSDimitry Andric 
1550e580952dSDimitry Andric   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
15510623d748SDimitry Andric   if (isNontemporal) {
15520623d748SDimitry Andric     llvm::MDNode *Node =
15530623d748SDimitry Andric         llvm::MDNode::get(Store->getContext(),
15540623d748SDimitry Andric                           llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
15550623d748SDimitry Andric     Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
15560623d748SDimitry Andric   }
1557139f7f9bSDimitry Andric   if (TBAAInfo) {
1558302affcbSDimitry Andric     bool MayAlias = BaseInfo.getMayAlias();
1559302affcbSDimitry Andric     llvm::MDNode *TBAA = MayAlias
1560302affcbSDimitry Andric         ? CGM.getTBAAInfo(getContext().CharTy)
1561302affcbSDimitry Andric         : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1562302affcbSDimitry Andric     if (TBAA)
1563302affcbSDimitry Andric       CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias);
1564139f7f9bSDimitry Andric   }
1565f22ef01cSRoman Divacky }
1566f22ef01cSRoman Divacky 
1567dff0c46cSDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1568dff0c46cSDimitry Andric                                         bool isInit) {
156917a519f9SDimitry Andric   EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1570d8866befSDimitry Andric                     lvalue.getType(), lvalue.getBaseInfo(),
1571139f7f9bSDimitry Andric                     lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
15720623d748SDimitry Andric                     lvalue.getTBAAOffset(), lvalue.isNontemporal());
157317a519f9SDimitry Andric }
157417a519f9SDimitry Andric 
1575f22ef01cSRoman Divacky /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1576f22ef01cSRoman Divacky /// method emits the address of the lvalue, then loads the result as an rvalue,
1577f22ef01cSRoman Divacky /// returning the rvalue.
1578f785676fSDimitry Andric RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1579f22ef01cSRoman Divacky   if (LV.isObjCWeak()) {
1580f22ef01cSRoman Divacky     // load of a __weak object.
15810623d748SDimitry Andric     Address AddrWeakObj = LV.getAddress();
1582f22ef01cSRoman Divacky     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1583f22ef01cSRoman Divacky                                                              AddrWeakObj));
1584f22ef01cSRoman Divacky   }
1585139f7f9bSDimitry Andric   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
15860623d748SDimitry Andric     // In MRC mode, we do a load+autorelease.
15870623d748SDimitry Andric     if (!getLangOpts().ObjCAutoRefCount) {
15880623d748SDimitry Andric       return RValue::get(EmitARCLoadWeak(LV.getAddress()));
15890623d748SDimitry Andric     }
15900623d748SDimitry Andric 
15910623d748SDimitry Andric     // In ARC mode, we load retained and then consume the value.
1592139f7f9bSDimitry Andric     llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1593139f7f9bSDimitry Andric     Object = EmitObjCConsumeObject(LV.getType(), Object);
1594139f7f9bSDimitry Andric     return RValue::get(Object);
1595139f7f9bSDimitry Andric   }
1596f22ef01cSRoman Divacky 
1597f22ef01cSRoman Divacky   if (LV.isSimple()) {
159817a519f9SDimitry Andric     assert(!LV.getType()->isFunctionType());
1599e580952dSDimitry Andric 
1600e580952dSDimitry Andric     // Everything needs a load.
1601f785676fSDimitry Andric     return RValue::get(EmitLoadOfScalar(LV, Loc));
1602f22ef01cSRoman Divacky   }
1603f22ef01cSRoman Divacky 
1604f22ef01cSRoman Divacky   if (LV.isVectorElt()) {
16050623d748SDimitry Andric     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
16066122f3e6SDimitry Andric                                               LV.isVolatileQualified());
1607dff0c46cSDimitry Andric     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1608f22ef01cSRoman Divacky                                                     "vecext"));
1609f22ef01cSRoman Divacky   }
1610f22ef01cSRoman Divacky 
1611f22ef01cSRoman Divacky   // If this is a reference to a subset of the elements of a vector, either
1612f22ef01cSRoman Divacky   // shuffle the input or extract/insert them as appropriate.
1613f22ef01cSRoman Divacky   if (LV.isExtVectorElt())
161417a519f9SDimitry Andric     return EmitLoadOfExtVectorElementLValue(LV);
1615f22ef01cSRoman Divacky 
161659d1ed5bSDimitry Andric   // Global Register variables always invoke intrinsics
161759d1ed5bSDimitry Andric   if (LV.isGlobalReg())
161859d1ed5bSDimitry Andric     return EmitLoadOfGlobalRegLValue(LV);
161959d1ed5bSDimitry Andric 
1620dff0c46cSDimitry Andric   assert(LV.isBitField() && "Unknown LValue type!");
162120e90f04SDimitry Andric   return EmitLoadOfBitfieldLValue(LV, Loc);
1622f22ef01cSRoman Divacky }
1623f22ef01cSRoman Divacky 
162420e90f04SDimitry Andric RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
162520e90f04SDimitry Andric                                                  SourceLocation Loc) {
1626f22ef01cSRoman Divacky   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1627f22ef01cSRoman Divacky 
1628f22ef01cSRoman Divacky   // Get the output type.
16296122f3e6SDimitry Andric   llvm::Type *ResLTy = ConvertType(LV.getType());
1630f22ef01cSRoman Divacky 
16310623d748SDimitry Andric   Address Ptr = LV.getBitFieldAddress();
16320623d748SDimitry Andric   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1633f22ef01cSRoman Divacky 
1634139f7f9bSDimitry Andric   if (Info.IsSigned) {
1635139f7f9bSDimitry Andric     assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1636139f7f9bSDimitry Andric     unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1637139f7f9bSDimitry Andric     if (HighBits)
1638139f7f9bSDimitry Andric       Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1639139f7f9bSDimitry Andric     if (Info.Offset + HighBits)
1640139f7f9bSDimitry Andric       Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1641139f7f9bSDimitry Andric   } else {
1642139f7f9bSDimitry Andric     if (Info.Offset)
1643139f7f9bSDimitry Andric       Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1644139f7f9bSDimitry Andric     if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1645139f7f9bSDimitry Andric       Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1646139f7f9bSDimitry Andric                                                               Info.Size),
1647f22ef01cSRoman Divacky                               "bf.clear");
1648f22ef01cSRoman Divacky   }
1649139f7f9bSDimitry Andric   Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
165020e90f04SDimitry Andric   EmitScalarRangeCheck(Val, LV.getType(), Loc);
1651139f7f9bSDimitry Andric   return RValue::get(Val);
1652f22ef01cSRoman Divacky }
1653f22ef01cSRoman Divacky 
1654f22ef01cSRoman Divacky // If this is a reference to a subset of the elements of a vector, create an
1655f22ef01cSRoman Divacky // appropriate shufflevector.
165617a519f9SDimitry Andric RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
16570623d748SDimitry Andric   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
16586122f3e6SDimitry Andric                                         LV.isVolatileQualified());
1659f22ef01cSRoman Divacky 
1660f22ef01cSRoman Divacky   const llvm::Constant *Elts = LV.getExtVectorElts();
1661f22ef01cSRoman Divacky 
1662f22ef01cSRoman Divacky   // If the result of the expression is a non-vector type, we must be extracting
1663f22ef01cSRoman Divacky   // a single element.  Just codegen as an extractelement.
166417a519f9SDimitry Andric   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1665f22ef01cSRoman Divacky   if (!ExprVT) {
1666f22ef01cSRoman Divacky     unsigned InIdx = getAccessedFieldNo(0, Elts);
166759d1ed5bSDimitry Andric     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
16686122f3e6SDimitry Andric     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1669f22ef01cSRoman Divacky   }
1670f22ef01cSRoman Divacky 
1671f22ef01cSRoman Divacky   // Always use shuffle vector to try to retain the original program structure
1672f22ef01cSRoman Divacky   unsigned NumResultElts = ExprVT->getNumElements();
1673f22ef01cSRoman Divacky 
16746122f3e6SDimitry Andric   SmallVector<llvm::Constant*, 4> Mask;
1675dff0c46cSDimitry Andric   for (unsigned i = 0; i != NumResultElts; ++i)
1676dff0c46cSDimitry Andric     Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1677f22ef01cSRoman Divacky 
16782754fe60SDimitry Andric   llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
16792754fe60SDimitry Andric   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
16806122f3e6SDimitry Andric                                     MaskV);
1681f22ef01cSRoman Divacky   return RValue::get(Vec);
1682f22ef01cSRoman Divacky }
1683f22ef01cSRoman Divacky 
168439d628a0SDimitry Andric /// @brief Generates lvalue for partial ext_vector access.
16850623d748SDimitry Andric Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
16860623d748SDimitry Andric   Address VectorAddress = LV.getExtVectorAddress();
168739d628a0SDimitry Andric   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
168839d628a0SDimitry Andric   QualType EQT = ExprVT->getElementType();
168939d628a0SDimitry Andric   llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
169039d628a0SDimitry Andric 
16910623d748SDimitry Andric   Address CastToPointerElement =
16920623d748SDimitry Andric     Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
16930623d748SDimitry Andric                                  "conv.ptr.element");
169439d628a0SDimitry Andric 
169539d628a0SDimitry Andric   const llvm::Constant *Elts = LV.getExtVectorElts();
169639d628a0SDimitry Andric   unsigned ix = getAccessedFieldNo(0, Elts);
169739d628a0SDimitry Andric 
16980623d748SDimitry Andric   Address VectorBasePtrPlusIx =
16990623d748SDimitry Andric     Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
17000623d748SDimitry Andric                                    getContext().getTypeSizeInChars(EQT),
17010623d748SDimitry Andric                                    "vector.elt");
170239d628a0SDimitry Andric 
170339d628a0SDimitry Andric   return VectorBasePtrPlusIx;
170439d628a0SDimitry Andric }
170539d628a0SDimitry Andric 
170659d1ed5bSDimitry Andric /// @brief Load of global gamed gegisters are always calls to intrinsics.
170759d1ed5bSDimitry Andric RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
170859d1ed5bSDimitry Andric   assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
170959d1ed5bSDimitry Andric          "Bad type for register variable");
171039d628a0SDimitry Andric   llvm::MDNode *RegName = cast<llvm::MDNode>(
171139d628a0SDimitry Andric       cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
171259d1ed5bSDimitry Andric 
171359d1ed5bSDimitry Andric   // We accept integer and pointer types only
171459d1ed5bSDimitry Andric   llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
171559d1ed5bSDimitry Andric   llvm::Type *Ty = OrigTy;
171659d1ed5bSDimitry Andric   if (OrigTy->isPointerTy())
171759d1ed5bSDimitry Andric     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
171859d1ed5bSDimitry Andric   llvm::Type *Types[] = { Ty };
171959d1ed5bSDimitry Andric 
172059d1ed5bSDimitry Andric   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
172139d628a0SDimitry Andric   llvm::Value *Call = Builder.CreateCall(
172239d628a0SDimitry Andric       F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
172359d1ed5bSDimitry Andric   if (OrigTy->isPointerTy())
172459d1ed5bSDimitry Andric     Call = Builder.CreateIntToPtr(Call, OrigTy);
172559d1ed5bSDimitry Andric   return RValue::get(Call);
172659d1ed5bSDimitry Andric }
1727f22ef01cSRoman Divacky 
1728f22ef01cSRoman Divacky 
1729f22ef01cSRoman Divacky /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1730f22ef01cSRoman Divacky /// lvalue, where both are guaranteed to the have the same type, and that type
1731f22ef01cSRoman Divacky /// is 'Ty'.
1732f785676fSDimitry Andric void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1733f785676fSDimitry Andric                                              bool isInit) {
1734f22ef01cSRoman Divacky   if (!Dst.isSimple()) {
1735f22ef01cSRoman Divacky     if (Dst.isVectorElt()) {
1736f22ef01cSRoman Divacky       // Read/modify/write the vector, inserting the new element.
17370623d748SDimitry Andric       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
17386122f3e6SDimitry Andric                                             Dst.isVolatileQualified());
1739f22ef01cSRoman Divacky       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1740f22ef01cSRoman Divacky                                         Dst.getVectorIdx(), "vecins");
17410623d748SDimitry Andric       Builder.CreateStore(Vec, Dst.getVectorAddress(),
1742dff0c46cSDimitry Andric                           Dst.isVolatileQualified());
1743f22ef01cSRoman Divacky       return;
1744f22ef01cSRoman Divacky     }
1745f22ef01cSRoman Divacky 
1746f22ef01cSRoman Divacky     // If this is an update of extended vector elements, insert them as
1747f22ef01cSRoman Divacky     // appropriate.
1748f22ef01cSRoman Divacky     if (Dst.isExtVectorElt())
174917a519f9SDimitry Andric       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1750f22ef01cSRoman Divacky 
175159d1ed5bSDimitry Andric     if (Dst.isGlobalReg())
175259d1ed5bSDimitry Andric       return EmitStoreThroughGlobalRegLValue(Src, Dst);
175359d1ed5bSDimitry Andric 
1754dff0c46cSDimitry Andric     assert(Dst.isBitField() && "Unknown LValue type");
175517a519f9SDimitry Andric     return EmitStoreThroughBitfieldLValue(Src, Dst);
1756f22ef01cSRoman Divacky   }
1757f22ef01cSRoman Divacky 
175817a519f9SDimitry Andric   // There's special magic for assigning into an ARC-qualified l-value.
175917a519f9SDimitry Andric   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
176017a519f9SDimitry Andric     switch (Lifetime) {
176117a519f9SDimitry Andric     case Qualifiers::OCL_None:
176217a519f9SDimitry Andric       llvm_unreachable("present but none");
176317a519f9SDimitry Andric 
176417a519f9SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
176517a519f9SDimitry Andric       // nothing special
176617a519f9SDimitry Andric       break;
176717a519f9SDimitry Andric 
176817a519f9SDimitry Andric     case Qualifiers::OCL_Strong:
176944290647SDimitry Andric       if (isInit) {
177044290647SDimitry Andric         Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
177144290647SDimitry Andric         break;
177244290647SDimitry Andric       }
177317a519f9SDimitry Andric       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
177417a519f9SDimitry Andric       return;
177517a519f9SDimitry Andric 
177617a519f9SDimitry Andric     case Qualifiers::OCL_Weak:
177744290647SDimitry Andric       if (isInit)
177844290647SDimitry Andric         // Initialize and then skip the primitive store.
177944290647SDimitry Andric         EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
178044290647SDimitry Andric       else
178117a519f9SDimitry Andric         EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
178217a519f9SDimitry Andric       return;
178317a519f9SDimitry Andric 
178417a519f9SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
178517a519f9SDimitry Andric       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
178617a519f9SDimitry Andric                                                      Src.getScalarVal()));
178717a519f9SDimitry Andric       // fall into the normal path
178817a519f9SDimitry Andric       break;
178917a519f9SDimitry Andric     }
179017a519f9SDimitry Andric   }
179117a519f9SDimitry Andric 
1792f22ef01cSRoman Divacky   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1793f22ef01cSRoman Divacky     // load of a __weak object.
17940623d748SDimitry Andric     Address LvalueDst = Dst.getAddress();
1795f22ef01cSRoman Divacky     llvm::Value *src = Src.getScalarVal();
1796f22ef01cSRoman Divacky      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1797f22ef01cSRoman Divacky     return;
1798f22ef01cSRoman Divacky   }
1799f22ef01cSRoman Divacky 
1800f22ef01cSRoman Divacky   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1801f22ef01cSRoman Divacky     // load of a __strong object.
18020623d748SDimitry Andric     Address LvalueDst = Dst.getAddress();
1803f22ef01cSRoman Divacky     llvm::Value *src = Src.getScalarVal();
1804f22ef01cSRoman Divacky     if (Dst.isObjCIvar()) {
1805f22ef01cSRoman Divacky       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
18060623d748SDimitry Andric       llvm::Type *ResultType = IntPtrTy;
18070623d748SDimitry Andric       Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
18080623d748SDimitry Andric       llvm::Value *RHS = dst.getPointer();
1809f22ef01cSRoman Divacky       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1810f22ef01cSRoman Divacky       llvm::Value *LHS =
18110623d748SDimitry Andric         Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
18120623d748SDimitry Andric                                "sub.ptr.lhs.cast");
1813f22ef01cSRoman Divacky       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1814f22ef01cSRoman Divacky       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1815f22ef01cSRoman Divacky                                               BytesBetween);
1816e580952dSDimitry Andric     } else if (Dst.isGlobalObjCRef()) {
1817e580952dSDimitry Andric       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1818e580952dSDimitry Andric                                                 Dst.isThreadLocalRef());
1819e580952dSDimitry Andric     }
1820f22ef01cSRoman Divacky     else
1821f22ef01cSRoman Divacky       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1822f22ef01cSRoman Divacky     return;
1823f22ef01cSRoman Divacky   }
1824f22ef01cSRoman Divacky 
1825f22ef01cSRoman Divacky   assert(Src.isScalar() && "Can't emit an agg store with this method");
1826dff0c46cSDimitry Andric   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1827f22ef01cSRoman Divacky }
1828f22ef01cSRoman Divacky 
1829f22ef01cSRoman Divacky void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1830f22ef01cSRoman Divacky                                                      llvm::Value **Result) {
1831f22ef01cSRoman Divacky   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
18326122f3e6SDimitry Andric   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
18330623d748SDimitry Andric   Address Ptr = Dst.getBitFieldAddress();
1834f22ef01cSRoman Divacky 
1835f22ef01cSRoman Divacky   // Get the source value, truncated to the width of the bit-field.
1836f22ef01cSRoman Divacky   llvm::Value *SrcVal = Src.getScalarVal();
1837f22ef01cSRoman Divacky 
1838139f7f9bSDimitry Andric   // Cast the source to the storage type and shift it into place.
18390623d748SDimitry Andric   SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1840139f7f9bSDimitry Andric                                  /*IsSigned=*/false);
1841139f7f9bSDimitry Andric   llvm::Value *MaskedVal = SrcVal;
1842f22ef01cSRoman Divacky 
1843139f7f9bSDimitry Andric   // See if there are other bits in the bitfield's storage we'll need to load
1844139f7f9bSDimitry Andric   // and mask together with source before storing.
1845139f7f9bSDimitry Andric   if (Info.StorageSize != Info.Size) {
1846139f7f9bSDimitry Andric     assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
18470623d748SDimitry Andric     llvm::Value *Val =
18480623d748SDimitry Andric       Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1849139f7f9bSDimitry Andric 
1850139f7f9bSDimitry Andric     // Mask the source value as needed.
1851139f7f9bSDimitry Andric     if (!hasBooleanRepresentation(Dst.getType()))
1852139f7f9bSDimitry Andric       SrcVal = Builder.CreateAnd(SrcVal,
1853139f7f9bSDimitry Andric                                  llvm::APInt::getLowBitsSet(Info.StorageSize,
1854139f7f9bSDimitry Andric                                                             Info.Size),
1855f22ef01cSRoman Divacky                                  "bf.value");
1856139f7f9bSDimitry Andric     MaskedVal = SrcVal;
1857139f7f9bSDimitry Andric     if (Info.Offset)
1858139f7f9bSDimitry Andric       SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1859139f7f9bSDimitry Andric 
1860139f7f9bSDimitry Andric     // Mask out the original value.
1861139f7f9bSDimitry Andric     Val = Builder.CreateAnd(Val,
1862139f7f9bSDimitry Andric                             ~llvm::APInt::getBitsSet(Info.StorageSize,
1863139f7f9bSDimitry Andric                                                      Info.Offset,
1864139f7f9bSDimitry Andric                                                      Info.Offset + Info.Size),
1865139f7f9bSDimitry Andric                             "bf.clear");
1866139f7f9bSDimitry Andric 
1867139f7f9bSDimitry Andric     // Or together the unchanged values and the source value.
1868139f7f9bSDimitry Andric     SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1869139f7f9bSDimitry Andric   } else {
1870139f7f9bSDimitry Andric     assert(Info.Offset == 0);
1871139f7f9bSDimitry Andric   }
1872139f7f9bSDimitry Andric 
1873139f7f9bSDimitry Andric   // Write the new value back out.
18740623d748SDimitry Andric   Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1875f22ef01cSRoman Divacky 
1876f22ef01cSRoman Divacky   // Return the new value of the bit-field, if requested.
1877f22ef01cSRoman Divacky   if (Result) {
1878139f7f9bSDimitry Andric     llvm::Value *ResultVal = MaskedVal;
1879f22ef01cSRoman Divacky 
1880139f7f9bSDimitry Andric     // Sign extend the value if needed.
1881139f7f9bSDimitry Andric     if (Info.IsSigned) {
1882139f7f9bSDimitry Andric       assert(Info.Size <= Info.StorageSize);
1883139f7f9bSDimitry Andric       unsigned HighBits = Info.StorageSize - Info.Size;
1884139f7f9bSDimitry Andric       if (HighBits) {
1885139f7f9bSDimitry Andric         ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1886139f7f9bSDimitry Andric         ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1887139f7f9bSDimitry Andric       }
1888f22ef01cSRoman Divacky     }
1889f22ef01cSRoman Divacky 
1890139f7f9bSDimitry Andric     ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1891139f7f9bSDimitry Andric                                       "bf.result.cast");
1892139f7f9bSDimitry Andric     *Result = EmitFromMemory(ResultVal, Dst.getType());
1893f22ef01cSRoman Divacky   }
1894f22ef01cSRoman Divacky }
1895f22ef01cSRoman Divacky 
1896f22ef01cSRoman Divacky void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
189717a519f9SDimitry Andric                                                                LValue Dst) {
1898f22ef01cSRoman Divacky   // This access turns into a read/modify/write of the vector.  Load the input
1899f22ef01cSRoman Divacky   // value now.
19000623d748SDimitry Andric   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
19016122f3e6SDimitry Andric                                         Dst.isVolatileQualified());
1902f22ef01cSRoman Divacky   const llvm::Constant *Elts = Dst.getExtVectorElts();
1903f22ef01cSRoman Divacky 
1904f22ef01cSRoman Divacky   llvm::Value *SrcVal = Src.getScalarVal();
1905f22ef01cSRoman Divacky 
190617a519f9SDimitry Andric   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1907f22ef01cSRoman Divacky     unsigned NumSrcElts = VTy->getNumElements();
1908e7145dcbSDimitry Andric     unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1909f22ef01cSRoman Divacky     if (NumDstElts == NumSrcElts) {
1910f22ef01cSRoman Divacky       // Use shuffle vector is the src and destination are the same number of
1911f22ef01cSRoman Divacky       // elements and restore the vector mask since it is on the side it will be
1912f22ef01cSRoman Divacky       // stored.
19136122f3e6SDimitry Andric       SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1914dff0c46cSDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
1915dff0c46cSDimitry Andric         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1916f22ef01cSRoman Divacky 
19172754fe60SDimitry Andric       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1918f22ef01cSRoman Divacky       Vec = Builder.CreateShuffleVector(SrcVal,
1919f22ef01cSRoman Divacky                                         llvm::UndefValue::get(Vec->getType()),
19206122f3e6SDimitry Andric                                         MaskV);
1921f22ef01cSRoman Divacky     } else if (NumDstElts > NumSrcElts) {
1922f22ef01cSRoman Divacky       // Extended the source vector to the same length and then shuffle it
1923f22ef01cSRoman Divacky       // into the destination.
1924f22ef01cSRoman Divacky       // FIXME: since we're shuffling with undef, can we just use the indices
1925f22ef01cSRoman Divacky       //        into that?  This could be simpler.
19266122f3e6SDimitry Andric       SmallVector<llvm::Constant*, 4> ExtMask;
1927dff0c46cSDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
1928dff0c46cSDimitry Andric         ExtMask.push_back(Builder.getInt32(i));
1929dff0c46cSDimitry Andric       ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
19302754fe60SDimitry Andric       llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1931f22ef01cSRoman Divacky       llvm::Value *ExtSrcVal =
1932f22ef01cSRoman Divacky         Builder.CreateShuffleVector(SrcVal,
1933f22ef01cSRoman Divacky                                     llvm::UndefValue::get(SrcVal->getType()),
19346122f3e6SDimitry Andric                                     ExtMaskV);
1935f22ef01cSRoman Divacky       // build identity
19366122f3e6SDimitry Andric       SmallVector<llvm::Constant*, 4> Mask;
1937f22ef01cSRoman Divacky       for (unsigned i = 0; i != NumDstElts; ++i)
1938dff0c46cSDimitry Andric         Mask.push_back(Builder.getInt32(i));
1939f22ef01cSRoman Divacky 
1940f785676fSDimitry Andric       // When the vector size is odd and .odd or .hi is used, the last element
1941f785676fSDimitry Andric       // of the Elts constant array will be one past the size of the vector.
1942f785676fSDimitry Andric       // Ignore the last element here, if it is greater than the mask size.
1943f785676fSDimitry Andric       if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1944f785676fSDimitry Andric         NumSrcElts--;
1945f785676fSDimitry Andric 
1946f22ef01cSRoman Divacky       // modify when what gets shuffled in
1947dff0c46cSDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
1948dff0c46cSDimitry Andric         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
19492754fe60SDimitry Andric       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
19506122f3e6SDimitry Andric       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1951f22ef01cSRoman Divacky     } else {
1952f22ef01cSRoman Divacky       // We should never shorten the vector
19536122f3e6SDimitry Andric       llvm_unreachable("unexpected shorten vector length");
1954f22ef01cSRoman Divacky     }
1955f22ef01cSRoman Divacky   } else {
1956f22ef01cSRoman Divacky     // If the Src is a scalar (not a vector) it must be updating one element.
1957f22ef01cSRoman Divacky     unsigned InIdx = getAccessedFieldNo(0, Elts);
195859d1ed5bSDimitry Andric     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
19596122f3e6SDimitry Andric     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1960f22ef01cSRoman Divacky   }
1961f22ef01cSRoman Divacky 
19620623d748SDimitry Andric   Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1963dff0c46cSDimitry Andric                       Dst.isVolatileQualified());
1964f22ef01cSRoman Divacky }
1965f22ef01cSRoman Divacky 
196659d1ed5bSDimitry Andric /// @brief Store of global named registers are always calls to intrinsics.
196759d1ed5bSDimitry Andric void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
196859d1ed5bSDimitry Andric   assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
196959d1ed5bSDimitry Andric          "Bad type for register variable");
197039d628a0SDimitry Andric   llvm::MDNode *RegName = cast<llvm::MDNode>(
197139d628a0SDimitry Andric       cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
197259d1ed5bSDimitry Andric   assert(RegName && "Register LValue is not metadata");
197359d1ed5bSDimitry Andric 
197459d1ed5bSDimitry Andric   // We accept integer and pointer types only
197559d1ed5bSDimitry Andric   llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
197659d1ed5bSDimitry Andric   llvm::Type *Ty = OrigTy;
197759d1ed5bSDimitry Andric   if (OrigTy->isPointerTy())
197859d1ed5bSDimitry Andric     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
197959d1ed5bSDimitry Andric   llvm::Type *Types[] = { Ty };
198059d1ed5bSDimitry Andric 
198159d1ed5bSDimitry Andric   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
198259d1ed5bSDimitry Andric   llvm::Value *Value = Src.getScalarVal();
198359d1ed5bSDimitry Andric   if (OrigTy->isPointerTy())
198459d1ed5bSDimitry Andric     Value = Builder.CreatePtrToInt(Value, Ty);
198533956c43SDimitry Andric   Builder.CreateCall(
198633956c43SDimitry Andric       F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
198759d1ed5bSDimitry Andric }
198859d1ed5bSDimitry Andric 
198959d1ed5bSDimitry Andric // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1990f22ef01cSRoman Divacky // generating write-barries API. It is currently a global, ivar,
1991f22ef01cSRoman Divacky // or neither.
1992f22ef01cSRoman Divacky static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
19936122f3e6SDimitry Andric                                  LValue &LV,
19946122f3e6SDimitry Andric                                  bool IsMemberAccess=false) {
1995dff0c46cSDimitry Andric   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1996f22ef01cSRoman Divacky     return;
1997f22ef01cSRoman Divacky 
1998f22ef01cSRoman Divacky   if (isa<ObjCIvarRefExpr>(E)) {
19996122f3e6SDimitry Andric     QualType ExpTy = E->getType();
20006122f3e6SDimitry Andric     if (IsMemberAccess && ExpTy->isPointerType()) {
20016122f3e6SDimitry Andric       // If ivar is a structure pointer, assigning to field of
20026122f3e6SDimitry Andric       // this struct follows gcc's behavior and makes it a non-ivar
20036122f3e6SDimitry Andric       // writer-barrier conservatively.
20046122f3e6SDimitry Andric       ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
20056122f3e6SDimitry Andric       if (ExpTy->isRecordType()) {
20066122f3e6SDimitry Andric         LV.setObjCIvar(false);
20076122f3e6SDimitry Andric         return;
20086122f3e6SDimitry Andric       }
20096122f3e6SDimitry Andric     }
2010e580952dSDimitry Andric     LV.setObjCIvar(true);
201159d1ed5bSDimitry Andric     auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2012f22ef01cSRoman Divacky     LV.setBaseIvarExp(Exp->getBase());
2013e580952dSDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
2014f22ef01cSRoman Divacky     return;
2015f22ef01cSRoman Divacky   }
2016f22ef01cSRoman Divacky 
201759d1ed5bSDimitry Andric   if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
201859d1ed5bSDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
20192754fe60SDimitry Andric       if (VD->hasGlobalStorage()) {
2020e580952dSDimitry Andric         LV.setGlobalObjCRef(true);
2021284c1978SDimitry Andric         LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2022f22ef01cSRoman Divacky       }
2023e580952dSDimitry Andric     }
2024e580952dSDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
2025f22ef01cSRoman Divacky     return;
2026f22ef01cSRoman Divacky   }
2027f22ef01cSRoman Divacky 
202859d1ed5bSDimitry Andric   if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
20296122f3e6SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2030f22ef01cSRoman Divacky     return;
2031f22ef01cSRoman Divacky   }
2032f22ef01cSRoman Divacky 
203359d1ed5bSDimitry Andric   if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
20346122f3e6SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2035f22ef01cSRoman Divacky     if (LV.isObjCIvar()) {
2036f22ef01cSRoman Divacky       // If cast is to a structure pointer, follow gcc's behavior and make it
2037f22ef01cSRoman Divacky       // a non-ivar write-barrier.
2038f22ef01cSRoman Divacky       QualType ExpTy = E->getType();
2039f22ef01cSRoman Divacky       if (ExpTy->isPointerType())
2040f22ef01cSRoman Divacky         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2041f22ef01cSRoman Divacky       if (ExpTy->isRecordType())
2042e580952dSDimitry Andric         LV.setObjCIvar(false);
2043f22ef01cSRoman Divacky     }
2044f22ef01cSRoman Divacky     return;
2045f22ef01cSRoman Divacky   }
20463b0f4066SDimitry Andric 
204759d1ed5bSDimitry Andric   if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
20483b0f4066SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
20493b0f4066SDimitry Andric     return;
20503b0f4066SDimitry Andric   }
20513b0f4066SDimitry Andric 
205259d1ed5bSDimitry Andric   if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
20536122f3e6SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2054f22ef01cSRoman Divacky     return;
2055f22ef01cSRoman Divacky   }
2056f22ef01cSRoman Divacky 
205759d1ed5bSDimitry Andric   if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
20586122f3e6SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2059f22ef01cSRoman Divacky     return;
2060f22ef01cSRoman Divacky   }
2061f22ef01cSRoman Divacky 
206259d1ed5bSDimitry Andric   if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
20636122f3e6SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
206417a519f9SDimitry Andric     return;
206517a519f9SDimitry Andric   }
206617a519f9SDimitry Andric 
206759d1ed5bSDimitry Andric   if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2068f22ef01cSRoman Divacky     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2069f22ef01cSRoman Divacky     if (LV.isObjCIvar() && !LV.isObjCArray())
2070f22ef01cSRoman Divacky       // Using array syntax to assigning to what an ivar points to is not
2071f22ef01cSRoman Divacky       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2072e580952dSDimitry Andric       LV.setObjCIvar(false);
2073f22ef01cSRoman Divacky     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2074f22ef01cSRoman Divacky       // Using array syntax to assigning to what global points to is not
2075f22ef01cSRoman Divacky       // same as assigning to the global itself. {id *G;} G[i] = 0;
2076e580952dSDimitry Andric       LV.setGlobalObjCRef(false);
2077f22ef01cSRoman Divacky     return;
2078f22ef01cSRoman Divacky   }
2079f22ef01cSRoman Divacky 
208059d1ed5bSDimitry Andric   if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
20816122f3e6SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2082f22ef01cSRoman Divacky     // We don't know if member is an 'ivar', but this flag is looked at
2083f22ef01cSRoman Divacky     // only in the context of LV.isObjCIvar().
2084e580952dSDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
2085f22ef01cSRoman Divacky     return;
2086f22ef01cSRoman Divacky   }
2087f22ef01cSRoman Divacky }
2088f22ef01cSRoman Divacky 
208917a519f9SDimitry Andric static llvm::Value *
209017a519f9SDimitry Andric EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
209117a519f9SDimitry Andric                                 llvm::Value *V, llvm::Type *IRType,
20926122f3e6SDimitry Andric                                 StringRef Name = StringRef()) {
209317a519f9SDimitry Andric   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
209417a519f9SDimitry Andric   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
209517a519f9SDimitry Andric }
209617a519f9SDimitry Andric 
209739d628a0SDimitry Andric static LValue EmitThreadPrivateVarDeclLValue(
20980623d748SDimitry Andric     CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
20990623d748SDimitry Andric     llvm::Type *RealVarTy, SourceLocation Loc) {
21000623d748SDimitry Andric   Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
21010623d748SDimitry Andric   Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2102d8866befSDimitry Andric   LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2103d8866befSDimitry Andric   return CGF.MakeAddrLValue(Addr, T, BaseInfo);
21040623d748SDimitry Andric }
21050623d748SDimitry Andric 
21060623d748SDimitry Andric Address CodeGenFunction::EmitLoadOfReference(Address Addr,
21070623d748SDimitry Andric                                              const ReferenceType *RefTy,
2108d8866befSDimitry Andric                                              LValueBaseInfo *BaseInfo) {
21090623d748SDimitry Andric   llvm::Value *Ptr = Builder.CreateLoad(Addr);
21100623d748SDimitry Andric   return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
2111d8866befSDimitry Andric                                               BaseInfo, /*forPointee*/ true));
21120623d748SDimitry Andric }
21130623d748SDimitry Andric 
21140623d748SDimitry Andric LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
21150623d748SDimitry Andric                                                   const ReferenceType *RefTy) {
2116d8866befSDimitry Andric   LValueBaseInfo BaseInfo;
2117d8866befSDimitry Andric   Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2118d8866befSDimitry Andric   return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
211939d628a0SDimitry Andric }
212039d628a0SDimitry Andric 
2121e7145dcbSDimitry Andric Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2122e7145dcbSDimitry Andric                                            const PointerType *PtrTy,
2123d8866befSDimitry Andric                                            LValueBaseInfo *BaseInfo) {
2124e7145dcbSDimitry Andric   llvm::Value *Addr = Builder.CreateLoad(Ptr);
2125d8866befSDimitry Andric   return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2126d8866befSDimitry Andric                                                BaseInfo,
2127e7145dcbSDimitry Andric                                                /*forPointeeType=*/true));
2128e7145dcbSDimitry Andric }
2129e7145dcbSDimitry Andric 
2130e7145dcbSDimitry Andric LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2131e7145dcbSDimitry Andric                                                 const PointerType *PtrTy) {
2132d8866befSDimitry Andric   LValueBaseInfo BaseInfo;
2133d8866befSDimitry Andric   Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2134d8866befSDimitry Andric   return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
2135e7145dcbSDimitry Andric }
2136e7145dcbSDimitry Andric 
2137f22ef01cSRoman Divacky static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2138f22ef01cSRoman Divacky                                       const Expr *E, const VarDecl *VD) {
213959d1ed5bSDimitry Andric   QualType T = E->getType();
214059d1ed5bSDimitry Andric 
214159d1ed5bSDimitry Andric   // If it's thread_local, emit a call to its wrapper function instead.
214239d628a0SDimitry Andric   if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
214339d628a0SDimitry Andric       CGF.CGM.getCXXABI().usesThreadWrapperFunction())
214459d1ed5bSDimitry Andric     return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
214559d1ed5bSDimitry Andric 
2146f22ef01cSRoman Divacky   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2147dff0c46cSDimitry Andric   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2148dff0c46cSDimitry Andric   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2149dff0c46cSDimitry Andric   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
21500623d748SDimitry Andric   Address Addr(V, Alignment);
2151dff0c46cSDimitry Andric   LValue LV;
215239d628a0SDimitry Andric   // Emit reference to the private copy of the variable if it is an OpenMP
215339d628a0SDimitry Andric   // threadprivate variable.
215439d628a0SDimitry Andric   if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
21550623d748SDimitry Andric     return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
215639d628a0SDimitry Andric                                           E->getExprLoc());
21570623d748SDimitry Andric   if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
21580623d748SDimitry Andric     LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2159dff0c46cSDimitry Andric   } else {
2160d8866befSDimitry Andric     LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2161d8866befSDimitry Andric     LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
2162dff0c46cSDimitry Andric   }
2163f22ef01cSRoman Divacky   setObjCGCLValueClass(CGF.getContext(), E, LV);
2164f22ef01cSRoman Divacky   return LV;
2165f22ef01cSRoman Divacky }
2166f22ef01cSRoman Divacky 
216744290647SDimitry Andric static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
216844290647SDimitry Andric                                                const FunctionDecl *FD) {
216944290647SDimitry Andric   if (FD->hasAttr<WeakRefAttr>()) {
217044290647SDimitry Andric     ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
217144290647SDimitry Andric     return aliasee.getPointer();
217244290647SDimitry Andric   }
217344290647SDimitry Andric 
217444290647SDimitry Andric   llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2175f22ef01cSRoman Divacky   if (!FD->hasPrototype()) {
2176f22ef01cSRoman Divacky     if (const FunctionProtoType *Proto =
2177f22ef01cSRoman Divacky             FD->getType()->getAs<FunctionProtoType>()) {
2178f22ef01cSRoman Divacky       // Ugly case: for a K&R-style definition, the type of the definition
2179f22ef01cSRoman Divacky       // isn't the same as the type of a use.  Correct for this with a
2180f22ef01cSRoman Divacky       // bitcast.
2181f22ef01cSRoman Divacky       QualType NoProtoType =
218244290647SDimitry Andric           CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
218344290647SDimitry Andric       NoProtoType = CGM.getContext().getPointerType(NoProtoType);
218444290647SDimitry Andric       V = llvm::ConstantExpr::getBitCast(V,
218544290647SDimitry Andric                                       CGM.getTypes().ConvertType(NoProtoType));
2186f22ef01cSRoman Divacky     }
2187f22ef01cSRoman Divacky   }
218844290647SDimitry Andric   return V;
218944290647SDimitry Andric }
219044290647SDimitry Andric 
219144290647SDimitry Andric static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
219244290647SDimitry Andric                                      const Expr *E, const FunctionDecl *FD) {
219344290647SDimitry Andric   llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2194dff0c46cSDimitry Andric   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2195d8866befSDimitry Andric   LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2196d8866befSDimitry Andric   return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
2197f22ef01cSRoman Divacky }
2198f22ef01cSRoman Divacky 
2199f785676fSDimitry Andric static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2200f785676fSDimitry Andric                                       llvm::Value *ThisValue) {
2201f785676fSDimitry Andric   QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2202f785676fSDimitry Andric   LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2203f785676fSDimitry Andric   return CGF.EmitLValueForField(LV, FD);
2204f785676fSDimitry Andric }
2205f785676fSDimitry Andric 
220659d1ed5bSDimitry Andric /// Named Registers are named metadata pointing to the register name
220759d1ed5bSDimitry Andric /// which will be read from/written to as an argument to the intrinsic
220859d1ed5bSDimitry Andric /// @llvm.read/write_register.
220959d1ed5bSDimitry Andric /// So far, only the name is being passed down, but other options such as
221059d1ed5bSDimitry Andric /// register type, allocation type or even optimization options could be
221159d1ed5bSDimitry Andric /// passed down via the metadata node.
22120623d748SDimitry Andric static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
221359d1ed5bSDimitry Andric   SmallString<64> Name("llvm.named.register.");
221459d1ed5bSDimitry Andric   AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
221559d1ed5bSDimitry Andric   assert(Asm->getLabel().size() < 64-Name.size() &&
221659d1ed5bSDimitry Andric       "Register name too big");
221759d1ed5bSDimitry Andric   Name.append(Asm->getLabel());
221859d1ed5bSDimitry Andric   llvm::NamedMDNode *M =
221959d1ed5bSDimitry Andric     CGM.getModule().getOrInsertNamedMetadata(Name);
222059d1ed5bSDimitry Andric   if (M->getNumOperands() == 0) {
222159d1ed5bSDimitry Andric     llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
222259d1ed5bSDimitry Andric                                               Asm->getLabel());
222339d628a0SDimitry Andric     llvm::Metadata *Ops[] = {Str};
222459d1ed5bSDimitry Andric     M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
222559d1ed5bSDimitry Andric   }
22260623d748SDimitry Andric 
22270623d748SDimitry Andric   CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
22280623d748SDimitry Andric 
22290623d748SDimitry Andric   llvm::Value *Ptr =
22300623d748SDimitry Andric     llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
22310623d748SDimitry Andric   return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
223259d1ed5bSDimitry Andric }
223359d1ed5bSDimitry Andric 
2234f22ef01cSRoman Divacky LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2235f22ef01cSRoman Divacky   const NamedDecl *ND = E->getDecl();
2236dff0c46cSDimitry Andric   QualType T = E->getType();
2237dff0c46cSDimitry Andric 
223859d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
223959d1ed5bSDimitry Andric     // Global Named registers access via intrinsics only
224059d1ed5bSDimitry Andric     if (VD->getStorageClass() == SC_Register &&
224159d1ed5bSDimitry Andric         VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
22420623d748SDimitry Andric       return EmitGlobalNamedRegister(VD, CGM);
224359d1ed5bSDimitry Andric 
22443861d79fSDimitry Andric     // A DeclRefExpr for a reference initialized by a constant expression can
22453861d79fSDimitry Andric     // appear without being odr-used. Directly emit the constant initializer.
22463861d79fSDimitry Andric     const Expr *Init = VD->getAnyInitializer(VD);
22473861d79fSDimitry Andric     if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
22483861d79fSDimitry Andric         VD->isUsableInConstantExpressions(getContext()) &&
22490623d748SDimitry Andric         VD->checkInitIsICE() &&
22500623d748SDimitry Andric         // Do not emit if it is private OpenMP variable.
22510623d748SDimitry Andric         !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
22520623d748SDimitry Andric           LocalDeclMap.count(VD))) {
22533861d79fSDimitry Andric       llvm::Constant *Val =
22543861d79fSDimitry Andric         CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
22553861d79fSDimitry Andric       assert(Val && "failed to emit reference constant expression");
22563861d79fSDimitry Andric       // FIXME: Eventually we will want to emit vector element references.
22570623d748SDimitry Andric 
22580623d748SDimitry Andric       // Should we be using the alignment of the constant pointer we emitted?
22590623d748SDimitry Andric       CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
22600623d748SDimitry Andric                                                     /*pointee*/ true);
2261d8866befSDimitry Andric       LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2262d8866befSDimitry Andric       return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
22633861d79fSDimitry Andric     }
226439d628a0SDimitry Andric 
226539d628a0SDimitry Andric     // Check for captured variables.
226639d628a0SDimitry Andric     if (E->refersToEnclosingVariableOrCapture()) {
226739d628a0SDimitry Andric       if (auto *FD = LambdaCaptureFields.lookup(VD))
226839d628a0SDimitry Andric         return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
226939d628a0SDimitry Andric       else if (CapturedStmtInfo) {
2270f41fbc90SDimitry Andric         auto I = LocalDeclMap.find(VD);
2271f41fbc90SDimitry Andric         if (I != LocalDeclMap.end()) {
2272f41fbc90SDimitry Andric           if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2273f41fbc90SDimitry Andric             return EmitLoadOfReferenceLValue(I->second, RefTy);
2274f41fbc90SDimitry Andric           return MakeAddrLValue(I->second, T);
22750623d748SDimitry Andric         }
22760623d748SDimitry Andric         LValue CapLVal =
22770623d748SDimitry Andric             EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
22780623d748SDimitry Andric                                     CapturedStmtInfo->getContextValue());
2279d8866befSDimitry Andric         bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
22800623d748SDimitry Andric         return MakeAddrLValue(
22810623d748SDimitry Andric             Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2282d8866befSDimitry Andric             CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
22830623d748SDimitry Andric       }
22840623d748SDimitry Andric 
228539d628a0SDimitry Andric       assert(isa<BlockDecl>(CurCodeDecl));
22860623d748SDimitry Andric       Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2287d8866befSDimitry Andric       LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2288d8866befSDimitry Andric       return MakeAddrLValue(addr, T, BaseInfo);
228939d628a0SDimitry Andric     }
22903861d79fSDimitry Andric   }
22913861d79fSDimitry Andric 
2292dff0c46cSDimitry Andric   // FIXME: We should be able to assert this for FunctionDecls as well!
2293dff0c46cSDimitry Andric   // FIXME: We should be able to assert this for all DeclRefExprs, not just
2294dff0c46cSDimitry Andric   // those with a valid source location.
2295dff0c46cSDimitry Andric   assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2296dff0c46cSDimitry Andric           !E->getLocation().isValid()) &&
2297dff0c46cSDimitry Andric          "Should not use decl without marking it used!");
2298f22ef01cSRoman Divacky 
2299f22ef01cSRoman Divacky   if (ND->hasAttr<WeakRefAttr>()) {
230059d1ed5bSDimitry Andric     const auto *VD = cast<ValueDecl>(ND);
23010623d748SDimitry Andric     ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2302d8866befSDimitry Andric     return MakeAddrLValue(Aliasee, T,
2303d8866befSDimitry Andric                           LValueBaseInfo(AlignmentSource::Decl, false));
2304f22ef01cSRoman Divacky   }
2305f22ef01cSRoman Divacky 
230659d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2307f22ef01cSRoman Divacky     // Check if this is a global variable.
230859d1ed5bSDimitry Andric     if (VD->hasLinkage() || VD->isStaticDataMember())
2309f22ef01cSRoman Divacky       return EmitGlobalVarDeclLValue(*this, E, VD);
2310f22ef01cSRoman Divacky 
23110623d748SDimitry Andric     Address addr = Address::invalid();
2312dff0c46cSDimitry Andric 
23130623d748SDimitry Andric     // The variable should generally be present in the local decl map.
23140623d748SDimitry Andric     auto iter = LocalDeclMap.find(VD);
23150623d748SDimitry Andric     if (iter != LocalDeclMap.end()) {
23160623d748SDimitry Andric       addr = iter->second;
2317dff0c46cSDimitry Andric 
23180623d748SDimitry Andric     // Otherwise, it might be static local we haven't emitted yet for
23190623d748SDimitry Andric     // some reason; most likely, because it's in an outer function.
23200623d748SDimitry Andric     } else if (VD->isStaticLocal()) {
23210623d748SDimitry Andric       addr = Address(CGM.getOrCreateStaticVarDecl(
23220623d748SDimitry Andric           *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
23230623d748SDimitry Andric                      getContext().getDeclAlign(VD));
2324dff0c46cSDimitry Andric 
23250623d748SDimitry Andric     // No other cases for now.
2326dff0c46cSDimitry Andric     } else {
23270623d748SDimitry Andric       llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
23280623d748SDimitry Andric     }
23290623d748SDimitry Andric 
23300623d748SDimitry Andric 
23310623d748SDimitry Andric     // Check for OpenMP threadprivate variables.
23320623d748SDimitry Andric     if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
23330623d748SDimitry Andric       return EmitThreadPrivateVarDeclLValue(
23340623d748SDimitry Andric           *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
23350623d748SDimitry Andric           E->getExprLoc());
23360623d748SDimitry Andric     }
23370623d748SDimitry Andric 
23380623d748SDimitry Andric     // Drill into block byref variables.
23390623d748SDimitry Andric     bool isBlockByref = VD->hasAttr<BlocksAttr>();
23400623d748SDimitry Andric     if (isBlockByref) {
23410623d748SDimitry Andric       addr = emitBlockByrefAddress(addr, VD);
23420623d748SDimitry Andric     }
23430623d748SDimitry Andric 
23440623d748SDimitry Andric     // Drill into reference types.
23450623d748SDimitry Andric     LValue LV;
23460623d748SDimitry Andric     if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
23470623d748SDimitry Andric       LV = EmitLoadOfReferenceLValue(addr, RefTy);
23480623d748SDimitry Andric     } else {
2349d8866befSDimitry Andric       LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2350d8866befSDimitry Andric       LV = MakeAddrLValue(addr, T, BaseInfo);
2351dff0c46cSDimitry Andric     }
2352e580952dSDimitry Andric 
2353139f7f9bSDimitry Andric     bool isLocalStorage = VD->hasLocalStorage();
2354139f7f9bSDimitry Andric 
2355139f7f9bSDimitry Andric     bool NonGCable = isLocalStorage &&
2356139f7f9bSDimitry Andric                      !VD->getType()->isReferenceType() &&
23570623d748SDimitry Andric                      !isBlockByref;
2358e580952dSDimitry Andric     if (NonGCable) {
2359e580952dSDimitry Andric       LV.getQuals().removeObjCGCAttr();
2360e580952dSDimitry Andric       LV.setNonGC(true);
2361e580952dSDimitry Andric     }
2362139f7f9bSDimitry Andric 
2363139f7f9bSDimitry Andric     bool isImpreciseLifetime =
2364139f7f9bSDimitry Andric       (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2365139f7f9bSDimitry Andric     if (isImpreciseLifetime)
2366139f7f9bSDimitry Andric       LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2367f22ef01cSRoman Divacky     setObjCGCLValueClass(getContext(), E, LV);
2368f22ef01cSRoman Divacky     return LV;
2369f22ef01cSRoman Divacky   }
2370f22ef01cSRoman Divacky 
237159d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2372f785676fSDimitry Andric     return EmitFunctionDeclLValue(*this, E, FD);
2373f22ef01cSRoman Divacky 
237444290647SDimitry Andric   // FIXME: While we're emitting a binding from an enclosing scope, all other
237544290647SDimitry Andric   // DeclRefExprs we see should be implicitly treated as if they also refer to
237644290647SDimitry Andric   // an enclosing scope.
237744290647SDimitry Andric   if (const auto *BD = dyn_cast<BindingDecl>(ND))
237844290647SDimitry Andric     return EmitLValue(BD->getBinding());
237944290647SDimitry Andric 
23806122f3e6SDimitry Andric   llvm_unreachable("Unhandled DeclRefExpr");
2381f22ef01cSRoman Divacky }
2382f22ef01cSRoman Divacky 
2383f22ef01cSRoman Divacky LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2384f22ef01cSRoman Divacky   // __extension__ doesn't affect lvalue-ness.
2385e580952dSDimitry Andric   if (E->getOpcode() == UO_Extension)
2386f22ef01cSRoman Divacky     return EmitLValue(E->getSubExpr());
2387f22ef01cSRoman Divacky 
2388f22ef01cSRoman Divacky   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2389f22ef01cSRoman Divacky   switch (E->getOpcode()) {
23906122f3e6SDimitry Andric   default: llvm_unreachable("Unknown unary operator lvalue!");
2391e580952dSDimitry Andric   case UO_Deref: {
2392f22ef01cSRoman Divacky     QualType T = E->getSubExpr()->getType()->getPointeeType();
2393f22ef01cSRoman Divacky     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2394f22ef01cSRoman Divacky 
2395d8866befSDimitry Andric     LValueBaseInfo BaseInfo;
2396d8866befSDimitry Andric     Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2397d8866befSDimitry Andric     LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
2398e580952dSDimitry Andric     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2399f22ef01cSRoman Divacky 
2400f22ef01cSRoman Divacky     // We should not generate __weak write barrier on indirect reference
2401f22ef01cSRoman Divacky     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2402f22ef01cSRoman Divacky     // But, we continue to generate __strong write barrier on indirect write
2403f22ef01cSRoman Divacky     // into a pointer to object.
24043861d79fSDimitry Andric     if (getLangOpts().ObjC1 &&
24053861d79fSDimitry Andric         getLangOpts().getGC() != LangOptions::NonGC &&
2406f22ef01cSRoman Divacky         LV.isObjCWeak())
2407e580952dSDimitry Andric       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2408f22ef01cSRoman Divacky     return LV;
2409f22ef01cSRoman Divacky   }
2410e580952dSDimitry Andric   case UO_Real:
2411e580952dSDimitry Andric   case UO_Imag: {
2412f22ef01cSRoman Divacky     LValue LV = EmitLValue(E->getSubExpr());
24132754fe60SDimitry Andric     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
24142754fe60SDimitry Andric 
2415dff0c46cSDimitry Andric     // __real is valid on scalars.  This is a faster way of testing that.
2416dff0c46cSDimitry Andric     // __imag can only produce an rvalue on scalars.
2417dff0c46cSDimitry Andric     if (E->getOpcode() == UO_Real &&
24180623d748SDimitry Andric         !LV.getAddress().getElementType()->isStructTy()) {
24192754fe60SDimitry Andric       assert(E->getSubExpr()->getType()->isArithmeticType());
24202754fe60SDimitry Andric       return LV;
24212754fe60SDimitry Andric     }
24222754fe60SDimitry Andric 
2423f41fbc90SDimitry Andric     QualType T = ExprTy->castAs<ComplexType>()->getElementType();
24242754fe60SDimitry Andric 
24250623d748SDimitry Andric     Address Component =
24260623d748SDimitry Andric       (E->getOpcode() == UO_Real
24270623d748SDimitry Andric          ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
24280623d748SDimitry Andric          : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2429d8866befSDimitry Andric     LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
2430f41fbc90SDimitry Andric     ElemLV.getQuals().addQualifiers(LV.getQuals());
2431f41fbc90SDimitry Andric     return ElemLV;
2432f22ef01cSRoman Divacky   }
2433e580952dSDimitry Andric   case UO_PreInc:
2434e580952dSDimitry Andric   case UO_PreDec: {
2435f22ef01cSRoman Divacky     LValue LV = EmitLValue(E->getSubExpr());
2436e580952dSDimitry Andric     bool isInc = E->getOpcode() == UO_PreInc;
2437f22ef01cSRoman Divacky 
2438f22ef01cSRoman Divacky     if (E->getType()->isAnyComplexType())
2439f22ef01cSRoman Divacky       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2440f22ef01cSRoman Divacky     else
2441f22ef01cSRoman Divacky       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2442f22ef01cSRoman Divacky     return LV;
2443f22ef01cSRoman Divacky   }
2444f22ef01cSRoman Divacky   }
2445f22ef01cSRoman Divacky }
2446f22ef01cSRoman Divacky 
2447f22ef01cSRoman Divacky LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2448e580952dSDimitry Andric   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2449d8866befSDimitry Andric                         E->getType(),
2450d8866befSDimitry Andric                         LValueBaseInfo(AlignmentSource::Decl, false));
2451f22ef01cSRoman Divacky }
2452f22ef01cSRoman Divacky 
2453f22ef01cSRoman Divacky LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2454e580952dSDimitry Andric   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2455d8866befSDimitry Andric                         E->getType(),
2456d8866befSDimitry Andric                         LValueBaseInfo(AlignmentSource::Decl, false));
2457f22ef01cSRoman Divacky }
2458f22ef01cSRoman Divacky 
2459e580952dSDimitry Andric LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
246039d628a0SDimitry Andric   auto SL = E->getFunctionName();
246139d628a0SDimitry Andric   assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
24626122f3e6SDimitry Andric   StringRef FnName = CurFn->getName();
2463f22ef01cSRoman Divacky   if (FnName.startswith("\01"))
2464f22ef01cSRoman Divacky     FnName = FnName.substr(1);
246539d628a0SDimitry Andric   StringRef NameItems[] = {
246639d628a0SDimitry Andric       PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
246739d628a0SDimitry Andric   std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2468d8866befSDimitry Andric   LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
246944290647SDimitry Andric   if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
247044290647SDimitry Andric     std::string Name = SL->getString();
247144290647SDimitry Andric     if (!Name.empty()) {
247244290647SDimitry Andric       unsigned Discriminator =
247344290647SDimitry Andric           CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
247444290647SDimitry Andric       if (Discriminator)
247544290647SDimitry Andric         Name += "_" + Twine(Discriminator + 1).str();
247644290647SDimitry Andric       auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2477d8866befSDimitry Andric       return MakeAddrLValue(C, E->getType(), BaseInfo);
247844290647SDimitry Andric     } else {
24790623d748SDimitry Andric       auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2480d8866befSDimitry Andric       return MakeAddrLValue(C, E->getType(), BaseInfo);
2481f22ef01cSRoman Divacky     }
248244290647SDimitry Andric   }
248339d628a0SDimitry Andric   auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2484d8866befSDimitry Andric   return MakeAddrLValue(C, E->getType(), BaseInfo);
2485f22ef01cSRoman Divacky }
2486f22ef01cSRoman Divacky 
24873861d79fSDimitry Andric /// Emit a type description suitable for use by a runtime sanitizer library. The
24883861d79fSDimitry Andric /// format of a type descriptor is
24893861d79fSDimitry Andric ///
24903861d79fSDimitry Andric /// \code
24913861d79fSDimitry Andric ///   { i16 TypeKind, i16 TypeInfo }
24923861d79fSDimitry Andric /// \endcode
24933861d79fSDimitry Andric ///
24943861d79fSDimitry Andric /// followed by an array of i8 containing the type name. TypeKind is 0 for an
24953861d79fSDimitry Andric /// integer, 1 for a floating point value, and -1 for anything else.
24963861d79fSDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2497f785676fSDimitry Andric   // Only emit each type's descriptor once.
249859d1ed5bSDimitry Andric   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2499f785676fSDimitry Andric     return C;
2500f785676fSDimitry Andric 
25013861d79fSDimitry Andric   uint16_t TypeKind = -1;
25023861d79fSDimitry Andric   uint16_t TypeInfo = 0;
2503f22ef01cSRoman Divacky 
25043861d79fSDimitry Andric   if (T->isIntegerType()) {
25053861d79fSDimitry Andric     TypeKind = 0;
25063861d79fSDimitry Andric     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2507139f7f9bSDimitry Andric                (T->isSignedIntegerType() ? 1 : 0);
25083861d79fSDimitry Andric   } else if (T->isFloatingType()) {
25093861d79fSDimitry Andric     TypeKind = 1;
25103861d79fSDimitry Andric     TypeInfo = getContext().getTypeSize(T);
2511f22ef01cSRoman Divacky   }
2512f22ef01cSRoman Divacky 
25133861d79fSDimitry Andric   // Format the type name as if for a diagnostic, including quotes and
25143861d79fSDimitry Andric   // optionally an 'aka'.
2515139f7f9bSDimitry Andric   SmallString<32> Buffer;
25163861d79fSDimitry Andric   CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
25173861d79fSDimitry Andric                                     (intptr_t)T.getAsOpaquePtr(),
251859d1ed5bSDimitry Andric                                     StringRef(), StringRef(), None, Buffer,
251939d628a0SDimitry Andric                                     None);
25203861d79fSDimitry Andric 
25213861d79fSDimitry Andric   llvm::Constant *Components[] = {
25223861d79fSDimitry Andric     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
25233861d79fSDimitry Andric     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
25243861d79fSDimitry Andric   };
25253861d79fSDimitry Andric   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
25263861d79fSDimitry Andric 
252759d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
252859d1ed5bSDimitry Andric       CGM.getModule(), Descriptor->getType(),
252959d1ed5bSDimitry Andric       /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2530e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
253139d628a0SDimitry Andric   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2532f785676fSDimitry Andric 
2533f785676fSDimitry Andric   // Remember the descriptor for this type.
253459d1ed5bSDimitry Andric   CGM.setTypeDescriptorInMap(T, GV);
2535f785676fSDimitry Andric 
25363861d79fSDimitry Andric   return GV;
25373861d79fSDimitry Andric }
25383861d79fSDimitry Andric 
25393861d79fSDimitry Andric llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
25403861d79fSDimitry Andric   llvm::Type *TargetTy = IntPtrTy;
25413861d79fSDimitry Andric 
2542139f7f9bSDimitry Andric   // Floating-point types which fit into intptr_t are bitcast to integers
2543139f7f9bSDimitry Andric   // and then passed directly (after zero-extension, if necessary).
2544139f7f9bSDimitry Andric   if (V->getType()->isFloatingPointTy()) {
2545139f7f9bSDimitry Andric     unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2546139f7f9bSDimitry Andric     if (Bits <= TargetTy->getIntegerBitWidth())
2547139f7f9bSDimitry Andric       V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2548139f7f9bSDimitry Andric                                                          Bits));
2549139f7f9bSDimitry Andric   }
2550139f7f9bSDimitry Andric 
25513861d79fSDimitry Andric   // Integers which fit in intptr_t are zero-extended and passed directly.
25523861d79fSDimitry Andric   if (V->getType()->isIntegerTy() &&
25533861d79fSDimitry Andric       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
25543861d79fSDimitry Andric     return Builder.CreateZExt(V, TargetTy);
25553861d79fSDimitry Andric 
25563861d79fSDimitry Andric   // Pointers are passed directly, everything else is passed by address.
25573861d79fSDimitry Andric   if (!V->getType()->isPointerTy()) {
25580623d748SDimitry Andric     Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
25593861d79fSDimitry Andric     Builder.CreateStore(V, Ptr);
25600623d748SDimitry Andric     V = Ptr.getPointer();
25613861d79fSDimitry Andric   }
25623861d79fSDimitry Andric   return Builder.CreatePtrToInt(V, TargetTy);
25633861d79fSDimitry Andric }
25643861d79fSDimitry Andric 
25653861d79fSDimitry Andric /// \brief Emit a representation of a SourceLocation for passing to a handler
25663861d79fSDimitry Andric /// in a sanitizer runtime library. The format for this data is:
25673861d79fSDimitry Andric /// \code
25683861d79fSDimitry Andric ///   struct SourceLocation {
25693861d79fSDimitry Andric ///     const char *Filename;
25703861d79fSDimitry Andric ///     int32_t Line, Column;
25713861d79fSDimitry Andric ///   };
25723861d79fSDimitry Andric /// \endcode
25733861d79fSDimitry Andric /// For an invalid SourceLocation, the Filename pointer is null.
25743861d79fSDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
257559d1ed5bSDimitry Andric   llvm::Constant *Filename;
257659d1ed5bSDimitry Andric   int Line, Column;
25773861d79fSDimitry Andric 
257859d1ed5bSDimitry Andric   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
257959d1ed5bSDimitry Andric   if (PLoc.isValid()) {
2580e7145dcbSDimitry Andric     StringRef FilenameString = PLoc.getFilename();
2581e7145dcbSDimitry Andric 
2582e7145dcbSDimitry Andric     int PathComponentsToStrip =
2583e7145dcbSDimitry Andric         CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2584e7145dcbSDimitry Andric     if (PathComponentsToStrip < 0) {
2585e7145dcbSDimitry Andric       assert(PathComponentsToStrip != INT_MIN);
2586e7145dcbSDimitry Andric       int PathComponentsToKeep = -PathComponentsToStrip;
2587e7145dcbSDimitry Andric       auto I = llvm::sys::path::rbegin(FilenameString);
2588e7145dcbSDimitry Andric       auto E = llvm::sys::path::rend(FilenameString);
2589e7145dcbSDimitry Andric       while (I != E && --PathComponentsToKeep)
2590e7145dcbSDimitry Andric         ++I;
2591e7145dcbSDimitry Andric 
2592e7145dcbSDimitry Andric       FilenameString = FilenameString.substr(I - E);
2593e7145dcbSDimitry Andric     } else if (PathComponentsToStrip > 0) {
2594e7145dcbSDimitry Andric       auto I = llvm::sys::path::begin(FilenameString);
2595e7145dcbSDimitry Andric       auto E = llvm::sys::path::end(FilenameString);
2596e7145dcbSDimitry Andric       while (I != E && PathComponentsToStrip--)
2597e7145dcbSDimitry Andric         ++I;
2598e7145dcbSDimitry Andric 
2599e7145dcbSDimitry Andric       if (I != E)
2600e7145dcbSDimitry Andric         FilenameString =
2601e7145dcbSDimitry Andric             FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2602e7145dcbSDimitry Andric       else
2603e7145dcbSDimitry Andric         FilenameString = llvm::sys::path::filename(FilenameString);
2604e7145dcbSDimitry Andric     }
2605e7145dcbSDimitry Andric 
2606e7145dcbSDimitry Andric     auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
26070623d748SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
26080623d748SDimitry Andric                           cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
26090623d748SDimitry Andric     Filename = FilenameGV.getPointer();
261059d1ed5bSDimitry Andric     Line = PLoc.getLine();
261159d1ed5bSDimitry Andric     Column = PLoc.getColumn();
261259d1ed5bSDimitry Andric   } else {
261359d1ed5bSDimitry Andric     Filename = llvm::Constant::getNullValue(Int8PtrTy);
261459d1ed5bSDimitry Andric     Line = Column = 0;
261559d1ed5bSDimitry Andric   }
261659d1ed5bSDimitry Andric 
261759d1ed5bSDimitry Andric   llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
261859d1ed5bSDimitry Andric                             Builder.getInt32(Column)};
26193861d79fSDimitry Andric 
26203861d79fSDimitry Andric   return llvm::ConstantStruct::getAnon(Data);
26213861d79fSDimitry Andric }
26223861d79fSDimitry Andric 
262339d628a0SDimitry Andric namespace {
262439d628a0SDimitry Andric /// \brief Specify under what conditions this check can be recovered
262539d628a0SDimitry Andric enum class CheckRecoverableKind {
262639d628a0SDimitry Andric   /// Always terminate program execution if this check fails.
262739d628a0SDimitry Andric   Unrecoverable,
262839d628a0SDimitry Andric   /// Check supports recovering, runtime has both fatal (noreturn) and
262939d628a0SDimitry Andric   /// non-fatal handlers for this check.
263039d628a0SDimitry Andric   Recoverable,
263139d628a0SDimitry Andric   /// Runtime conditionally aborts, always need to support recovery.
263239d628a0SDimitry Andric   AlwaysRecoverable
263339d628a0SDimitry Andric };
263439d628a0SDimitry Andric }
263539d628a0SDimitry Andric 
263633956c43SDimitry Andric static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
263733956c43SDimitry Andric   assert(llvm::countPopulation(Kind) == 1);
263839d628a0SDimitry Andric   switch (Kind) {
263939d628a0SDimitry Andric   case SanitizerKind::Vptr:
264039d628a0SDimitry Andric     return CheckRecoverableKind::AlwaysRecoverable;
264139d628a0SDimitry Andric   case SanitizerKind::Return:
264239d628a0SDimitry Andric   case SanitizerKind::Unreachable:
264339d628a0SDimitry Andric     return CheckRecoverableKind::Unrecoverable;
264439d628a0SDimitry Andric   default:
264539d628a0SDimitry Andric     return CheckRecoverableKind::Recoverable;
264639d628a0SDimitry Andric   }
264739d628a0SDimitry Andric }
264839d628a0SDimitry Andric 
264944290647SDimitry Andric namespace {
265044290647SDimitry Andric struct SanitizerHandlerInfo {
265144290647SDimitry Andric   char const *const Name;
265244290647SDimitry Andric   unsigned Version;
265344290647SDimitry Andric };
265444290647SDimitry Andric }
265544290647SDimitry Andric 
265644290647SDimitry Andric const SanitizerHandlerInfo SanitizerHandlers[] = {
265744290647SDimitry Andric #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
265844290647SDimitry Andric     LIST_SANITIZER_CHECKS
265944290647SDimitry Andric #undef SANITIZER_CHECK
266044290647SDimitry Andric };
266144290647SDimitry Andric 
266239d628a0SDimitry Andric static void emitCheckHandlerCall(CodeGenFunction &CGF,
266339d628a0SDimitry Andric                                  llvm::FunctionType *FnType,
266439d628a0SDimitry Andric                                  ArrayRef<llvm::Value *> FnArgs,
266544290647SDimitry Andric                                  SanitizerHandler CheckHandler,
266639d628a0SDimitry Andric                                  CheckRecoverableKind RecoverKind, bool IsFatal,
266739d628a0SDimitry Andric                                  llvm::BasicBlock *ContBB) {
266839d628a0SDimitry Andric   assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
266939d628a0SDimitry Andric   bool NeedsAbortSuffix =
267039d628a0SDimitry Andric       IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
267144290647SDimitry Andric   const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
267244290647SDimitry Andric   const StringRef CheckName = CheckInfo.Name;
267344290647SDimitry Andric   std::string FnName =
267444290647SDimitry Andric       ("__ubsan_handle_" + CheckName +
267544290647SDimitry Andric        (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
267644290647SDimitry Andric        (NeedsAbortSuffix ? "_abort" : ""))
267744290647SDimitry Andric           .str();
267839d628a0SDimitry Andric   bool MayReturn =
267939d628a0SDimitry Andric       !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
268039d628a0SDimitry Andric 
268139d628a0SDimitry Andric   llvm::AttrBuilder B;
268239d628a0SDimitry Andric   if (!MayReturn) {
268339d628a0SDimitry Andric     B.addAttribute(llvm::Attribute::NoReturn)
268439d628a0SDimitry Andric         .addAttribute(llvm::Attribute::NoUnwind);
268539d628a0SDimitry Andric   }
268639d628a0SDimitry Andric   B.addAttribute(llvm::Attribute::UWTable);
268739d628a0SDimitry Andric 
268839d628a0SDimitry Andric   llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
268939d628a0SDimitry Andric       FnType, FnName,
269020e90f04SDimitry Andric       llvm::AttributeList::get(CGF.getLLVMContext(),
269120e90f04SDimitry Andric                                llvm::AttributeList::FunctionIndex, B),
269244290647SDimitry Andric       /*Local=*/true);
269339d628a0SDimitry Andric   llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
269439d628a0SDimitry Andric   if (!MayReturn) {
269539d628a0SDimitry Andric     HandlerCall->setDoesNotReturn();
269639d628a0SDimitry Andric     CGF.Builder.CreateUnreachable();
269739d628a0SDimitry Andric   } else {
269839d628a0SDimitry Andric     CGF.Builder.CreateBr(ContBB);
269939d628a0SDimitry Andric   }
270039d628a0SDimitry Andric }
270139d628a0SDimitry Andric 
270239d628a0SDimitry Andric void CodeGenFunction::EmitCheck(
270333956c43SDimitry Andric     ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
270444290647SDimitry Andric     SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
270539d628a0SDimitry Andric     ArrayRef<llvm::Value *> DynamicArgs) {
270659d1ed5bSDimitry Andric   assert(IsSanitizerScope);
270739d628a0SDimitry Andric   assert(Checked.size() > 0);
270844290647SDimitry Andric   assert(CheckHandler >= 0 &&
270944290647SDimitry Andric          CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
271044290647SDimitry Andric   const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
271139d628a0SDimitry Andric 
271239d628a0SDimitry Andric   llvm::Value *FatalCond = nullptr;
271339d628a0SDimitry Andric   llvm::Value *RecoverableCond = nullptr;
27148f0fd8f6SDimitry Andric   llvm::Value *TrapCond = nullptr;
271539d628a0SDimitry Andric   for (int i = 0, n = Checked.size(); i < n; ++i) {
271639d628a0SDimitry Andric     llvm::Value *Check = Checked[i].first;
27178f0fd8f6SDimitry Andric     // -fsanitize-trap= overrides -fsanitize-recover=.
271839d628a0SDimitry Andric     llvm::Value *&Cond =
27198f0fd8f6SDimitry Andric         CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
27208f0fd8f6SDimitry Andric             ? TrapCond
27218f0fd8f6SDimitry Andric             : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
272239d628a0SDimitry Andric                   ? RecoverableCond
272339d628a0SDimitry Andric                   : FatalCond;
272439d628a0SDimitry Andric     Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
272539d628a0SDimitry Andric   }
272639d628a0SDimitry Andric 
27278f0fd8f6SDimitry Andric   if (TrapCond)
27288f0fd8f6SDimitry Andric     EmitTrapCheck(TrapCond);
27298f0fd8f6SDimitry Andric   if (!FatalCond && !RecoverableCond)
27308f0fd8f6SDimitry Andric     return;
27318f0fd8f6SDimitry Andric 
273239d628a0SDimitry Andric   llvm::Value *JointCond;
273339d628a0SDimitry Andric   if (FatalCond && RecoverableCond)
273439d628a0SDimitry Andric     JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
273539d628a0SDimitry Andric   else
273639d628a0SDimitry Andric     JointCond = FatalCond ? FatalCond : RecoverableCond;
273739d628a0SDimitry Andric   assert(JointCond);
273839d628a0SDimitry Andric 
273939d628a0SDimitry Andric   CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
274039d628a0SDimitry Andric   assert(SanOpts.has(Checked[0].second));
274139d628a0SDimitry Andric #ifndef NDEBUG
274239d628a0SDimitry Andric   for (int i = 1, n = Checked.size(); i < n; ++i) {
274339d628a0SDimitry Andric     assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
274439d628a0SDimitry Andric            "All recoverable kinds in a single check must be same!");
274539d628a0SDimitry Andric     assert(SanOpts.has(Checked[i].second));
274639d628a0SDimitry Andric   }
274739d628a0SDimitry Andric #endif
2748139f7f9bSDimitry Andric 
27493861d79fSDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cont");
275039d628a0SDimitry Andric   llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
275139d628a0SDimitry Andric   llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2752139f7f9bSDimitry Andric   // Give hint that we very much don't expect to execute the handler
2753139f7f9bSDimitry Andric   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2754139f7f9bSDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
2755139f7f9bSDimitry Andric   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2756139f7f9bSDimitry Andric   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
275739d628a0SDimitry Andric   EmitBlock(Handlers);
2758139f7f9bSDimitry Andric 
2759e7145dcbSDimitry Andric   // Handler functions take an i8* pointing to the (handler-specific) static
2760e7145dcbSDimitry Andric   // information block, followed by a sequence of intptr_t arguments
2761e7145dcbSDimitry Andric   // representing operand values.
2762139f7f9bSDimitry Andric   SmallVector<llvm::Value *, 4> Args;
2763139f7f9bSDimitry Andric   SmallVector<llvm::Type *, 4> ArgTypes;
27643861d79fSDimitry Andric   Args.reserve(DynamicArgs.size() + 1);
27653861d79fSDimitry Andric   ArgTypes.reserve(DynamicArgs.size() + 1);
27663861d79fSDimitry Andric 
2767e7145dcbSDimitry Andric   // Emit handler arguments and create handler function type.
2768e7145dcbSDimitry Andric   if (!StaticArgs.empty()) {
2769e7145dcbSDimitry Andric     llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2770e7145dcbSDimitry Andric     auto *InfoPtr =
2771e7145dcbSDimitry Andric         new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2772e7145dcbSDimitry Andric                                  llvm::GlobalVariable::PrivateLinkage, Info);
2773e7145dcbSDimitry Andric     InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2774e7145dcbSDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
27753861d79fSDimitry Andric     Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
27763861d79fSDimitry Andric     ArgTypes.push_back(Int8PtrTy);
2777e7145dcbSDimitry Andric   }
2778e7145dcbSDimitry Andric 
27793861d79fSDimitry Andric   for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
27803861d79fSDimitry Andric     Args.push_back(EmitCheckValue(DynamicArgs[i]));
27813861d79fSDimitry Andric     ArgTypes.push_back(IntPtrTy);
27823861d79fSDimitry Andric   }
27833861d79fSDimitry Andric 
27843861d79fSDimitry Andric   llvm::FunctionType *FnType =
27853861d79fSDimitry Andric     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2786139f7f9bSDimitry Andric 
278739d628a0SDimitry Andric   if (!FatalCond || !RecoverableCond) {
278839d628a0SDimitry Andric     // Simple case: we need to generate a single handler call, either
278939d628a0SDimitry Andric     // fatal, or non-fatal.
279044290647SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
279139d628a0SDimitry Andric                          (FatalCond != nullptr), Cont);
27923861d79fSDimitry Andric   } else {
279339d628a0SDimitry Andric     // Emit two handler calls: first one for set of unrecoverable checks,
279439d628a0SDimitry Andric     // another one for recoverable.
279539d628a0SDimitry Andric     llvm::BasicBlock *NonFatalHandlerBB =
279639d628a0SDimitry Andric         createBasicBlock("non_fatal." + CheckName);
279739d628a0SDimitry Andric     llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
279839d628a0SDimitry Andric     Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
279939d628a0SDimitry Andric     EmitBlock(FatalHandlerBB);
280044290647SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
280139d628a0SDimitry Andric                          NonFatalHandlerBB);
280239d628a0SDimitry Andric     EmitBlock(NonFatalHandlerBB);
280344290647SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
280439d628a0SDimitry Andric                          Cont);
28053861d79fSDimitry Andric   }
28063861d79fSDimitry Andric 
28073861d79fSDimitry Andric   EmitBlock(Cont);
28083861d79fSDimitry Andric }
28093861d79fSDimitry Andric 
2810e7145dcbSDimitry Andric void CodeGenFunction::EmitCfiSlowPathCheck(
2811e7145dcbSDimitry Andric     SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2812e7145dcbSDimitry Andric     llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
28130623d748SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
28140623d748SDimitry Andric 
28150623d748SDimitry Andric   llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
28160623d748SDimitry Andric   llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
28170623d748SDimitry Andric 
28180623d748SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
28190623d748SDimitry Andric   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
28200623d748SDimitry Andric   BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
28210623d748SDimitry Andric 
28220623d748SDimitry Andric   EmitBlock(CheckBB);
28230623d748SDimitry Andric 
2824e7145dcbSDimitry Andric   bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2825e7145dcbSDimitry Andric 
2826e7145dcbSDimitry Andric   llvm::CallInst *CheckCall;
2827e7145dcbSDimitry Andric   if (WithDiag) {
2828e7145dcbSDimitry Andric     llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2829e7145dcbSDimitry Andric     auto *InfoPtr =
2830e7145dcbSDimitry Andric         new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2831e7145dcbSDimitry Andric                                  llvm::GlobalVariable::PrivateLinkage, Info);
2832e7145dcbSDimitry Andric     InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2833e7145dcbSDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2834e7145dcbSDimitry Andric 
2835e7145dcbSDimitry Andric     llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2836e7145dcbSDimitry Andric         "__cfi_slowpath_diag",
2837e7145dcbSDimitry Andric         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2838e7145dcbSDimitry Andric                                 false));
2839e7145dcbSDimitry Andric     CheckCall = Builder.CreateCall(
2840e7145dcbSDimitry Andric         SlowPathDiagFn,
2841e7145dcbSDimitry Andric         {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2842e7145dcbSDimitry Andric   } else {
28430623d748SDimitry Andric     llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
28440623d748SDimitry Andric         "__cfi_slowpath",
2845e7145dcbSDimitry Andric         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2846e7145dcbSDimitry Andric     CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2847e7145dcbSDimitry Andric   }
2848e7145dcbSDimitry Andric 
28490623d748SDimitry Andric   CheckCall->setDoesNotThrow();
28500623d748SDimitry Andric 
28510623d748SDimitry Andric   EmitBlock(Cont);
28520623d748SDimitry Andric }
28530623d748SDimitry Andric 
285420e90f04SDimitry Andric // Emit a stub for __cfi_check function so that the linker knows about this
285520e90f04SDimitry Andric // symbol in LTO mode.
285620e90f04SDimitry Andric void CodeGenFunction::EmitCfiCheckStub() {
285720e90f04SDimitry Andric   llvm::Module *M = &CGM.getModule();
285820e90f04SDimitry Andric   auto &Ctx = M->getContext();
285920e90f04SDimitry Andric   llvm::Function *F = llvm::Function::Create(
286020e90f04SDimitry Andric       llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
286120e90f04SDimitry Andric       llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
286220e90f04SDimitry Andric   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
286320e90f04SDimitry Andric   // FIXME: consider emitting an intrinsic call like
286420e90f04SDimitry Andric   // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
286520e90f04SDimitry Andric   // which can be lowered in CrossDSOCFI pass to the actual contents of
286620e90f04SDimitry Andric   // __cfi_check. This would allow inlining of __cfi_check calls.
286720e90f04SDimitry Andric   llvm::CallInst::Create(
286820e90f04SDimitry Andric       llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
286920e90f04SDimitry Andric   llvm::ReturnInst::Create(Ctx, nullptr, BB);
287020e90f04SDimitry Andric }
287120e90f04SDimitry Andric 
2872e7145dcbSDimitry Andric // This function is basically a switch over the CFI failure kind, which is
2873e7145dcbSDimitry Andric // extracted from CFICheckFailData (1st function argument). Each case is either
2874e7145dcbSDimitry Andric // llvm.trap or a call to one of the two runtime handlers, based on
2875e7145dcbSDimitry Andric // -fsanitize-trap and -fsanitize-recover settings.  Default case (invalid
2876e7145dcbSDimitry Andric // failure kind) traps, but this should really never happen.  CFICheckFailData
2877e7145dcbSDimitry Andric // can be nullptr if the calling module has -fsanitize-trap behavior for this
2878e7145dcbSDimitry Andric // check kind; in this case __cfi_check_fail traps as well.
2879e7145dcbSDimitry Andric void CodeGenFunction::EmitCfiCheckFail() {
2880e7145dcbSDimitry Andric   SanitizerScope SanScope(this);
2881e7145dcbSDimitry Andric   FunctionArgList Args;
2882db17bf38SDimitry Andric   ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2883db17bf38SDimitry Andric                             ImplicitParamDecl::Other);
2884db17bf38SDimitry Andric   ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2885db17bf38SDimitry Andric                             ImplicitParamDecl::Other);
2886e7145dcbSDimitry Andric   Args.push_back(&ArgData);
2887e7145dcbSDimitry Andric   Args.push_back(&ArgAddr);
2888e7145dcbSDimitry Andric 
2889e7145dcbSDimitry Andric   const CGFunctionInfo &FI =
2890e7145dcbSDimitry Andric     CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2891e7145dcbSDimitry Andric 
2892e7145dcbSDimitry Andric   llvm::Function *F = llvm::Function::Create(
2893e7145dcbSDimitry Andric       llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2894e7145dcbSDimitry Andric       llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2895e7145dcbSDimitry Andric   F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2896e7145dcbSDimitry Andric 
2897e7145dcbSDimitry Andric   StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2898e7145dcbSDimitry Andric                 SourceLocation());
2899e7145dcbSDimitry Andric 
2900e7145dcbSDimitry Andric   llvm::Value *Data =
2901e7145dcbSDimitry Andric       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2902e7145dcbSDimitry Andric                        CGM.getContext().VoidPtrTy, ArgData.getLocation());
2903e7145dcbSDimitry Andric   llvm::Value *Addr =
2904e7145dcbSDimitry Andric       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2905e7145dcbSDimitry Andric                        CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2906e7145dcbSDimitry Andric 
2907e7145dcbSDimitry Andric   // Data == nullptr means the calling module has trap behaviour for this check.
2908e7145dcbSDimitry Andric   llvm::Value *DataIsNotNullPtr =
2909e7145dcbSDimitry Andric       Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2910e7145dcbSDimitry Andric   EmitTrapCheck(DataIsNotNullPtr);
2911e7145dcbSDimitry Andric 
2912e7145dcbSDimitry Andric   llvm::StructType *SourceLocationTy =
29135517e702SDimitry Andric       llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
2914e7145dcbSDimitry Andric   llvm::StructType *CfiCheckFailDataTy =
29155517e702SDimitry Andric       llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
2916e7145dcbSDimitry Andric 
2917e7145dcbSDimitry Andric   llvm::Value *V = Builder.CreateConstGEP2_32(
2918e7145dcbSDimitry Andric       CfiCheckFailDataTy,
2919e7145dcbSDimitry Andric       Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2920e7145dcbSDimitry Andric       0);
2921e7145dcbSDimitry Andric   Address CheckKindAddr(V, getIntAlign());
2922e7145dcbSDimitry Andric   llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2923e7145dcbSDimitry Andric 
2924e7145dcbSDimitry Andric   llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2925e7145dcbSDimitry Andric       CGM.getLLVMContext(),
2926e7145dcbSDimitry Andric       llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2927e7145dcbSDimitry Andric   llvm::Value *ValidVtable = Builder.CreateZExt(
2928e7145dcbSDimitry Andric       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2929e7145dcbSDimitry Andric                          {Addr, AllVtables}),
2930e7145dcbSDimitry Andric       IntPtrTy);
2931e7145dcbSDimitry Andric 
2932e7145dcbSDimitry Andric   const std::pair<int, SanitizerMask> CheckKinds[] = {
2933e7145dcbSDimitry Andric       {CFITCK_VCall, SanitizerKind::CFIVCall},
2934e7145dcbSDimitry Andric       {CFITCK_NVCall, SanitizerKind::CFINVCall},
2935e7145dcbSDimitry Andric       {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2936e7145dcbSDimitry Andric       {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2937e7145dcbSDimitry Andric       {CFITCK_ICall, SanitizerKind::CFIICall}};
2938e7145dcbSDimitry Andric 
2939e7145dcbSDimitry Andric   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2940e7145dcbSDimitry Andric   for (auto CheckKindMaskPair : CheckKinds) {
2941e7145dcbSDimitry Andric     int Kind = CheckKindMaskPair.first;
2942e7145dcbSDimitry Andric     SanitizerMask Mask = CheckKindMaskPair.second;
2943e7145dcbSDimitry Andric     llvm::Value *Cond =
2944e7145dcbSDimitry Andric         Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2945e7145dcbSDimitry Andric     if (CGM.getLangOpts().Sanitize.has(Mask))
294644290647SDimitry Andric       EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
2947e7145dcbSDimitry Andric                 {Data, Addr, ValidVtable});
2948e7145dcbSDimitry Andric     else
2949e7145dcbSDimitry Andric       EmitTrapCheck(Cond);
2950e7145dcbSDimitry Andric   }
2951e7145dcbSDimitry Andric 
2952e7145dcbSDimitry Andric   FinishFunction();
2953e7145dcbSDimitry Andric   // The only reference to this function will be created during LTO link.
2954e7145dcbSDimitry Andric   // Make sure it survives until then.
2955e7145dcbSDimitry Andric   CGM.addUsedGlobal(F);
2956e7145dcbSDimitry Andric }
2957e7145dcbSDimitry Andric 
2958139f7f9bSDimitry Andric void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
29593861d79fSDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cont");
29603861d79fSDimitry Andric 
29613861d79fSDimitry Andric   // If we're optimizing, collapse all calls to trap down to just one per
29623861d79fSDimitry Andric   // function to save on code size.
29633861d79fSDimitry Andric   if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
29643861d79fSDimitry Andric     TrapBB = createBasicBlock("trap");
29653861d79fSDimitry Andric     Builder.CreateCondBr(Checked, Cont, TrapBB);
29663861d79fSDimitry Andric     EmitBlock(TrapBB);
29673dac3a9bSDimitry Andric     llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2968f22ef01cSRoman Divacky     TrapCall->setDoesNotReturn();
2969f22ef01cSRoman Divacky     TrapCall->setDoesNotThrow();
2970f22ef01cSRoman Divacky     Builder.CreateUnreachable();
29713861d79fSDimitry Andric   } else {
29723861d79fSDimitry Andric     Builder.CreateCondBr(Checked, Cont, TrapBB);
29733861d79fSDimitry Andric   }
2974f22ef01cSRoman Divacky 
2975f22ef01cSRoman Divacky   EmitBlock(Cont);
2976f22ef01cSRoman Divacky }
2977f22ef01cSRoman Divacky 
29783dac3a9bSDimitry Andric llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
2979875ed548SDimitry Andric   llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
29803dac3a9bSDimitry Andric 
298144290647SDimitry Andric   if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
298244290647SDimitry Andric     auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
29833dac3a9bSDimitry Andric                                   CGM.getCodeGenOpts().TrapFuncName);
298420e90f04SDimitry Andric     TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
298544290647SDimitry Andric   }
29863dac3a9bSDimitry Andric 
29873dac3a9bSDimitry Andric   return TrapCall;
29883dac3a9bSDimitry Andric }
29893dac3a9bSDimitry Andric 
29900623d748SDimitry Andric Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2991d8866befSDimitry Andric                                                  LValueBaseInfo *BaseInfo) {
29920623d748SDimitry Andric   assert(E->getType()->isArrayType() &&
29930623d748SDimitry Andric          "Array to pointer decay must have array source type!");
29940623d748SDimitry Andric 
29950623d748SDimitry Andric   // Expressions of array type can't be bitfields or vector elements.
29960623d748SDimitry Andric   LValue LV = EmitLValue(E);
29970623d748SDimitry Andric   Address Addr = LV.getAddress();
2998d8866befSDimitry Andric   if (BaseInfo) *BaseInfo = LV.getBaseInfo();
29990623d748SDimitry Andric 
30000623d748SDimitry Andric   // If the array type was an incomplete type, we need to make sure
30010623d748SDimitry Andric   // the decay ends up being the right type.
30020623d748SDimitry Andric   llvm::Type *NewTy = ConvertType(E->getType());
30030623d748SDimitry Andric   Addr = Builder.CreateElementBitCast(Addr, NewTy);
30040623d748SDimitry Andric 
30050623d748SDimitry Andric   // Note that VLA pointers are always decayed, so we don't need to do
30060623d748SDimitry Andric   // anything here.
30070623d748SDimitry Andric   if (!E->getType()->isVariableArrayType()) {
30080623d748SDimitry Andric     assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
30090623d748SDimitry Andric            "Expected pointer to array");
30100623d748SDimitry Andric     Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
30110623d748SDimitry Andric   }
30120623d748SDimitry Andric 
30130623d748SDimitry Andric   QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
30140623d748SDimitry Andric   return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
30150623d748SDimitry Andric }
30160623d748SDimitry Andric 
3017ffd1746dSEd Schouten /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3018ffd1746dSEd Schouten /// array to pointer, return the array subexpression.
3019ffd1746dSEd Schouten static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3020ffd1746dSEd Schouten   // If this isn't just an array->pointer decay, bail out.
302159d1ed5bSDimitry Andric   const auto *CE = dyn_cast<CastExpr>(E);
302259d1ed5bSDimitry Andric   if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
302359d1ed5bSDimitry Andric     return nullptr;
3024ffd1746dSEd Schouten 
3025ffd1746dSEd Schouten   // If this is a decay from variable width array, bail out.
3026ffd1746dSEd Schouten   const Expr *SubExpr = CE->getSubExpr();
3027ffd1746dSEd Schouten   if (SubExpr->getType()->isVariableArrayType())
302859d1ed5bSDimitry Andric     return nullptr;
3029ffd1746dSEd Schouten 
3030ffd1746dSEd Schouten   return SubExpr;
3031ffd1746dSEd Schouten }
3032ffd1746dSEd Schouten 
30330623d748SDimitry Andric static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
30340623d748SDimitry Andric                                           llvm::Value *ptr,
30350623d748SDimitry Andric                                           ArrayRef<llvm::Value*> indices,
30360623d748SDimitry Andric                                           bool inbounds,
303724d58133SDimitry Andric                                           bool signedIndices,
3038f9448bf3SDimitry Andric                                           SourceLocation loc,
30390623d748SDimitry Andric                                     const llvm::Twine &name = "arrayidx") {
30400623d748SDimitry Andric   if (inbounds) {
304124d58133SDimitry Andric     return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices, loc, name);
30420623d748SDimitry Andric   } else {
30430623d748SDimitry Andric     return CGF.Builder.CreateGEP(ptr, indices, name);
30440623d748SDimitry Andric   }
30450623d748SDimitry Andric }
30460623d748SDimitry Andric 
30470623d748SDimitry Andric static CharUnits getArrayElementAlign(CharUnits arrayAlign,
30480623d748SDimitry Andric                                       llvm::Value *idx,
30490623d748SDimitry Andric                                       CharUnits eltSize) {
30500623d748SDimitry Andric   // If we have a constant index, we can use the exact offset of the
30510623d748SDimitry Andric   // element we're accessing.
30520623d748SDimitry Andric   if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
30530623d748SDimitry Andric     CharUnits offset = constantIdx->getZExtValue() * eltSize;
30540623d748SDimitry Andric     return arrayAlign.alignmentAtOffset(offset);
30550623d748SDimitry Andric 
30560623d748SDimitry Andric   // Otherwise, use the worst-case alignment for any element.
30570623d748SDimitry Andric   } else {
30580623d748SDimitry Andric     return arrayAlign.alignmentOfArrayElement(eltSize);
30590623d748SDimitry Andric   }
30600623d748SDimitry Andric }
30610623d748SDimitry Andric 
30620623d748SDimitry Andric static QualType getFixedSizeElementType(const ASTContext &ctx,
30630623d748SDimitry Andric                                         const VariableArrayType *vla) {
30640623d748SDimitry Andric   QualType eltType;
30650623d748SDimitry Andric   do {
30660623d748SDimitry Andric     eltType = vla->getElementType();
30670623d748SDimitry Andric   } while ((vla = ctx.getAsVariableArrayType(eltType)));
30680623d748SDimitry Andric   return eltType;
30690623d748SDimitry Andric }
30700623d748SDimitry Andric 
30710623d748SDimitry Andric static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
30720623d748SDimitry Andric                                      ArrayRef<llvm::Value *> indices,
30730623d748SDimitry Andric                                      QualType eltType, bool inbounds,
307424d58133SDimitry Andric                                      bool signedIndices, SourceLocation loc,
30750623d748SDimitry Andric                                      const llvm::Twine &name = "arrayidx") {
30760623d748SDimitry Andric   // All the indices except that last must be zero.
30770623d748SDimitry Andric #ifndef NDEBUG
30780623d748SDimitry Andric   for (auto idx : indices.drop_back())
30790623d748SDimitry Andric     assert(isa<llvm::ConstantInt>(idx) &&
30800623d748SDimitry Andric            cast<llvm::ConstantInt>(idx)->isZero());
30810623d748SDimitry Andric #endif
30820623d748SDimitry Andric 
30830623d748SDimitry Andric   // Determine the element size of the statically-sized base.  This is
30840623d748SDimitry Andric   // the thing that the indices are expressed in terms of.
30850623d748SDimitry Andric   if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
30860623d748SDimitry Andric     eltType = getFixedSizeElementType(CGF.getContext(), vla);
30870623d748SDimitry Andric   }
30880623d748SDimitry Andric 
30890623d748SDimitry Andric   // We can use that to compute the best alignment of the element.
30900623d748SDimitry Andric   CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
30910623d748SDimitry Andric   CharUnits eltAlign =
30920623d748SDimitry Andric     getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
30930623d748SDimitry Andric 
309424d58133SDimitry Andric   llvm::Value *eltPtr = emitArraySubscriptGEP(
309524d58133SDimitry Andric       CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
30960623d748SDimitry Andric   return Address(eltPtr, eltAlign);
30970623d748SDimitry Andric }
30980623d748SDimitry Andric 
3099139f7f9bSDimitry Andric LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3100139f7f9bSDimitry Andric                                                bool Accessed) {
310144290647SDimitry Andric   // The index must always be an integer, which is not an aggregate.  Emit it
310244290647SDimitry Andric   // in lexical order (this complexity is, sadly, required by C++17).
310344290647SDimitry Andric   llvm::Value *IdxPre =
310444290647SDimitry Andric       (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
310524d58133SDimitry Andric   bool SignedIndices = false;
310644290647SDimitry Andric   auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
310744290647SDimitry Andric     auto *Idx = IdxPre;
310844290647SDimitry Andric     if (E->getLHS() != E->getIdx()) {
310944290647SDimitry Andric       assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
311044290647SDimitry Andric       Idx = EmitScalarExpr(E->getIdx());
311144290647SDimitry Andric     }
311244290647SDimitry Andric 
3113f22ef01cSRoman Divacky     QualType IdxTy = E->getIdx()->getType();
3114bd5abe19SDimitry Andric     bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
311524d58133SDimitry Andric     SignedIndices |= IdxSigned;
3116f22ef01cSRoman Divacky 
311739d628a0SDimitry Andric     if (SanOpts.has(SanitizerKind::ArrayBounds))
3118139f7f9bSDimitry Andric       EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3119139f7f9bSDimitry Andric 
312044290647SDimitry Andric     // Extend or truncate the index type to 32 or 64-bits.
312144290647SDimitry Andric     if (Promote && Idx->getType() != IntPtrTy)
312244290647SDimitry Andric       Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
312344290647SDimitry Andric 
312444290647SDimitry Andric     return Idx;
312544290647SDimitry Andric   };
312644290647SDimitry Andric   IdxPre = nullptr;
312744290647SDimitry Andric 
3128f22ef01cSRoman Divacky   // If the base is a vector type, then we are forming a vector element lvalue
3129f22ef01cSRoman Divacky   // with this subscript.
313039d628a0SDimitry Andric   if (E->getBase()->getType()->isVectorType() &&
313139d628a0SDimitry Andric       !isa<ExtVectorElementExpr>(E->getBase())) {
3132f22ef01cSRoman Divacky     // Emit the vector as an lvalue to get its address.
3133f22ef01cSRoman Divacky     LValue LHS = EmitLValue(E->getBase());
313444290647SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3135f22ef01cSRoman Divacky     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3136f22ef01cSRoman Divacky     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
31370623d748SDimitry Andric                                  E->getBase()->getType(),
3138d8866befSDimitry Andric                                  LHS.getBaseInfo());
3139f22ef01cSRoman Divacky   }
3140f22ef01cSRoman Divacky 
31410623d748SDimitry Andric   // All the other cases basically behave like simple offsetting.
31420623d748SDimitry Andric 
31430623d748SDimitry Andric   // Handle the extvector case we ignored above.
314439d628a0SDimitry Andric   if (isa<ExtVectorElementExpr>(E->getBase())) {
314539d628a0SDimitry Andric     LValue LV = EmitLValue(E->getBase());
314644290647SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
31470623d748SDimitry Andric     Address Addr = EmitExtVectorElementLValue(LV);
31480623d748SDimitry Andric 
31490623d748SDimitry Andric     QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3150f9448bf3SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
315124d58133SDimitry Andric                                  SignedIndices, E->getExprLoc());
3152d8866befSDimitry Andric     return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
315339d628a0SDimitry Andric   }
31540623d748SDimitry Andric 
3155d8866befSDimitry Andric   LValueBaseInfo BaseInfo;
31560623d748SDimitry Andric   Address Addr = Address::invalid();
31570623d748SDimitry Andric   if (const VariableArrayType *vla =
3158f22ef01cSRoman Divacky            getContext().getAsVariableArrayType(E->getType())) {
315917a519f9SDimitry Andric     // The base must be a pointer, which is not an aggregate.  Emit
316017a519f9SDimitry Andric     // it.  It needs to be emitted first in case it's what captures
316117a519f9SDimitry Andric     // the VLA bounds.
3162d8866befSDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
316344290647SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3164f22ef01cSRoman Divacky 
316517a519f9SDimitry Andric     // The element count here is the total number of non-VLA elements.
316617a519f9SDimitry Andric     llvm::Value *numElements = getVLASize(vla).first;
3167f22ef01cSRoman Divacky 
316817a519f9SDimitry Andric     // Effectively, the multiply by the VLA size is part of the GEP.
316917a519f9SDimitry Andric     // GEP indexes are signed, and scaling an index isn't permitted to
317017a519f9SDimitry Andric     // signed-overflow, so we use the same semantics for our explicit
317117a519f9SDimitry Andric     // multiply.  We suppress this if overflow is not undefined behavior.
3172dff0c46cSDimitry Andric     if (getLangOpts().isSignedOverflowDefined()) {
317317a519f9SDimitry Andric       Idx = Builder.CreateMul(Idx, numElements);
317417a519f9SDimitry Andric     } else {
317517a519f9SDimitry Andric       Idx = Builder.CreateNSWMul(Idx, numElements);
317617a519f9SDimitry Andric     }
31770623d748SDimitry Andric 
31780623d748SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3179f9448bf3SDimitry Andric                                  !getLangOpts().isSignedOverflowDefined(),
318024d58133SDimitry Andric                                  SignedIndices, E->getExprLoc());
31810623d748SDimitry Andric 
3182ffd1746dSEd Schouten   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3183ffd1746dSEd Schouten     // Indexing over an interface, as in "NSString *P; P[4];"
3184f22ef01cSRoman Divacky 
31850623d748SDimitry Andric     // Emit the base pointer.
3186d8866befSDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
318744290647SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
318844290647SDimitry Andric 
318944290647SDimitry Andric     CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
319044290647SDimitry Andric     llvm::Value *InterfaceSizeVal =
319144290647SDimitry Andric         llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
319244290647SDimitry Andric 
319344290647SDimitry Andric     llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
31940623d748SDimitry Andric 
31950623d748SDimitry Andric     // We don't necessarily build correct LLVM struct types for ObjC
31960623d748SDimitry Andric     // interfaces, so we can't rely on GEP to do this scaling
31970623d748SDimitry Andric     // correctly, so we need to cast to i8*.  FIXME: is this actually
31980623d748SDimitry Andric     // true?  A lot of other things in the fragile ABI would break...
31990623d748SDimitry Andric     llvm::Type *OrigBaseTy = Addr.getType();
32000623d748SDimitry Andric     Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
32010623d748SDimitry Andric 
32020623d748SDimitry Andric     // Do the GEP.
32030623d748SDimitry Andric     CharUnits EltAlign =
32040623d748SDimitry Andric       getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
320524d58133SDimitry Andric     llvm::Value *EltPtr =
320624d58133SDimitry Andric         emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
320724d58133SDimitry Andric                               SignedIndices, E->getExprLoc());
32080623d748SDimitry Andric     Addr = Address(EltPtr, EltAlign);
32090623d748SDimitry Andric 
32100623d748SDimitry Andric     // Cast back.
32110623d748SDimitry Andric     Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3212ffd1746dSEd Schouten   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3213ffd1746dSEd Schouten     // If this is A[i] where A is an array, the frontend will have decayed the
3214ffd1746dSEd Schouten     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
3215ffd1746dSEd Schouten     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3216ffd1746dSEd Schouten     // "gep x, i" here.  Emit one "gep A, 0, i".
3217ffd1746dSEd Schouten     assert(Array->getType()->isArrayType() &&
3218ffd1746dSEd Schouten            "Array to pointer decay must have array source type!");
3219139f7f9bSDimitry Andric     LValue ArrayLV;
3220139f7f9bSDimitry Andric     // For simple multidimensional array indexing, set the 'accessed' flag for
3221139f7f9bSDimitry Andric     // better bounds-checking of the base expression.
322259d1ed5bSDimitry Andric     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3223139f7f9bSDimitry Andric       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3224139f7f9bSDimitry Andric     else
3225139f7f9bSDimitry Andric       ArrayLV = EmitLValue(Array);
322644290647SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3227ffd1746dSEd Schouten 
32283b0f4066SDimitry Andric     // Propagate the alignment from the array itself to the result.
322924d58133SDimitry Andric     Addr = emitArraySubscriptGEP(
323024d58133SDimitry Andric         *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
323124d58133SDimitry Andric         E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3232f9448bf3SDimitry Andric         E->getExprLoc());
3233d8866befSDimitry Andric     BaseInfo = ArrayLV.getBaseInfo();
3234f22ef01cSRoman Divacky   } else {
32350623d748SDimitry Andric     // The base must be a pointer; emit it with an estimate of its alignment.
3236d8866befSDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
323744290647SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
32380623d748SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3239f9448bf3SDimitry Andric                                  !getLangOpts().isSignedOverflowDefined(),
324024d58133SDimitry Andric                                  SignedIndices, E->getExprLoc());
3241f22ef01cSRoman Divacky   }
3242f22ef01cSRoman Divacky 
3243d8866befSDimitry Andric   LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
3244f22ef01cSRoman Divacky 
32450623d748SDimitry Andric   // TODO: Preserve/extend path TBAA metadata?
3246f22ef01cSRoman Divacky 
32473861d79fSDimitry Andric   if (getLangOpts().ObjC1 &&
32483861d79fSDimitry Andric       getLangOpts().getGC() != LangOptions::NonGC) {
3249e580952dSDimitry Andric     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3250f22ef01cSRoman Divacky     setObjCGCLValueClass(getContext(), E, LV);
3251f22ef01cSRoman Divacky   }
3252f22ef01cSRoman Divacky   return LV;
3253f22ef01cSRoman Divacky }
3254f22ef01cSRoman Divacky 
3255e7145dcbSDimitry Andric static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3256d8866befSDimitry Andric                                        LValueBaseInfo &BaseInfo,
3257e7145dcbSDimitry Andric                                        QualType BaseTy, QualType ElTy,
3258e7145dcbSDimitry Andric                                        bool IsLowerBound) {
3259e7145dcbSDimitry Andric   LValue BaseLVal;
3260e7145dcbSDimitry Andric   if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3261e7145dcbSDimitry Andric     BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3262e7145dcbSDimitry Andric     if (BaseTy->isArrayType()) {
3263e7145dcbSDimitry Andric       Address Addr = BaseLVal.getAddress();
3264d8866befSDimitry Andric       BaseInfo = BaseLVal.getBaseInfo();
3265e7145dcbSDimitry Andric 
3266e7145dcbSDimitry Andric       // If the array type was an incomplete type, we need to make sure
3267e7145dcbSDimitry Andric       // the decay ends up being the right type.
3268e7145dcbSDimitry Andric       llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3269e7145dcbSDimitry Andric       Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3270e7145dcbSDimitry Andric 
3271e7145dcbSDimitry Andric       // Note that VLA pointers are always decayed, so we don't need to do
3272e7145dcbSDimitry Andric       // anything here.
3273e7145dcbSDimitry Andric       if (!BaseTy->isVariableArrayType()) {
3274e7145dcbSDimitry Andric         assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3275e7145dcbSDimitry Andric                "Expected pointer to array");
3276e7145dcbSDimitry Andric         Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3277e7145dcbSDimitry Andric                                            "arraydecay");
3278e7145dcbSDimitry Andric       }
3279e7145dcbSDimitry Andric 
3280e7145dcbSDimitry Andric       return CGF.Builder.CreateElementBitCast(Addr,
3281e7145dcbSDimitry Andric                                               CGF.ConvertTypeForMem(ElTy));
3282e7145dcbSDimitry Andric     }
3283d8866befSDimitry Andric     LValueBaseInfo TypeInfo;
3284d8866befSDimitry Andric     CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3285d8866befSDimitry Andric     BaseInfo.mergeForCast(TypeInfo);
3286e7145dcbSDimitry Andric     return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3287e7145dcbSDimitry Andric   }
3288d8866befSDimitry Andric   return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
3289e7145dcbSDimitry Andric }
3290e7145dcbSDimitry Andric 
32910623d748SDimitry Andric LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
32920623d748SDimitry Andric                                                 bool IsLowerBound) {
3293e7145dcbSDimitry Andric   QualType BaseTy;
32940623d748SDimitry Andric   if (auto *ASE =
32950623d748SDimitry Andric           dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3296e7145dcbSDimitry Andric     BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
32970623d748SDimitry Andric   else
3298e7145dcbSDimitry Andric     BaseTy = E->getBase()->getType();
32990623d748SDimitry Andric   QualType ResultExprTy;
33000623d748SDimitry Andric   if (auto *AT = getContext().getAsArrayType(BaseTy))
33010623d748SDimitry Andric     ResultExprTy = AT->getElementType();
33020623d748SDimitry Andric   else
33030623d748SDimitry Andric     ResultExprTy = BaseTy->getPointeeType();
3304e7145dcbSDimitry Andric   llvm::Value *Idx = nullptr;
3305e7145dcbSDimitry Andric   if (IsLowerBound || E->getColonLoc().isInvalid()) {
33060623d748SDimitry Andric     // Requesting lower bound or upper bound, but without provided length and
33070623d748SDimitry Andric     // without ':' symbol for the default length -> length = 1.
33080623d748SDimitry Andric     // Idx = LowerBound ?: 0;
33090623d748SDimitry Andric     if (auto *LowerBound = E->getLowerBound()) {
33100623d748SDimitry Andric       Idx = Builder.CreateIntCast(
33110623d748SDimitry Andric           EmitScalarExpr(LowerBound), IntPtrTy,
33120623d748SDimitry Andric           LowerBound->getType()->hasSignedIntegerRepresentation());
33130623d748SDimitry Andric     } else
33140623d748SDimitry Andric       Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
33150623d748SDimitry Andric   } else {
3316e7145dcbSDimitry Andric     // Try to emit length or lower bound as constant. If this is possible, 1
3317e7145dcbSDimitry Andric     // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3318e7145dcbSDimitry Andric     // IR (LB + Len) - 1.
33190623d748SDimitry Andric     auto &C = CGM.getContext();
33200623d748SDimitry Andric     auto *Length = E->getLength();
33210623d748SDimitry Andric     llvm::APSInt ConstLength;
33220623d748SDimitry Andric     if (Length) {
33230623d748SDimitry Andric       // Idx = LowerBound + Length - 1;
33240623d748SDimitry Andric       if (Length->isIntegerConstantExpr(ConstLength, C)) {
33250623d748SDimitry Andric         ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
33260623d748SDimitry Andric         Length = nullptr;
33270623d748SDimitry Andric       }
33280623d748SDimitry Andric       auto *LowerBound = E->getLowerBound();
33290623d748SDimitry Andric       llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
33300623d748SDimitry Andric       if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
33310623d748SDimitry Andric         ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
33320623d748SDimitry Andric         LowerBound = nullptr;
33330623d748SDimitry Andric       }
33340623d748SDimitry Andric       if (!Length)
33350623d748SDimitry Andric         --ConstLength;
33360623d748SDimitry Andric       else if (!LowerBound)
33370623d748SDimitry Andric         --ConstLowerBound;
3338f22ef01cSRoman Divacky 
33390623d748SDimitry Andric       if (Length || LowerBound) {
33400623d748SDimitry Andric         auto *LowerBoundVal =
33410623d748SDimitry Andric             LowerBound
33420623d748SDimitry Andric                 ? Builder.CreateIntCast(
33430623d748SDimitry Andric                       EmitScalarExpr(LowerBound), IntPtrTy,
33440623d748SDimitry Andric                       LowerBound->getType()->hasSignedIntegerRepresentation())
33450623d748SDimitry Andric                 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
33460623d748SDimitry Andric         auto *LengthVal =
33470623d748SDimitry Andric             Length
33480623d748SDimitry Andric                 ? Builder.CreateIntCast(
33490623d748SDimitry Andric                       EmitScalarExpr(Length), IntPtrTy,
33500623d748SDimitry Andric                       Length->getType()->hasSignedIntegerRepresentation())
33510623d748SDimitry Andric                 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
33520623d748SDimitry Andric         Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
33530623d748SDimitry Andric                                 /*HasNUW=*/false,
33540623d748SDimitry Andric                                 !getLangOpts().isSignedOverflowDefined());
33550623d748SDimitry Andric         if (Length && LowerBound) {
33560623d748SDimitry Andric           Idx = Builder.CreateSub(
33570623d748SDimitry Andric               Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
33580623d748SDimitry Andric               /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
33590623d748SDimitry Andric         }
33600623d748SDimitry Andric       } else
33610623d748SDimitry Andric         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
33620623d748SDimitry Andric     } else {
33630623d748SDimitry Andric       // Idx = ArraySize - 1;
3364e7145dcbSDimitry Andric       QualType ArrayTy = BaseTy->isPointerType()
3365e7145dcbSDimitry Andric                              ? E->getBase()->IgnoreParenImpCasts()->getType()
3366e7145dcbSDimitry Andric                              : BaseTy;
3367e7145dcbSDimitry Andric       if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
33680623d748SDimitry Andric         Length = VAT->getSizeExpr();
33690623d748SDimitry Andric         if (Length->isIntegerConstantExpr(ConstLength, C))
33700623d748SDimitry Andric           Length = nullptr;
33710623d748SDimitry Andric       } else {
3372e7145dcbSDimitry Andric         auto *CAT = C.getAsConstantArrayType(ArrayTy);
33730623d748SDimitry Andric         ConstLength = CAT->getSize();
33740623d748SDimitry Andric       }
33750623d748SDimitry Andric       if (Length) {
33760623d748SDimitry Andric         auto *LengthVal = Builder.CreateIntCast(
33770623d748SDimitry Andric             EmitScalarExpr(Length), IntPtrTy,
33780623d748SDimitry Andric             Length->getType()->hasSignedIntegerRepresentation());
33790623d748SDimitry Andric         Idx = Builder.CreateSub(
33800623d748SDimitry Andric             LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
33810623d748SDimitry Andric             /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
33820623d748SDimitry Andric       } else {
33830623d748SDimitry Andric         ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
33840623d748SDimitry Andric         --ConstLength;
33850623d748SDimitry Andric         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
33860623d748SDimitry Andric       }
33870623d748SDimitry Andric     }
33880623d748SDimitry Andric   }
33890623d748SDimitry Andric   assert(Idx);
33900623d748SDimitry Andric 
3391e7145dcbSDimitry Andric   Address EltPtr = Address::invalid();
3392d8866befSDimitry Andric   LValueBaseInfo BaseInfo;
33930623d748SDimitry Andric   if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3394e7145dcbSDimitry Andric     // The base must be a pointer, which is not an aggregate.  Emit
3395e7145dcbSDimitry Andric     // it.  It needs to be emitted first in case it's what captures
3396e7145dcbSDimitry Andric     // the VLA bounds.
3397e7145dcbSDimitry Andric     Address Base =
3398d8866befSDimitry Andric         emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
3399e7145dcbSDimitry Andric                                 VLA->getElementType(), IsLowerBound);
34000623d748SDimitry Andric     // The element count here is the total number of non-VLA elements.
3401e7145dcbSDimitry Andric     llvm::Value *NumElements = getVLASize(VLA).first;
34020623d748SDimitry Andric 
34030623d748SDimitry Andric     // Effectively, the multiply by the VLA size is part of the GEP.
34040623d748SDimitry Andric     // GEP indexes are signed, and scaling an index isn't permitted to
34050623d748SDimitry Andric     // signed-overflow, so we use the same semantics for our explicit
34060623d748SDimitry Andric     // multiply.  We suppress this if overflow is not undefined behavior.
3407e7145dcbSDimitry Andric     if (getLangOpts().isSignedOverflowDefined())
3408e7145dcbSDimitry Andric       Idx = Builder.CreateMul(Idx, NumElements);
3409e7145dcbSDimitry Andric     else
3410e7145dcbSDimitry Andric       Idx = Builder.CreateNSWMul(Idx, NumElements);
3411e7145dcbSDimitry Andric     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3412f9448bf3SDimitry Andric                                    !getLangOpts().isSignedOverflowDefined(),
341324d58133SDimitry Andric                                    /*SignedIndices=*/false, E->getExprLoc());
3414e7145dcbSDimitry Andric   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3415e7145dcbSDimitry Andric     // If this is A[i] where A is an array, the frontend will have decayed the
3416e7145dcbSDimitry Andric     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
3417e7145dcbSDimitry Andric     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3418e7145dcbSDimitry Andric     // "gep x, i" here.  Emit one "gep A, 0, i".
3419e7145dcbSDimitry Andric     assert(Array->getType()->isArrayType() &&
3420e7145dcbSDimitry Andric            "Array to pointer decay must have array source type!");
3421e7145dcbSDimitry Andric     LValue ArrayLV;
3422e7145dcbSDimitry Andric     // For simple multidimensional array indexing, set the 'accessed' flag for
3423e7145dcbSDimitry Andric     // better bounds-checking of the base expression.
3424e7145dcbSDimitry Andric     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3425e7145dcbSDimitry Andric       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3426e7145dcbSDimitry Andric     else
3427e7145dcbSDimitry Andric       ArrayLV = EmitLValue(Array);
34280623d748SDimitry Andric 
3429e7145dcbSDimitry Andric     // Propagate the alignment from the array itself to the result.
3430e7145dcbSDimitry Andric     EltPtr = emitArraySubscriptGEP(
3431e7145dcbSDimitry Andric         *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3432f9448bf3SDimitry Andric         ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
343324d58133SDimitry Andric         /*SignedIndices=*/false, E->getExprLoc());
3434d8866befSDimitry Andric     BaseInfo = ArrayLV.getBaseInfo();
34350623d748SDimitry Andric   } else {
3436d8866befSDimitry Andric     Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
3437e7145dcbSDimitry Andric                                            BaseTy, ResultExprTy, IsLowerBound);
3438e7145dcbSDimitry Andric     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3439f9448bf3SDimitry Andric                                    !getLangOpts().isSignedOverflowDefined(),
344024d58133SDimitry Andric                                    /*SignedIndices=*/false, E->getExprLoc());
34410623d748SDimitry Andric   }
34420623d748SDimitry Andric 
3443d8866befSDimitry Andric   return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
3444f22ef01cSRoman Divacky }
3445f22ef01cSRoman Divacky 
3446f22ef01cSRoman Divacky LValue CodeGenFunction::
3447f22ef01cSRoman Divacky EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3448f22ef01cSRoman Divacky   // Emit the base vector as an l-value.
3449f22ef01cSRoman Divacky   LValue Base;
3450f22ef01cSRoman Divacky 
3451f22ef01cSRoman Divacky   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3452f22ef01cSRoman Divacky   if (E->isArrow()) {
3453f22ef01cSRoman Divacky     // If it is a pointer to a vector, emit the address and form an lvalue with
3454f22ef01cSRoman Divacky     // it.
3455d8866befSDimitry Andric     LValueBaseInfo BaseInfo;
3456d8866befSDimitry Andric     Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3457f22ef01cSRoman Divacky     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3458d8866befSDimitry Andric     Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
3459e580952dSDimitry Andric     Base.getQuals().removeObjCGCAttr();
34602754fe60SDimitry Andric   } else if (E->getBase()->isGLValue()) {
3461f22ef01cSRoman Divacky     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3462f22ef01cSRoman Divacky     // emit the base as an lvalue.
3463f22ef01cSRoman Divacky     assert(E->getBase()->getType()->isVectorType());
3464f22ef01cSRoman Divacky     Base = EmitLValue(E->getBase());
3465f22ef01cSRoman Divacky   } else {
3466f22ef01cSRoman Divacky     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
346717a519f9SDimitry Andric     assert(E->getBase()->getType()->isVectorType() &&
3468f22ef01cSRoman Divacky            "Result must be a vector");
3469f22ef01cSRoman Divacky     llvm::Value *Vec = EmitScalarExpr(E->getBase());
3470f22ef01cSRoman Divacky 
3471f22ef01cSRoman Divacky     // Store the vector to memory (because LValue wants an address).
34720623d748SDimitry Andric     Address VecMem = CreateMemTemp(E->getBase()->getType());
3473f22ef01cSRoman Divacky     Builder.CreateStore(Vec, VecMem);
34740623d748SDimitry Andric     Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3475d8866befSDimitry Andric                           LValueBaseInfo(AlignmentSource::Decl, false));
3476f22ef01cSRoman Divacky   }
3477f22ef01cSRoman Divacky 
347817a519f9SDimitry Andric   QualType type =
347917a519f9SDimitry Andric     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
348017a519f9SDimitry Andric 
3481f22ef01cSRoman Divacky   // Encode the element access list into a vector of unsigned indices.
34820623d748SDimitry Andric   SmallVector<uint32_t, 4> Indices;
3483f22ef01cSRoman Divacky   E->getEncodedElementAccess(Indices);
3484f22ef01cSRoman Divacky 
3485f22ef01cSRoman Divacky   if (Base.isSimple()) {
34860623d748SDimitry Andric     llvm::Constant *CV =
34870623d748SDimitry Andric         llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3488dff0c46cSDimitry Andric     return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3489d8866befSDimitry Andric                                     Base.getBaseInfo());
3490f22ef01cSRoman Divacky   }
3491f22ef01cSRoman Divacky   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3492f22ef01cSRoman Divacky 
3493f22ef01cSRoman Divacky   llvm::Constant *BaseElts = Base.getExtVectorElts();
34946122f3e6SDimitry Andric   SmallVector<llvm::Constant *, 4> CElts;
3495f22ef01cSRoman Divacky 
3496dff0c46cSDimitry Andric   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3497dff0c46cSDimitry Andric     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
34982754fe60SDimitry Andric   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
34990623d748SDimitry Andric   return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3500d8866befSDimitry Andric                                   Base.getBaseInfo());
3501f22ef01cSRoman Divacky }
3502f22ef01cSRoman Divacky 
3503f22ef01cSRoman Divacky LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3504f22ef01cSRoman Divacky   Expr *BaseExpr = E->getBase();
3505f22ef01cSRoman Divacky   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
3506cb4dff85SDimitry Andric   LValue BaseLV;
35073861d79fSDimitry Andric   if (E->isArrow()) {
3508d8866befSDimitry Andric     LValueBaseInfo BaseInfo;
3509d8866befSDimitry Andric     Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
35103861d79fSDimitry Andric     QualType PtrTy = BaseExpr->getType()->getPointeeType();
351120e90f04SDimitry Andric     SanitizerSet SkippedChecks;
351220e90f04SDimitry Andric     bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
351320e90f04SDimitry Andric     if (IsBaseCXXThis)
351420e90f04SDimitry Andric       SkippedChecks.set(SanitizerKind::Alignment, true);
351520e90f04SDimitry Andric     if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
351620e90f04SDimitry Andric       SkippedChecks.set(SanitizerKind::Null, true);
351720e90f04SDimitry Andric     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
351820e90f04SDimitry Andric                   /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3519d8866befSDimitry Andric     BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
35203861d79fSDimitry Andric   } else
35213861d79fSDimitry Andric     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3522f22ef01cSRoman Divacky 
3523f22ef01cSRoman Divacky   NamedDecl *ND = E->getMemberDecl();
352459d1ed5bSDimitry Andric   if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3525cb4dff85SDimitry Andric     LValue LV = EmitLValueForField(BaseLV, Field);
3526f22ef01cSRoman Divacky     setObjCGCLValueClass(getContext(), E, LV);
3527f22ef01cSRoman Divacky     return LV;
3528f22ef01cSRoman Divacky   }
3529f22ef01cSRoman Divacky 
353059d1ed5bSDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(ND))
3531f22ef01cSRoman Divacky     return EmitGlobalVarDeclLValue(*this, E, VD);
3532f22ef01cSRoman Divacky 
353359d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3534f22ef01cSRoman Divacky     return EmitFunctionDeclLValue(*this, E, FD);
3535f22ef01cSRoman Divacky 
35366122f3e6SDimitry Andric   llvm_unreachable("Unhandled member declaration!");
3537f22ef01cSRoman Divacky }
3538f22ef01cSRoman Divacky 
3539284c1978SDimitry Andric /// Given that we are currently emitting a lambda, emit an l-value for
3540284c1978SDimitry Andric /// one of its members.
3541284c1978SDimitry Andric LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3542284c1978SDimitry Andric   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3543284c1978SDimitry Andric   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3544284c1978SDimitry Andric   QualType LambdaTagType =
3545284c1978SDimitry Andric     getContext().getTagDeclType(Field->getParent());
3546284c1978SDimitry Andric   LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3547284c1978SDimitry Andric   return EmitLValueForField(LambdaLV, Field);
3548284c1978SDimitry Andric }
3549284c1978SDimitry Andric 
35500623d748SDimitry Andric /// Drill down to the storage of a field without walking into
35510623d748SDimitry Andric /// reference types.
35520623d748SDimitry Andric ///
35530623d748SDimitry Andric /// The resulting address doesn't necessarily have the right type.
35540623d748SDimitry Andric static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
35550623d748SDimitry Andric                                       const FieldDecl *field) {
35560623d748SDimitry Andric   const RecordDecl *rec = field->getParent();
35570623d748SDimitry Andric 
35580623d748SDimitry Andric   unsigned idx =
35590623d748SDimitry Andric     CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
35600623d748SDimitry Andric 
35610623d748SDimitry Andric   CharUnits offset;
35620623d748SDimitry Andric   // Adjust the alignment down to the given offset.
35630623d748SDimitry Andric   // As a special case, if the LLVM field index is 0, we know that this
35640623d748SDimitry Andric   // is zero.
35650623d748SDimitry Andric   assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
35660623d748SDimitry Andric                          .getFieldOffset(field->getFieldIndex()) == 0) &&
35670623d748SDimitry Andric          "LLVM field at index zero had non-zero offset?");
35680623d748SDimitry Andric   if (idx != 0) {
35690623d748SDimitry Andric     auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
35700623d748SDimitry Andric     auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
35710623d748SDimitry Andric     offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
35720623d748SDimitry Andric   }
35730623d748SDimitry Andric 
35740623d748SDimitry Andric   return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
35750623d748SDimitry Andric }
35760623d748SDimitry Andric 
3577f9448bf3SDimitry Andric static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3578f9448bf3SDimitry Andric   const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3579f9448bf3SDimitry Andric   if (!RD)
3580f9448bf3SDimitry Andric     return false;
3581f9448bf3SDimitry Andric 
3582f9448bf3SDimitry Andric   if (RD->isDynamicClass())
3583f9448bf3SDimitry Andric     return true;
3584f9448bf3SDimitry Andric 
3585f9448bf3SDimitry Andric   for (const auto &Base : RD->bases())
3586f9448bf3SDimitry Andric     if (hasAnyVptr(Base.getType(), Context))
3587f9448bf3SDimitry Andric       return true;
3588f9448bf3SDimitry Andric 
3589f9448bf3SDimitry Andric   for (const FieldDecl *Field : RD->fields())
3590f9448bf3SDimitry Andric     if (hasAnyVptr(Field->getType(), Context))
3591f9448bf3SDimitry Andric       return true;
3592f9448bf3SDimitry Andric 
3593f9448bf3SDimitry Andric   return false;
3594f9448bf3SDimitry Andric }
3595f9448bf3SDimitry Andric 
3596cb4dff85SDimitry Andric LValue CodeGenFunction::EmitLValueForField(LValue base,
3597cb4dff85SDimitry Andric                                            const FieldDecl *field) {
3598d8866befSDimitry Andric   LValueBaseInfo BaseInfo = base.getBaseInfo();
35990623d748SDimitry Andric   AlignmentSource fieldAlignSource =
3600d8866befSDimitry Andric     getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3601d8866befSDimitry Andric   LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
36020623d748SDimitry Andric 
3603302affcbSDimitry Andric   const RecordDecl *rec = field->getParent();
3604302affcbSDimitry Andric   if (rec->isUnion() || rec->hasAttr<MayAliasAttr>())
3605302affcbSDimitry Andric     FieldBaseInfo.setMayAlias(true);
3606302affcbSDimitry Andric   bool mayAlias = FieldBaseInfo.getMayAlias();
3607302affcbSDimitry Andric 
36087ae0e2c9SDimitry Andric   if (field->isBitField()) {
36097ae0e2c9SDimitry Andric     const CGRecordLayout &RL =
36107ae0e2c9SDimitry Andric       CGM.getTypes().getCGRecordLayout(field->getParent());
36117ae0e2c9SDimitry Andric     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
36120623d748SDimitry Andric     Address Addr = base.getAddress();
3613139f7f9bSDimitry Andric     unsigned Idx = RL.getLLVMFieldNo(field);
3614139f7f9bSDimitry Andric     if (Idx != 0)
3615139f7f9bSDimitry Andric       // For structs, we GEP to the field that the record layout suggests.
36160623d748SDimitry Andric       Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
36170623d748SDimitry Andric                                      field->getName());
3618139f7f9bSDimitry Andric     // Get the access type.
36190623d748SDimitry Andric     llvm::Type *FieldIntTy =
36200623d748SDimitry Andric       llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
36210623d748SDimitry Andric     if (Addr.getElementType() != FieldIntTy)
36220623d748SDimitry Andric       Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3623139f7f9bSDimitry Andric 
36247ae0e2c9SDimitry Andric     QualType fieldType =
36257ae0e2c9SDimitry Andric       field->getType().withCVRQualifiers(base.getVRQualifiers());
3626d8866befSDimitry Andric     return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
36277ae0e2c9SDimitry Andric   }
3628f22ef01cSRoman Divacky 
3629dd6029ffSDimitry Andric   QualType type = field->getType();
36300623d748SDimitry Andric   Address addr = base.getAddress();
3631cb4dff85SDimitry Andric   unsigned cvr = base.getVRQualifiers();
3632139f7f9bSDimitry Andric   bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3633dd6029ffSDimitry Andric   if (rec->isUnion()) {
363417a519f9SDimitry Andric     // For unions, there is no pointer adjustment.
3635dd6029ffSDimitry Andric     assert(!type->isReferenceType() && "union has reference member");
3636139f7f9bSDimitry Andric     // TODO: handle path-aware TBAA for union.
3637139f7f9bSDimitry Andric     TBAAPath = false;
3638f9448bf3SDimitry Andric 
3639f9448bf3SDimitry Andric     const auto FieldType = field->getType();
3640f9448bf3SDimitry Andric     if (CGM.getCodeGenOpts().StrictVTablePointers &&
3641f9448bf3SDimitry Andric         hasAnyVptr(FieldType, getContext()))
3642f9448bf3SDimitry Andric       // Because unions can easily skip invariant.barriers, we need to add
3643f9448bf3SDimitry Andric       // a barrier every time CXXRecord field with vptr is referenced.
3644f9448bf3SDimitry Andric       addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3645f9448bf3SDimitry Andric                      addr.getAlignment());
3646dd6029ffSDimitry Andric   } else {
3647dd6029ffSDimitry Andric     // For structs, we GEP to the field that the record layout suggests.
36480623d748SDimitry Andric     addr = emitAddrOfFieldStorage(*this, addr, field);
3649dd6029ffSDimitry Andric 
3650dd6029ffSDimitry Andric     // If this is a reference field, load the reference right now.
3651dd6029ffSDimitry Andric     if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3652dd6029ffSDimitry Andric       llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3653dd6029ffSDimitry Andric       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3654dd6029ffSDimitry Andric 
3655139f7f9bSDimitry Andric       // Loading the reference will disable path-aware TBAA.
3656139f7f9bSDimitry Andric       TBAAPath = false;
3657dd6029ffSDimitry Andric       if (CGM.shouldUseTBAA()) {
3658dd6029ffSDimitry Andric         llvm::MDNode *tbaa;
3659dd6029ffSDimitry Andric         if (mayAlias)
3660dd6029ffSDimitry Andric           tbaa = CGM.getTBAAInfo(getContext().CharTy);
3661dd6029ffSDimitry Andric         else
3662dd6029ffSDimitry Andric           tbaa = CGM.getTBAAInfo(type);
3663f785676fSDimitry Andric         if (tbaa)
36640623d748SDimitry Andric           CGM.DecorateInstructionWithTBAA(load, tbaa);
3665f22ef01cSRoman Divacky       }
3666f22ef01cSRoman Divacky 
3667dd6029ffSDimitry Andric       mayAlias = false;
3668dd6029ffSDimitry Andric       type = refType->getPointeeType();
36690623d748SDimitry Andric 
36700623d748SDimitry Andric       CharUnits alignment =
3671d8866befSDimitry Andric         getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3672d8866befSDimitry Andric       FieldBaseInfo.setMayAlias(false);
36730623d748SDimitry Andric       addr = Address(load, alignment);
36740623d748SDimitry Andric 
36750623d748SDimitry Andric       // Qualifiers on the struct don't apply to the referencee, and
36760623d748SDimitry Andric       // we'll pick up CVR from the actual type later, so reset these
36770623d748SDimitry Andric       // additional qualifiers now.
36780623d748SDimitry Andric       cvr = 0;
3679dd6029ffSDimitry Andric     }
3680dd6029ffSDimitry Andric   }
3681dd6029ffSDimitry Andric 
368217a519f9SDimitry Andric   // Make sure that the address is pointing to the right type.  This is critical
368317a519f9SDimitry Andric   // for both unions and structs.  A union needs a bitcast, a struct element
368417a519f9SDimitry Andric   // will need a bitcast if the LLVM type laid out doesn't match the desired
368517a519f9SDimitry Andric   // type.
36860623d748SDimitry Andric   addr = Builder.CreateElementBitCast(addr,
368717a519f9SDimitry Andric                                       CGM.getTypes().ConvertTypeForMem(type),
368817a519f9SDimitry Andric                                       field->getName());
368917a519f9SDimitry Andric 
36906122f3e6SDimitry Andric   if (field->hasAttr<AnnotateAttr>())
36916122f3e6SDimitry Andric     addr = EmitFieldAnnotations(field, addr);
36926122f3e6SDimitry Andric 
3693d8866befSDimitry Andric   LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
3694dd6029ffSDimitry Andric   LV.getQuals().addCVRQualifiers(cvr);
3695139f7f9bSDimitry Andric   if (TBAAPath) {
3696139f7f9bSDimitry Andric     const ASTRecordLayout &Layout =
3697139f7f9bSDimitry Andric         getContext().getASTRecordLayout(field->getParent());
3698139f7f9bSDimitry Andric     // Set the base type to be the base type of the base LValue and
3699139f7f9bSDimitry Andric     // update offset to be relative to the base type.
3700284c1978SDimitry Andric     LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3701284c1978SDimitry Andric     LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
3702139f7f9bSDimitry Andric                      Layout.getFieldOffset(field->getFieldIndex()) /
3703139f7f9bSDimitry Andric                                            getContext().getCharWidth());
3704139f7f9bSDimitry Andric   }
3705f22ef01cSRoman Divacky 
3706e580952dSDimitry Andric   // __weak attribute on a field is ignored.
3707e580952dSDimitry Andric   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3708e580952dSDimitry Andric     LV.getQuals().removeObjCGCAttr();
3709e580952dSDimitry Andric 
3710dd6029ffSDimitry Andric   // Fields of may_alias structs act like 'char' for TBAA purposes.
3711dd6029ffSDimitry Andric   // FIXME: this should get propagated down through anonymous structs
3712dd6029ffSDimitry Andric   // and unions.
3713dd6029ffSDimitry Andric   if (mayAlias && LV.getTBAAInfo())
3714dd6029ffSDimitry Andric     LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3715dd6029ffSDimitry Andric 
3716e580952dSDimitry Andric   return LV;
3717f22ef01cSRoman Divacky }
3718f22ef01cSRoman Divacky 
3719f22ef01cSRoman Divacky LValue
3720cb4dff85SDimitry Andric CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3721cb4dff85SDimitry Andric                                                   const FieldDecl *Field) {
3722f22ef01cSRoman Divacky   QualType FieldType = Field->getType();
3723f22ef01cSRoman Divacky 
3724f22ef01cSRoman Divacky   if (!FieldType->isReferenceType())
3725cb4dff85SDimitry Andric     return EmitLValueForField(Base, Field);
3726f22ef01cSRoman Divacky 
37270623d748SDimitry Andric   Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3728f22ef01cSRoman Divacky 
37290623d748SDimitry Andric   // Make sure that the address is pointing to the right type.
37306122f3e6SDimitry Andric   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
37310623d748SDimitry Andric   V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
373217a519f9SDimitry Andric 
37330623d748SDimitry Andric   // TODO: access-path TBAA?
3734d8866befSDimitry Andric   LValueBaseInfo BaseInfo = Base.getBaseInfo();
3735d8866befSDimitry Andric   LValueBaseInfo FieldBaseInfo(
3736d8866befSDimitry Andric       getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3737d8866befSDimitry Andric       BaseInfo.getMayAlias());
3738d8866befSDimitry Andric   return MakeAddrLValue(V, FieldType, FieldBaseInfo);
3739f22ef01cSRoman Divacky }
3740f22ef01cSRoman Divacky 
3741f22ef01cSRoman Divacky LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3742d8866befSDimitry Andric   LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
3743dff0c46cSDimitry Andric   if (E->isFileScope()) {
37440623d748SDimitry Andric     ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3745d8866befSDimitry Andric     return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
3746dff0c46cSDimitry Andric   }
37477ae0e2c9SDimitry Andric   if (E->getType()->isVariablyModifiedType())
37487ae0e2c9SDimitry Andric     // make sure to emit the VLA size.
37497ae0e2c9SDimitry Andric     EmitVariablyModifiedType(E->getType());
3750dff0c46cSDimitry Andric 
37510623d748SDimitry Andric   Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3752f22ef01cSRoman Divacky   const Expr *InitExpr = E->getInitializer();
3753d8866befSDimitry Andric   LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
3754f22ef01cSRoman Divacky 
375517a519f9SDimitry Andric   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
375617a519f9SDimitry Andric                    /*Init*/ true);
3757f22ef01cSRoman Divacky 
3758f22ef01cSRoman Divacky   return Result;
3759f22ef01cSRoman Divacky }
3760f22ef01cSRoman Divacky 
37617ae0e2c9SDimitry Andric LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
37627ae0e2c9SDimitry Andric   if (!E->isGLValue())
37637ae0e2c9SDimitry Andric     // Initializing an aggregate temporary in C++11: T{...}.
37647ae0e2c9SDimitry Andric     return EmitAggExprToLValue(E);
37657ae0e2c9SDimitry Andric 
37667ae0e2c9SDimitry Andric   // An lvalue initializer list must be initializing a reference.
376744290647SDimitry Andric   assert(E->isTransparent() && "non-transparent glvalue init list");
37687ae0e2c9SDimitry Andric   return EmitLValue(E->getInit(0));
37697ae0e2c9SDimitry Andric }
37707ae0e2c9SDimitry Andric 
377159d1ed5bSDimitry Andric /// Emit the operand of a glvalue conditional operator. This is either a glvalue
377259d1ed5bSDimitry Andric /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
377359d1ed5bSDimitry Andric /// LValue is returned and the current block has been terminated.
377459d1ed5bSDimitry Andric static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
377559d1ed5bSDimitry Andric                                                     const Expr *Operand) {
377659d1ed5bSDimitry Andric   if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
377759d1ed5bSDimitry Andric     CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
377859d1ed5bSDimitry Andric     return None;
377959d1ed5bSDimitry Andric   }
378059d1ed5bSDimitry Andric 
378159d1ed5bSDimitry Andric   return CGF.EmitLValue(Operand);
378259d1ed5bSDimitry Andric }
378359d1ed5bSDimitry Andric 
37842754fe60SDimitry Andric LValue CodeGenFunction::
37852754fe60SDimitry Andric EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
37862754fe60SDimitry Andric   if (!expr->isGLValue()) {
3787f22ef01cSRoman Divacky     // ?: here should be an aggregate.
3788139f7f9bSDimitry Andric     assert(hasAggregateEvaluationKind(expr->getType()) &&
3789f22ef01cSRoman Divacky            "Unexpected conditional operator!");
37902754fe60SDimitry Andric     return EmitAggExprToLValue(expr);
37912754fe60SDimitry Andric   }
3792f22ef01cSRoman Divacky 
3793dff0c46cSDimitry Andric   OpaqueValueMapping binding(*this, expr);
3794dff0c46cSDimitry Andric 
37952754fe60SDimitry Andric   const Expr *condExpr = expr->getCond();
37963b0f4066SDimitry Andric   bool CondExprBool;
37973b0f4066SDimitry Andric   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
37982754fe60SDimitry Andric     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
37993b0f4066SDimitry Andric     if (!CondExprBool) std::swap(live, dead);
38002754fe60SDimitry Andric 
380159d1ed5bSDimitry Andric     if (!ContainsLabel(dead)) {
380259d1ed5bSDimitry Andric       // If the true case is live, we need to track its region.
380359d1ed5bSDimitry Andric       if (CondExprBool)
380433956c43SDimitry Andric         incrementProfileCounter(expr);
38052754fe60SDimitry Andric       return EmitLValue(live);
38062754fe60SDimitry Andric     }
380759d1ed5bSDimitry Andric   }
38082754fe60SDimitry Andric 
38092754fe60SDimitry Andric   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
38102754fe60SDimitry Andric   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
38112754fe60SDimitry Andric   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
38122754fe60SDimitry Andric 
38132754fe60SDimitry Andric   ConditionalEvaluation eval(*this);
381433956c43SDimitry Andric   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
38152754fe60SDimitry Andric 
38162754fe60SDimitry Andric   // Any temporaries created here are conditional.
38172754fe60SDimitry Andric   EmitBlock(lhsBlock);
381833956c43SDimitry Andric   incrementProfileCounter(expr);
38192754fe60SDimitry Andric   eval.begin(*this);
382059d1ed5bSDimitry Andric   Optional<LValue> lhs =
382159d1ed5bSDimitry Andric       EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
38222754fe60SDimitry Andric   eval.end(*this);
38232754fe60SDimitry Andric 
382459d1ed5bSDimitry Andric   if (lhs && !lhs->isSimple())
38252754fe60SDimitry Andric     return EmitUnsupportedLValue(expr, "conditional operator");
38262754fe60SDimitry Andric 
38272754fe60SDimitry Andric   lhsBlock = Builder.GetInsertBlock();
382859d1ed5bSDimitry Andric   if (lhs)
38292754fe60SDimitry Andric     Builder.CreateBr(contBlock);
38302754fe60SDimitry Andric 
38312754fe60SDimitry Andric   // Any temporaries created here are conditional.
38322754fe60SDimitry Andric   EmitBlock(rhsBlock);
38332754fe60SDimitry Andric   eval.begin(*this);
383459d1ed5bSDimitry Andric   Optional<LValue> rhs =
383559d1ed5bSDimitry Andric       EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
38362754fe60SDimitry Andric   eval.end(*this);
383759d1ed5bSDimitry Andric   if (rhs && !rhs->isSimple())
38382754fe60SDimitry Andric     return EmitUnsupportedLValue(expr, "conditional operator");
38392754fe60SDimitry Andric   rhsBlock = Builder.GetInsertBlock();
38402754fe60SDimitry Andric 
38412754fe60SDimitry Andric   EmitBlock(contBlock);
38422754fe60SDimitry Andric 
384359d1ed5bSDimitry Andric   if (lhs && rhs) {
38440623d748SDimitry Andric     llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
384559d1ed5bSDimitry Andric                                            2, "cond-lvalue");
38460623d748SDimitry Andric     phi->addIncoming(lhs->getPointer(), lhsBlock);
38470623d748SDimitry Andric     phi->addIncoming(rhs->getPointer(), rhsBlock);
38480623d748SDimitry Andric     Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
38490623d748SDimitry Andric     AlignmentSource alignSource =
3850d8866befSDimitry Andric       std::max(lhs->getBaseInfo().getAlignmentSource(),
3851d8866befSDimitry Andric                rhs->getBaseInfo().getAlignmentSource());
3852d8866befSDimitry Andric     bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3853d8866befSDimitry Andric                     rhs->getBaseInfo().getMayAlias();
3854d8866befSDimitry Andric     return MakeAddrLValue(result, expr->getType(),
3855d8866befSDimitry Andric                           LValueBaseInfo(alignSource, MayAlias));
385659d1ed5bSDimitry Andric   } else {
385759d1ed5bSDimitry Andric     assert((lhs || rhs) &&
385859d1ed5bSDimitry Andric            "both operands of glvalue conditional are throw-expressions?");
385959d1ed5bSDimitry Andric     return lhs ? *lhs : *rhs;
386059d1ed5bSDimitry Andric   }
3861f22ef01cSRoman Divacky }
3862f22ef01cSRoman Divacky 
38637ae0e2c9SDimitry Andric /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
38647ae0e2c9SDimitry Andric /// type. If the cast is to a reference, we can have the usual lvalue result,
3865f22ef01cSRoman Divacky /// otherwise if a cast is needed by the code generator in an lvalue context,
3866f22ef01cSRoman Divacky /// then it must mean that we need the address of an aggregate in order to
38677ae0e2c9SDimitry Andric /// access one of its members.  This can happen for all the reasons that casts
3868f22ef01cSRoman Divacky /// are permitted with aggregate result, including noop aggregate casts, and
3869f22ef01cSRoman Divacky /// cast from scalar to union.
3870f22ef01cSRoman Divacky LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3871f22ef01cSRoman Divacky   switch (E->getCastKind()) {
3872e580952dSDimitry Andric   case CK_ToVoid:
3873e580952dSDimitry Andric   case CK_BitCast:
3874e580952dSDimitry Andric   case CK_ArrayToPointerDecay:
3875e580952dSDimitry Andric   case CK_FunctionToPointerDecay:
3876e580952dSDimitry Andric   case CK_NullToMemberPointer:
38772754fe60SDimitry Andric   case CK_NullToPointer:
3878e580952dSDimitry Andric   case CK_IntegralToPointer:
3879e580952dSDimitry Andric   case CK_PointerToIntegral:
38802754fe60SDimitry Andric   case CK_PointerToBoolean:
3881e580952dSDimitry Andric   case CK_VectorSplat:
3882e580952dSDimitry Andric   case CK_IntegralCast:
3883444ed5c5SDimitry Andric   case CK_BooleanToSignedIntegral:
38842754fe60SDimitry Andric   case CK_IntegralToBoolean:
3885e580952dSDimitry Andric   case CK_IntegralToFloating:
3886e580952dSDimitry Andric   case CK_FloatingToIntegral:
38872754fe60SDimitry Andric   case CK_FloatingToBoolean:
3888e580952dSDimitry Andric   case CK_FloatingCast:
38892754fe60SDimitry Andric   case CK_FloatingRealToComplex:
38902754fe60SDimitry Andric   case CK_FloatingComplexToReal:
38912754fe60SDimitry Andric   case CK_FloatingComplexToBoolean:
38922754fe60SDimitry Andric   case CK_FloatingComplexCast:
38932754fe60SDimitry Andric   case CK_FloatingComplexToIntegralComplex:
38942754fe60SDimitry Andric   case CK_IntegralRealToComplex:
38952754fe60SDimitry Andric   case CK_IntegralComplexToReal:
38962754fe60SDimitry Andric   case CK_IntegralComplexToBoolean:
38972754fe60SDimitry Andric   case CK_IntegralComplexCast:
38982754fe60SDimitry Andric   case CK_IntegralComplexToFloatingComplex:
3899e580952dSDimitry Andric   case CK_DerivedToBaseMemberPointer:
3900e580952dSDimitry Andric   case CK_BaseToDerivedMemberPointer:
3901e580952dSDimitry Andric   case CK_MemberPointerToBoolean:
3902dff0c46cSDimitry Andric   case CK_ReinterpretMemberPointer:
390317a519f9SDimitry Andric   case CK_AnyPointerToBlockPointerCast:
39046122f3e6SDimitry Andric   case CK_ARCProduceObject:
39056122f3e6SDimitry Andric   case CK_ARCConsumeObject:
39066122f3e6SDimitry Andric   case CK_ARCReclaimReturnedObject:
3907dff0c46cSDimitry Andric   case CK_ARCExtendBlockObject:
3908f785676fSDimitry Andric   case CK_CopyAndAutoreleaseBlockObject:
390959d1ed5bSDimitry Andric   case CK_AddressSpaceConversion:
391044290647SDimitry Andric   case CK_IntToOCLSampler:
3911f785676fSDimitry Andric     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3912f785676fSDimitry Andric 
3913f785676fSDimitry Andric   case CK_Dependent:
3914f785676fSDimitry Andric     llvm_unreachable("dependent cast kind in IR gen!");
3915f785676fSDimitry Andric 
3916f785676fSDimitry Andric   case CK_BuiltinFnToFnPtr:
3917f785676fSDimitry Andric     llvm_unreachable("builtin functions are handled elsewhere");
3918f785676fSDimitry Andric 
3919f785676fSDimitry Andric   // These are never l-values; just use the aggregate emission code.
3920f785676fSDimitry Andric   case CK_NonAtomicToAtomic:
3921f785676fSDimitry Andric   case CK_AtomicToNonAtomic:
3922f785676fSDimitry Andric     return EmitAggExprToLValue(E);
3923e580952dSDimitry Andric 
3924e580952dSDimitry Andric   case CK_Dynamic: {
3925e580952dSDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
39260623d748SDimitry Andric     Address V = LV.getAddress();
392759d1ed5bSDimitry Andric     const auto *DCE = cast<CXXDynamicCastExpr>(E);
39280623d748SDimitry Andric     return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
3929e580952dSDimitry Andric   }
3930e580952dSDimitry Andric 
3931e580952dSDimitry Andric   case CK_ConstructorConversion:
3932e580952dSDimitry Andric   case CK_UserDefinedConversion:
39336122f3e6SDimitry Andric   case CK_CPointerToObjCPointerCast:
39346122f3e6SDimitry Andric   case CK_BlockPointerToObjCPointerCast:
3935f785676fSDimitry Andric   case CK_NoOp:
3936f785676fSDimitry Andric   case CK_LValueToRValue:
3937f22ef01cSRoman Divacky     return EmitLValue(E->getSubExpr());
3938f22ef01cSRoman Divacky 
3939e580952dSDimitry Andric   case CK_UncheckedDerivedToBase:
3940e580952dSDimitry Andric   case CK_DerivedToBase: {
3941f22ef01cSRoman Divacky     const RecordType *DerivedClassTy =
3942f22ef01cSRoman Divacky       E->getSubExpr()->getType()->getAs<RecordType>();
394359d1ed5bSDimitry Andric     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3944f22ef01cSRoman Divacky 
3945f22ef01cSRoman Divacky     LValue LV = EmitLValue(E->getSubExpr());
39460623d748SDimitry Andric     Address This = LV.getAddress();
3947f22ef01cSRoman Divacky 
3948f22ef01cSRoman Divacky     // Perform the derived-to-base conversion
39490623d748SDimitry Andric     Address Base = GetAddressOfBaseClass(
395039d628a0SDimitry Andric         This, DerivedClassDecl, E->path_begin(), E->path_end(),
395139d628a0SDimitry Andric         /*NullCheckValue=*/false, E->getExprLoc());
3952f22ef01cSRoman Divacky 
3953d8866befSDimitry Andric     return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
3954f22ef01cSRoman Divacky   }
3955e580952dSDimitry Andric   case CK_ToUnion:
3956f22ef01cSRoman Divacky     return EmitAggExprToLValue(E);
3957e580952dSDimitry Andric   case CK_BaseToDerived: {
3958f22ef01cSRoman Divacky     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
395959d1ed5bSDimitry Andric     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3960f22ef01cSRoman Divacky 
3961f22ef01cSRoman Divacky     LValue LV = EmitLValue(E->getSubExpr());
3962f22ef01cSRoman Divacky 
3963f22ef01cSRoman Divacky     // Perform the base-to-derived conversion
39640623d748SDimitry Andric     Address Derived =
3965f22ef01cSRoman Divacky       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3966e580952dSDimitry Andric                                E->path_begin(), E->path_end(),
3967e580952dSDimitry Andric                                /*NullCheckValue=*/false);
3968f22ef01cSRoman Divacky 
3969f785676fSDimitry Andric     // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3970f785676fSDimitry Andric     // performed and the object is not of the derived type.
397159d1ed5bSDimitry Andric     if (sanitizePerformTypeCheck())
3972f785676fSDimitry Andric       EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
39730623d748SDimitry Andric                     Derived.getPointer(), E->getType());
3974f785676fSDimitry Andric 
397533956c43SDimitry Andric     if (SanOpts.has(SanitizerKind::CFIDerivedCast))
39760623d748SDimitry Andric       EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
39770623d748SDimitry Andric                                 /*MayBeNull=*/false,
39788f0fd8f6SDimitry Andric                                 CFITCK_DerivedCast, E->getLocStart());
397933956c43SDimitry Andric 
3980d8866befSDimitry Andric     return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
3981f22ef01cSRoman Divacky   }
3982e580952dSDimitry Andric   case CK_LValueBitCast: {
3983f22ef01cSRoman Divacky     // This must be a reinterpret_cast (or c-style equivalent).
398459d1ed5bSDimitry Andric     const auto *CE = cast<ExplicitCastExpr>(E);
3985f22ef01cSRoman Divacky 
39860623d748SDimitry Andric     CGM.EmitExplicitCastExprType(CE, this);
3987f22ef01cSRoman Divacky     LValue LV = EmitLValue(E->getSubExpr());
39880623d748SDimitry Andric     Address V = Builder.CreateBitCast(LV.getAddress(),
3989f22ef01cSRoman Divacky                                       ConvertType(CE->getTypeAsWritten()));
399033956c43SDimitry Andric 
399133956c43SDimitry Andric     if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
39920623d748SDimitry Andric       EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
39930623d748SDimitry Andric                                 /*MayBeNull=*/false,
39948f0fd8f6SDimitry Andric                                 CFITCK_UnrelatedCast, E->getLocStart());
399533956c43SDimitry Andric 
3996d8866befSDimitry Andric     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
3997e580952dSDimitry Andric   }
3998e580952dSDimitry Andric   case CK_ObjCObjectLValueCast: {
3999e580952dSDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
40000623d748SDimitry Andric     Address V = Builder.CreateElementBitCast(LV.getAddress(),
40010623d748SDimitry Andric                                              ConvertType(E->getType()));
4002d8866befSDimitry Andric     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
4003f22ef01cSRoman Divacky   }
400444290647SDimitry Andric   case CK_ZeroToOCLQueue:
400544290647SDimitry Andric     llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
4006139f7f9bSDimitry Andric   case CK_ZeroToOCLEvent:
4007139f7f9bSDimitry Andric     llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
4008f22ef01cSRoman Divacky   }
4009e580952dSDimitry Andric 
4010e580952dSDimitry Andric   llvm_unreachable("Unhandled lvalue cast kind?");
4011f22ef01cSRoman Divacky }
4012f22ef01cSRoman Divacky 
40132754fe60SDimitry Andric LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4014dff0c46cSDimitry Andric   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
40152754fe60SDimitry Andric   return getOpaqueLValueMapping(e);
40162754fe60SDimitry Andric }
40172754fe60SDimitry Andric 
4018cb4dff85SDimitry Andric RValue CodeGenFunction::EmitRValueForField(LValue LV,
4019f785676fSDimitry Andric                                            const FieldDecl *FD,
4020f785676fSDimitry Andric                                            SourceLocation Loc) {
4021cb4dff85SDimitry Andric   QualType FT = FD->getType();
4022cb4dff85SDimitry Andric   LValue FieldLV = EmitLValueForField(LV, FD);
4023139f7f9bSDimitry Andric   switch (getEvaluationKind(FT)) {
4024139f7f9bSDimitry Andric   case TEK_Complex:
4025f785676fSDimitry Andric     return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4026139f7f9bSDimitry Andric   case TEK_Aggregate:
4027cb4dff85SDimitry Andric     return FieldLV.asAggregateRValue();
4028139f7f9bSDimitry Andric   case TEK_Scalar:
4029e7145dcbSDimitry Andric     // This routine is used to load fields one-by-one to perform a copy, so
4030e7145dcbSDimitry Andric     // don't load reference fields.
4031e7145dcbSDimitry Andric     if (FD->getType()->isReferenceType())
4032e7145dcbSDimitry Andric       return RValue::get(FieldLV.getPointer());
4033f785676fSDimitry Andric     return EmitLoadOfLValue(FieldLV, Loc);
4034cb4dff85SDimitry Andric   }
4035139f7f9bSDimitry Andric   llvm_unreachable("bad evaluation kind");
4036139f7f9bSDimitry Andric }
403717a519f9SDimitry Andric 
4038f22ef01cSRoman Divacky //===--------------------------------------------------------------------===//
4039f22ef01cSRoman Divacky //                             Expression Emission
4040f22ef01cSRoman Divacky //===--------------------------------------------------------------------===//
4041f22ef01cSRoman Divacky 
4042f22ef01cSRoman Divacky RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
4043f22ef01cSRoman Divacky                                      ReturnValueSlot ReturnValue) {
4044f22ef01cSRoman Divacky   // Builtins never have block type.
4045f22ef01cSRoman Divacky   if (E->getCallee()->getType()->isBlockPointerType())
4046f22ef01cSRoman Divacky     return EmitBlockCallExpr(E, ReturnValue);
4047f22ef01cSRoman Divacky 
404859d1ed5bSDimitry Andric   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4049f22ef01cSRoman Divacky     return EmitCXXMemberCallExpr(CE, ReturnValue);
4050f22ef01cSRoman Divacky 
405159d1ed5bSDimitry Andric   if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
40526122f3e6SDimitry Andric     return EmitCUDAKernelCallExpr(CE, ReturnValue);
40536122f3e6SDimitry Andric 
405459d1ed5bSDimitry Andric   if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
405544290647SDimitry Andric     if (const CXXMethodDecl *MD =
405644290647SDimitry Andric           dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4057f22ef01cSRoman Divacky       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4058f22ef01cSRoman Divacky 
405944290647SDimitry Andric   CGCallee callee = EmitCallee(E->getCallee());
406017a519f9SDimitry Andric 
406144290647SDimitry Andric   if (callee.isBuiltin()) {
406244290647SDimitry Andric     return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
406344290647SDimitry Andric                            E, ReturnValue);
406444290647SDimitry Andric   }
406544290647SDimitry Andric 
406644290647SDimitry Andric   if (callee.isPseudoDestructor()) {
406744290647SDimitry Andric     return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
406844290647SDimitry Andric   }
406944290647SDimitry Andric 
407044290647SDimitry Andric   return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
407144290647SDimitry Andric }
407244290647SDimitry Andric 
407344290647SDimitry Andric /// Emit a CallExpr without considering whether it might be a subclass.
407444290647SDimitry Andric RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
407544290647SDimitry Andric                                            ReturnValueSlot ReturnValue) {
407644290647SDimitry Andric   CGCallee Callee = EmitCallee(E->getCallee());
407744290647SDimitry Andric   return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
407844290647SDimitry Andric }
407944290647SDimitry Andric 
408044290647SDimitry Andric static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
408144290647SDimitry Andric   if (auto builtinID = FD->getBuiltinID()) {
408244290647SDimitry Andric     return CGCallee::forBuiltin(builtinID, FD);
408344290647SDimitry Andric   }
408444290647SDimitry Andric 
408544290647SDimitry Andric   llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
408644290647SDimitry Andric   return CGCallee::forDirect(calleePtr, FD);
408744290647SDimitry Andric }
408844290647SDimitry Andric 
408944290647SDimitry Andric CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
409044290647SDimitry Andric   E = E->IgnoreParens();
409144290647SDimitry Andric 
409244290647SDimitry Andric   // Look through function-to-pointer decay.
409344290647SDimitry Andric   if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
409444290647SDimitry Andric     if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
409544290647SDimitry Andric         ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
409644290647SDimitry Andric       return EmitCallee(ICE->getSubExpr());
409744290647SDimitry Andric     }
409844290647SDimitry Andric 
409944290647SDimitry Andric   // Resolve direct calls.
410044290647SDimitry Andric   } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
410144290647SDimitry Andric     if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
410244290647SDimitry Andric       return EmitDirectCallee(*this, FD);
410344290647SDimitry Andric     }
410444290647SDimitry Andric   } else if (auto ME = dyn_cast<MemberExpr>(E)) {
410544290647SDimitry Andric     if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
410644290647SDimitry Andric       EmitIgnoredExpr(ME->getBase());
410744290647SDimitry Andric       return EmitDirectCallee(*this, FD);
410844290647SDimitry Andric     }
410944290647SDimitry Andric 
411044290647SDimitry Andric   // Look through template substitutions.
411144290647SDimitry Andric   } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
411244290647SDimitry Andric     return EmitCallee(NTTP->getReplacement());
411344290647SDimitry Andric 
411444290647SDimitry Andric   // Treat pseudo-destructor calls differently.
411544290647SDimitry Andric   } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
411644290647SDimitry Andric     return CGCallee::forPseudoDestructor(PDE);
411744290647SDimitry Andric   }
411844290647SDimitry Andric 
411944290647SDimitry Andric   // Otherwise, we have an indirect reference.
412044290647SDimitry Andric   llvm::Value *calleePtr;
412144290647SDimitry Andric   QualType functionType;
412244290647SDimitry Andric   if (auto ptrType = E->getType()->getAs<PointerType>()) {
412344290647SDimitry Andric     calleePtr = EmitScalarExpr(E);
412444290647SDimitry Andric     functionType = ptrType->getPointeeType();
412517a519f9SDimitry Andric   } else {
412644290647SDimitry Andric     functionType = E->getType();
412744290647SDimitry Andric     calleePtr = EmitLValue(E).getPointer();
412817a519f9SDimitry Andric   }
412944290647SDimitry Andric   assert(functionType->isFunctionType());
413044290647SDimitry Andric   CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
413144290647SDimitry Andric                           E->getReferencedDeclOfCallee());
413244290647SDimitry Andric   CGCallee callee(calleeInfo, calleePtr);
413344290647SDimitry Andric   return callee;
4134f22ef01cSRoman Divacky }
4135f22ef01cSRoman Divacky 
4136f22ef01cSRoman Divacky LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4137f22ef01cSRoman Divacky   // Comma expressions just emit their LHS then their RHS as an l-value.
4138e580952dSDimitry Andric   if (E->getOpcode() == BO_Comma) {
41392754fe60SDimitry Andric     EmitIgnoredExpr(E->getLHS());
4140f22ef01cSRoman Divacky     EnsureInsertPoint();
4141f22ef01cSRoman Divacky     return EmitLValue(E->getRHS());
4142f22ef01cSRoman Divacky   }
4143f22ef01cSRoman Divacky 
4144e580952dSDimitry Andric   if (E->getOpcode() == BO_PtrMemD ||
4145e580952dSDimitry Andric       E->getOpcode() == BO_PtrMemI)
4146f22ef01cSRoman Divacky     return EmitPointerToDataMemberBinaryExpr(E);
4147f22ef01cSRoman Divacky 
41482754fe60SDimitry Andric   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4149f22ef01cSRoman Divacky 
415017a519f9SDimitry Andric   // Note that in all of these cases, __block variables need the RHS
415117a519f9SDimitry Andric   // evaluated first just in case the variable gets moved by the RHS.
415217a519f9SDimitry Andric 
4153139f7f9bSDimitry Andric   switch (getEvaluationKind(E->getType())) {
4154139f7f9bSDimitry Andric   case TEK_Scalar: {
415517a519f9SDimitry Andric     switch (E->getLHS()->getType().getObjCLifetime()) {
415617a519f9SDimitry Andric     case Qualifiers::OCL_Strong:
415717a519f9SDimitry Andric       return EmitARCStoreStrong(E, /*ignored*/ false).first;
415817a519f9SDimitry Andric 
415917a519f9SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
416017a519f9SDimitry Andric       return EmitARCStoreAutoreleasing(E).first;
416117a519f9SDimitry Andric 
416217a519f9SDimitry Andric     // No reason to do any of these differently.
416317a519f9SDimitry Andric     case Qualifiers::OCL_None:
416417a519f9SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
416517a519f9SDimitry Andric     case Qualifiers::OCL_Weak:
416617a519f9SDimitry Andric       break;
416717a519f9SDimitry Andric     }
416817a519f9SDimitry Andric 
41692754fe60SDimitry Andric     RValue RV = EmitAnyExpr(E->getRHS());
41703861d79fSDimitry Andric     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4171f37b6182SDimitry Andric     if (RV.isScalar())
4172f37b6182SDimitry Andric       EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
417317a519f9SDimitry Andric     EmitStoreThroughLValue(RV, LV);
4174f22ef01cSRoman Divacky     return LV;
4175f22ef01cSRoman Divacky   }
4176f22ef01cSRoman Divacky 
4177139f7f9bSDimitry Andric   case TEK_Complex:
41782754fe60SDimitry Andric     return EmitComplexAssignmentLValue(E);
41792754fe60SDimitry Andric 
4180139f7f9bSDimitry Andric   case TEK_Aggregate:
4181f22ef01cSRoman Divacky     return EmitAggExprToLValue(E);
4182f22ef01cSRoman Divacky   }
4183139f7f9bSDimitry Andric   llvm_unreachable("bad evaluation kind");
4184139f7f9bSDimitry Andric }
4185f22ef01cSRoman Divacky 
4186f22ef01cSRoman Divacky LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4187f22ef01cSRoman Divacky   RValue RV = EmitCallExpr(E);
4188f22ef01cSRoman Divacky 
4189f22ef01cSRoman Divacky   if (!RV.isScalar())
41900623d748SDimitry Andric     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4191d8866befSDimitry Andric                           LValueBaseInfo(AlignmentSource::Decl, false));
4192f22ef01cSRoman Divacky 
419333956c43SDimitry Andric   assert(E->getCallReturnType(getContext())->isReferenceType() &&
4194f22ef01cSRoman Divacky          "Can't have a scalar return unless the return type is a "
4195f22ef01cSRoman Divacky          "reference type!");
4196f22ef01cSRoman Divacky 
41970623d748SDimitry Andric   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4198f22ef01cSRoman Divacky }
4199f22ef01cSRoman Divacky 
4200f22ef01cSRoman Divacky LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4201f22ef01cSRoman Divacky   // FIXME: This shouldn't require another copy.
4202f22ef01cSRoman Divacky   return EmitAggExprToLValue(E);
4203f22ef01cSRoman Divacky }
4204f22ef01cSRoman Divacky 
4205f22ef01cSRoman Divacky LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
42062754fe60SDimitry Andric   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
42072754fe60SDimitry Andric          && "binding l-value to type which needs a temporary");
42086122f3e6SDimitry Andric   AggValueSlot Slot = CreateAggTemp(E->getType());
42092754fe60SDimitry Andric   EmitCXXConstructExpr(E, Slot);
42100623d748SDimitry Andric   return MakeAddrLValue(Slot.getAddress(), E->getType(),
4211d8866befSDimitry Andric                         LValueBaseInfo(AlignmentSource::Decl, false));
4212f22ef01cSRoman Divacky }
4213f22ef01cSRoman Divacky 
4214f22ef01cSRoman Divacky LValue
4215f22ef01cSRoman Divacky CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
42160623d748SDimitry Andric   return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4217f22ef01cSRoman Divacky }
4218f22ef01cSRoman Divacky 
42190623d748SDimitry Andric Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
42200623d748SDimitry Andric   return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
42210623d748SDimitry Andric                                       ConvertType(E->getType()));
42223861d79fSDimitry Andric }
42233861d79fSDimitry Andric 
42243861d79fSDimitry Andric LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
42250623d748SDimitry Andric   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4226d8866befSDimitry Andric                         LValueBaseInfo(AlignmentSource::Decl, false));
42273861d79fSDimitry Andric }
42283861d79fSDimitry Andric 
4229f22ef01cSRoman Divacky LValue
4230f22ef01cSRoman Divacky CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
42312754fe60SDimitry Andric   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
42326122f3e6SDimitry Andric   Slot.setExternallyDestructed();
42332754fe60SDimitry Andric   EmitAggExpr(E->getSubExpr(), Slot);
42340623d748SDimitry Andric   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
42350623d748SDimitry Andric   return MakeAddrLValue(Slot.getAddress(), E->getType(),
4236d8866befSDimitry Andric                         LValueBaseInfo(AlignmentSource::Decl, false));
4237dff0c46cSDimitry Andric }
4238dff0c46cSDimitry Andric 
4239dff0c46cSDimitry Andric LValue
4240dff0c46cSDimitry Andric CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4241dff0c46cSDimitry Andric   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4242dff0c46cSDimitry Andric   EmitLambdaExpr(E, Slot);
42430623d748SDimitry Andric   return MakeAddrLValue(Slot.getAddress(), E->getType(),
4244d8866befSDimitry Andric                         LValueBaseInfo(AlignmentSource::Decl, false));
4245f22ef01cSRoman Divacky }
4246f22ef01cSRoman Divacky 
4247f22ef01cSRoman Divacky LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4248f22ef01cSRoman Divacky   RValue RV = EmitObjCMessageExpr(E);
4249ffd1746dSEd Schouten 
4250ffd1746dSEd Schouten   if (!RV.isScalar())
42510623d748SDimitry Andric     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4252d8866befSDimitry Andric                           LValueBaseInfo(AlignmentSource::Decl, false));
4253ffd1746dSEd Schouten 
425459d1ed5bSDimitry Andric   assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4255ffd1746dSEd Schouten          "Can't have a scalar return unless the return type is a "
4256ffd1746dSEd Schouten          "reference type!");
4257ffd1746dSEd Schouten 
42580623d748SDimitry Andric   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4259ffd1746dSEd Schouten }
4260ffd1746dSEd Schouten 
4261ffd1746dSEd Schouten LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
42620623d748SDimitry Andric   Address V =
42630623d748SDimitry Andric     CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4264d8866befSDimitry Andric   return MakeAddrLValue(V, E->getType(),
4265d8866befSDimitry Andric                         LValueBaseInfo(AlignmentSource::Decl, false));
4266f22ef01cSRoman Divacky }
4267f22ef01cSRoman Divacky 
4268f22ef01cSRoman Divacky llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4269f22ef01cSRoman Divacky                                              const ObjCIvarDecl *Ivar) {
4270f22ef01cSRoman Divacky   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4271f22ef01cSRoman Divacky }
4272f22ef01cSRoman Divacky 
4273f22ef01cSRoman Divacky LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4274f22ef01cSRoman Divacky                                           llvm::Value *BaseValue,
4275f22ef01cSRoman Divacky                                           const ObjCIvarDecl *Ivar,
4276f22ef01cSRoman Divacky                                           unsigned CVRQualifiers) {
4277f22ef01cSRoman Divacky   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4278f22ef01cSRoman Divacky                                                    Ivar, CVRQualifiers);
4279f22ef01cSRoman Divacky }
4280f22ef01cSRoman Divacky 
4281f22ef01cSRoman Divacky LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4282f22ef01cSRoman Divacky   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
428359d1ed5bSDimitry Andric   llvm::Value *BaseValue = nullptr;
4284f22ef01cSRoman Divacky   const Expr *BaseExpr = E->getBase();
4285f22ef01cSRoman Divacky   Qualifiers BaseQuals;
4286f22ef01cSRoman Divacky   QualType ObjectTy;
4287f22ef01cSRoman Divacky   if (E->isArrow()) {
4288f22ef01cSRoman Divacky     BaseValue = EmitScalarExpr(BaseExpr);
4289f22ef01cSRoman Divacky     ObjectTy = BaseExpr->getType()->getPointeeType();
4290f22ef01cSRoman Divacky     BaseQuals = ObjectTy.getQualifiers();
4291f22ef01cSRoman Divacky   } else {
4292f22ef01cSRoman Divacky     LValue BaseLV = EmitLValue(BaseExpr);
42930623d748SDimitry Andric     BaseValue = BaseLV.getPointer();
4294f22ef01cSRoman Divacky     ObjectTy = BaseExpr->getType();
4295f22ef01cSRoman Divacky     BaseQuals = ObjectTy.getQualifiers();
4296f22ef01cSRoman Divacky   }
4297f22ef01cSRoman Divacky 
4298f22ef01cSRoman Divacky   LValue LV =
4299f22ef01cSRoman Divacky     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4300f22ef01cSRoman Divacky                       BaseQuals.getCVRQualifiers());
4301f22ef01cSRoman Divacky   setObjCGCLValueClass(getContext(), E, LV);
4302f22ef01cSRoman Divacky   return LV;
4303f22ef01cSRoman Divacky }
4304f22ef01cSRoman Divacky 
4305f22ef01cSRoman Divacky LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4306f22ef01cSRoman Divacky   // Can only get l-value for message expression returning aggregate type
4307f22ef01cSRoman Divacky   RValue RV = EmitAnyExprToTemp(E);
43080623d748SDimitry Andric   return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4309d8866befSDimitry Andric                         LValueBaseInfo(AlignmentSource::Decl, false));
4310f22ef01cSRoman Divacky }
4311f22ef01cSRoman Divacky 
431244290647SDimitry Andric RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
431339d628a0SDimitry Andric                                  const CallExpr *E, ReturnValueSlot ReturnValue,
431444290647SDimitry Andric                                  llvm::Value *Chain) {
4315f22ef01cSRoman Divacky   // Get the actual function type. The callee type will always be a pointer to
4316f22ef01cSRoman Divacky   // function type or a block pointer type.
4317f22ef01cSRoman Divacky   assert(CalleeType->isFunctionPointerType() &&
4318f22ef01cSRoman Divacky          "Call must have function pointer type!");
4319f22ef01cSRoman Divacky 
432044290647SDimitry Andric   const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
43210623d748SDimitry Andric 
43220623d748SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
43230623d748SDimitry Andric     // We can only guarantee that a function is called from the correct
43240623d748SDimitry Andric     // context/function based on the appropriate target attributes,
43250623d748SDimitry Andric     // so only check in the case where we have both always_inline and target
43260623d748SDimitry Andric     // since otherwise we could be making a conditional call after a check for
43270623d748SDimitry Andric     // the proper cpu features (and it won't cause code generation issues due to
43280623d748SDimitry Andric     // function based code generation).
43290623d748SDimitry Andric     if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
43300623d748SDimitry Andric         TargetDecl->hasAttr<TargetAttr>())
43310623d748SDimitry Andric       checkTargetFeatures(E, FD);
43320623d748SDimitry Andric 
4333f22ef01cSRoman Divacky   CalleeType = getContext().getCanonicalType(CalleeType);
4334f22ef01cSRoman Divacky 
433559d1ed5bSDimitry Andric   const auto *FnType =
433659d1ed5bSDimitry Andric       cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4337f22ef01cSRoman Divacky 
433844290647SDimitry Andric   CGCallee Callee = OrigCallee;
433944290647SDimitry Andric 
434039d628a0SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4341f785676fSDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4342f785676fSDimitry Andric     if (llvm::Constant *PrefixSig =
4343f785676fSDimitry Andric             CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
434459d1ed5bSDimitry Andric       SanitizerScope SanScope(this);
4345f785676fSDimitry Andric       llvm::Constant *FTRTTIConst =
4346f785676fSDimitry Andric           CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4347f785676fSDimitry Andric       llvm::Type *PrefixStructTyElems[] = {
4348f785676fSDimitry Andric         PrefixSig->getType(),
4349f785676fSDimitry Andric         FTRTTIConst->getType()
4350f785676fSDimitry Andric       };
4351f785676fSDimitry Andric       llvm::StructType *PrefixStructTy = llvm::StructType::get(
4352f785676fSDimitry Andric           CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4353f785676fSDimitry Andric 
435444290647SDimitry Andric       llvm::Value *CalleePtr = Callee.getFunctionPointer();
435544290647SDimitry Andric 
4356f785676fSDimitry Andric       llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
435744290647SDimitry Andric           CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4358f785676fSDimitry Andric       llvm::Value *CalleeSigPtr =
435933956c43SDimitry Andric           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
43600623d748SDimitry Andric       llvm::Value *CalleeSig =
43610623d748SDimitry Andric           Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4362f785676fSDimitry Andric       llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4363f785676fSDimitry Andric 
4364f785676fSDimitry Andric       llvm::BasicBlock *Cont = createBasicBlock("cont");
4365f785676fSDimitry Andric       llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4366f785676fSDimitry Andric       Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4367f785676fSDimitry Andric 
4368f785676fSDimitry Andric       EmitBlock(TypeCheck);
4369f785676fSDimitry Andric       llvm::Value *CalleeRTTIPtr =
437033956c43SDimitry Andric           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
43710623d748SDimitry Andric       llvm::Value *CalleeRTTI =
43720623d748SDimitry Andric           Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4373f785676fSDimitry Andric       llvm::Value *CalleeRTTIMatch =
4374f785676fSDimitry Andric           Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4375f785676fSDimitry Andric       llvm::Constant *StaticData[] = {
437639d628a0SDimitry Andric         EmitCheckSourceLocation(E->getLocStart()),
4377f785676fSDimitry Andric         EmitCheckTypeDescriptor(CalleeType)
4378f785676fSDimitry Andric       };
437939d628a0SDimitry Andric       EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
438044290647SDimitry Andric                 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4381f785676fSDimitry Andric 
4382f785676fSDimitry Andric       Builder.CreateBr(Cont);
4383f785676fSDimitry Andric       EmitBlock(Cont);
4384f785676fSDimitry Andric     }
4385f785676fSDimitry Andric   }
4386f785676fSDimitry Andric 
43870623d748SDimitry Andric   // If we are checking indirect calls and this call is indirect, check that the
43880623d748SDimitry Andric   // function pointer is a member of the bit set for the function type.
43890623d748SDimitry Andric   if (SanOpts.has(SanitizerKind::CFIICall) &&
43900623d748SDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
43910623d748SDimitry Andric     SanitizerScope SanScope(this);
4392e7145dcbSDimitry Andric     EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
43930623d748SDimitry Andric 
43940623d748SDimitry Andric     llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4395e7145dcbSDimitry Andric     llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
43960623d748SDimitry Andric 
439744290647SDimitry Andric     llvm::Value *CalleePtr = Callee.getFunctionPointer();
439844290647SDimitry Andric     llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4399e7145dcbSDimitry Andric     llvm::Value *TypeTest = Builder.CreateCall(
4400e7145dcbSDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
44010623d748SDimitry Andric 
4402e7145dcbSDimitry Andric     auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
44030623d748SDimitry Andric     llvm::Constant *StaticData[] = {
4404e7145dcbSDimitry Andric         llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
44050623d748SDimitry Andric         EmitCheckSourceLocation(E->getLocStart()),
44060623d748SDimitry Andric         EmitCheckTypeDescriptor(QualType(FnType, 0)),
44070623d748SDimitry Andric     };
4408e7145dcbSDimitry Andric     if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4409e7145dcbSDimitry Andric       EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4410e7145dcbSDimitry Andric                            CastedCallee, StaticData);
4411e7145dcbSDimitry Andric     } else {
4412e7145dcbSDimitry Andric       EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
441344290647SDimitry Andric                 SanitizerHandler::CFICheckFail, StaticData,
4414e7145dcbSDimitry Andric                 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
44150623d748SDimitry Andric     }
44160623d748SDimitry Andric   }
44170623d748SDimitry Andric 
4418f22ef01cSRoman Divacky   CallArgList Args;
441939d628a0SDimitry Andric   if (Chain)
442039d628a0SDimitry Andric     Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
442139d628a0SDimitry Andric              CGM.getContext().VoidPtrTy);
442244290647SDimitry Andric 
442344290647SDimitry Andric   // C++17 requires that we evaluate arguments to a call using assignment syntax
442444290647SDimitry Andric   // right-to-left, and that we evaluate arguments to certain other operators
442544290647SDimitry Andric   // left-to-right. Note that we allow this to override the order dictated by
442644290647SDimitry Andric   // the calling convention on the MS ABI, which means that parameter
442744290647SDimitry Andric   // destruction order is not necessarily reverse construction order.
442844290647SDimitry Andric   // FIXME: Revisit this based on C++ committee response to unimplementability.
442944290647SDimitry Andric   EvaluationOrder Order = EvaluationOrder::Default;
443044290647SDimitry Andric   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
443144290647SDimitry Andric     if (OCE->isAssignmentOp())
443244290647SDimitry Andric       Order = EvaluationOrder::ForceRightToLeft;
443344290647SDimitry Andric     else {
443444290647SDimitry Andric       switch (OCE->getOperator()) {
443544290647SDimitry Andric       case OO_LessLess:
443644290647SDimitry Andric       case OO_GreaterGreater:
443744290647SDimitry Andric       case OO_AmpAmp:
443844290647SDimitry Andric       case OO_PipePipe:
443944290647SDimitry Andric       case OO_Comma:
444044290647SDimitry Andric       case OO_ArrowStar:
444144290647SDimitry Andric         Order = EvaluationOrder::ForceLeftToRight;
444244290647SDimitry Andric         break;
444344290647SDimitry Andric       default:
444444290647SDimitry Andric         break;
444544290647SDimitry Andric       }
444644290647SDimitry Andric     }
444744290647SDimitry Andric   }
444844290647SDimitry Andric 
44490623d748SDimitry Andric   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
445044290647SDimitry Andric                E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4451f22ef01cSRoman Divacky 
445239d628a0SDimitry Andric   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
445339d628a0SDimitry Andric       Args, FnType, /*isChainCall=*/Chain);
44546122f3e6SDimitry Andric 
44556122f3e6SDimitry Andric   // C99 6.5.2.2p6:
44566122f3e6SDimitry Andric   //   If the expression that denotes the called function has a type
44576122f3e6SDimitry Andric   //   that does not include a prototype, [the default argument
44586122f3e6SDimitry Andric   //   promotions are performed]. If the number of arguments does not
44596122f3e6SDimitry Andric   //   equal the number of parameters, the behavior is undefined. If
44606122f3e6SDimitry Andric   //   the function is defined with a type that includes a prototype,
44616122f3e6SDimitry Andric   //   and either the prototype ends with an ellipsis (, ...) or the
44626122f3e6SDimitry Andric   //   types of the arguments after promotion are not compatible with
44636122f3e6SDimitry Andric   //   the types of the parameters, the behavior is undefined. If the
44646122f3e6SDimitry Andric   //   function is defined with a type that does not include a
44656122f3e6SDimitry Andric   //   prototype, and the types of the arguments after promotion are
44666122f3e6SDimitry Andric   //   not compatible with those of the parameters after promotion,
44676122f3e6SDimitry Andric   //   the behavior is undefined [except in some trivial cases].
44686122f3e6SDimitry Andric   // That is, in the general case, we should assume that a call
44696122f3e6SDimitry Andric   // through an unprototyped function type works like a *non-variadic*
44706122f3e6SDimitry Andric   // call.  The way we make this work is to cast to the exact type
44716122f3e6SDimitry Andric   // of the promoted arguments.
447239d628a0SDimitry Andric   //
447339d628a0SDimitry Andric   // Chain calls use this same code path to add the invisible chain parameter
447439d628a0SDimitry Andric   // to the function type.
447539d628a0SDimitry Andric   if (isa<FunctionNoProtoType>(FnType) || Chain) {
4476dff0c46cSDimitry Andric     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
44776122f3e6SDimitry Andric     CalleeTy = CalleeTy->getPointerTo();
447844290647SDimitry Andric 
447944290647SDimitry Andric     llvm::Value *CalleePtr = Callee.getFunctionPointer();
448044290647SDimitry Andric     CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
448144290647SDimitry Andric     Callee.setFunctionPointer(CalleePtr);
44826122f3e6SDimitry Andric   }
44836122f3e6SDimitry Andric 
448444290647SDimitry Andric   return EmitCall(FnInfo, Callee, ReturnValue, Args);
4485f22ef01cSRoman Divacky }
4486f22ef01cSRoman Divacky 
4487f22ef01cSRoman Divacky LValue CodeGenFunction::
4488f22ef01cSRoman Divacky EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
44890623d748SDimitry Andric   Address BaseAddr = Address::invalid();
44900623d748SDimitry Andric   if (E->getOpcode() == BO_PtrMemI) {
44910623d748SDimitry Andric     BaseAddr = EmitPointerWithAlignment(E->getLHS());
44920623d748SDimitry Andric   } else {
44930623d748SDimitry Andric     BaseAddr = EmitLValue(E->getLHS()).getAddress();
44940623d748SDimitry Andric   }
4495e580952dSDimitry Andric 
4496f22ef01cSRoman Divacky   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4497f22ef01cSRoman Divacky 
4498e580952dSDimitry Andric   const MemberPointerType *MPT
4499e580952dSDimitry Andric     = E->getRHS()->getType()->getAs<MemberPointerType>();
4500f22ef01cSRoman Divacky 
4501d8866befSDimitry Andric   LValueBaseInfo BaseInfo;
45020623d748SDimitry Andric   Address MemberAddr =
4503d8866befSDimitry Andric     EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
4504e580952dSDimitry Andric 
4505d8866befSDimitry Andric   return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
4506f22ef01cSRoman Divacky }
45076122f3e6SDimitry Andric 
4508139f7f9bSDimitry Andric /// Given the address of a temporary variable, produce an r-value of
4509139f7f9bSDimitry Andric /// its type.
45100623d748SDimitry Andric RValue CodeGenFunction::convertTempToRValue(Address addr,
4511f785676fSDimitry Andric                                             QualType type,
4512f785676fSDimitry Andric                                             SourceLocation loc) {
4513d8866befSDimitry Andric   LValue lvalue = MakeAddrLValue(addr, type,
4514d8866befSDimitry Andric                                  LValueBaseInfo(AlignmentSource::Decl, false));
4515139f7f9bSDimitry Andric   switch (getEvaluationKind(type)) {
4516139f7f9bSDimitry Andric   case TEK_Complex:
4517f785676fSDimitry Andric     return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4518139f7f9bSDimitry Andric   case TEK_Aggregate:
4519139f7f9bSDimitry Andric     return lvalue.asAggregateRValue();
4520139f7f9bSDimitry Andric   case TEK_Scalar:
4521f785676fSDimitry Andric     return RValue::get(EmitLoadOfScalar(lvalue, loc));
45226122f3e6SDimitry Andric   }
4523139f7f9bSDimitry Andric   llvm_unreachable("bad evaluation kind");
45246122f3e6SDimitry Andric }
4525dff0c46cSDimitry Andric 
4526dff0c46cSDimitry Andric void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4527dff0c46cSDimitry Andric   assert(Val->getType()->isFPOrFPVectorTy());
4528dff0c46cSDimitry Andric   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4529dff0c46cSDimitry Andric     return;
4530dff0c46cSDimitry Andric 
4531cb4dff85SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
4532cb4dff85SDimitry Andric   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4533dff0c46cSDimitry Andric 
4534cb4dff85SDimitry Andric   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4535dff0c46cSDimitry Andric }
4536dff0c46cSDimitry Andric 
4537dff0c46cSDimitry Andric namespace {
4538dff0c46cSDimitry Andric   struct LValueOrRValue {
4539dff0c46cSDimitry Andric     LValue LV;
4540dff0c46cSDimitry Andric     RValue RV;
4541dff0c46cSDimitry Andric   };
4542dff0c46cSDimitry Andric }
4543dff0c46cSDimitry Andric 
4544dff0c46cSDimitry Andric static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4545dff0c46cSDimitry Andric                                            const PseudoObjectExpr *E,
4546dff0c46cSDimitry Andric                                            bool forLValue,
4547dff0c46cSDimitry Andric                                            AggValueSlot slot) {
4548139f7f9bSDimitry Andric   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4549dff0c46cSDimitry Andric 
4550dff0c46cSDimitry Andric   // Find the result expression, if any.
4551dff0c46cSDimitry Andric   const Expr *resultExpr = E->getResultExpr();
4552dff0c46cSDimitry Andric   LValueOrRValue result;
4553dff0c46cSDimitry Andric 
4554dff0c46cSDimitry Andric   for (PseudoObjectExpr::const_semantics_iterator
4555dff0c46cSDimitry Andric          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4556dff0c46cSDimitry Andric     const Expr *semantic = *i;
4557dff0c46cSDimitry Andric 
4558dff0c46cSDimitry Andric     // If this semantic expression is an opaque value, bind it
4559dff0c46cSDimitry Andric     // to the result of its source expression.
456059d1ed5bSDimitry Andric     if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4561dff0c46cSDimitry Andric 
4562dff0c46cSDimitry Andric       // If this is the result expression, we may need to evaluate
4563dff0c46cSDimitry Andric       // directly into the slot.
4564dff0c46cSDimitry Andric       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4565dff0c46cSDimitry Andric       OVMA opaqueData;
4566dff0c46cSDimitry Andric       if (ov == resultExpr && ov->isRValue() && !forLValue &&
4567139f7f9bSDimitry Andric           CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4568dff0c46cSDimitry Andric         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4569d8866befSDimitry Andric         LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
45700623d748SDimitry Andric         LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4571d8866befSDimitry Andric                                        BaseInfo);
4572dff0c46cSDimitry Andric         opaqueData = OVMA::bind(CGF, ov, LV);
4573dff0c46cSDimitry Andric         result.RV = slot.asRValue();
4574dff0c46cSDimitry Andric 
4575dff0c46cSDimitry Andric       // Otherwise, emit as normal.
4576dff0c46cSDimitry Andric       } else {
4577dff0c46cSDimitry Andric         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4578dff0c46cSDimitry Andric 
4579dff0c46cSDimitry Andric         // If this is the result, also evaluate the result now.
4580dff0c46cSDimitry Andric         if (ov == resultExpr) {
4581dff0c46cSDimitry Andric           if (forLValue)
4582dff0c46cSDimitry Andric             result.LV = CGF.EmitLValue(ov);
4583dff0c46cSDimitry Andric           else
4584dff0c46cSDimitry Andric             result.RV = CGF.EmitAnyExpr(ov, slot);
4585dff0c46cSDimitry Andric         }
4586dff0c46cSDimitry Andric       }
4587dff0c46cSDimitry Andric 
4588dff0c46cSDimitry Andric       opaques.push_back(opaqueData);
4589dff0c46cSDimitry Andric 
4590dff0c46cSDimitry Andric     // Otherwise, if the expression is the result, evaluate it
4591dff0c46cSDimitry Andric     // and remember the result.
4592dff0c46cSDimitry Andric     } else if (semantic == resultExpr) {
4593dff0c46cSDimitry Andric       if (forLValue)
4594dff0c46cSDimitry Andric         result.LV = CGF.EmitLValue(semantic);
4595dff0c46cSDimitry Andric       else
4596dff0c46cSDimitry Andric         result.RV = CGF.EmitAnyExpr(semantic, slot);
4597dff0c46cSDimitry Andric 
4598dff0c46cSDimitry Andric     // Otherwise, evaluate the expression in an ignored context.
4599dff0c46cSDimitry Andric     } else {
4600dff0c46cSDimitry Andric       CGF.EmitIgnoredExpr(semantic);
4601dff0c46cSDimitry Andric     }
4602dff0c46cSDimitry Andric   }
4603dff0c46cSDimitry Andric 
4604dff0c46cSDimitry Andric   // Unbind all the opaques now.
4605dff0c46cSDimitry Andric   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4606dff0c46cSDimitry Andric     opaques[i].unbind(CGF);
4607dff0c46cSDimitry Andric 
4608dff0c46cSDimitry Andric   return result;
4609dff0c46cSDimitry Andric }
4610dff0c46cSDimitry Andric 
4611dff0c46cSDimitry Andric RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4612dff0c46cSDimitry Andric                                                AggValueSlot slot) {
4613dff0c46cSDimitry Andric   return emitPseudoObjectExpr(*this, E, false, slot).RV;
4614dff0c46cSDimitry Andric }
4615dff0c46cSDimitry Andric 
4616dff0c46cSDimitry Andric LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4617dff0c46cSDimitry Andric   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4618dff0c46cSDimitry Andric }
4619